GithubHelp home page GithubHelp logo

moonscript / jquery-ajaxtransport-xdomainrequest Goto Github PK

View Code? Open in Web Editor NEW
951.0 46.0 321.0 406 KB

jQuery ajaxTransport extension that uses XDomainRequest for IE8 and IE9.

License: MIT License

JavaScript 100.00%

jquery-ajaxtransport-xdomainrequest's People

Contributors

cbaxter avatar devongovett avatar fidian avatar jcruz2us avatar moonscript avatar riddla avatar tracker1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-ajaxtransport-xdomainrequest's Issues

Not working with sending JSON

I wrote following code:

var config = {
    'appid': gaeAppId,
    'passwd': gaePassword,
};

$.ajax({
    type: 'POST',
    url: 'http://127.0.0.1:8084/config?cmd=set_config',
    data: config,
    dataType: 'JSON',
    success: function(result) {
        console.log(result);
    }
});

This works fine in Chrome, but not working in IE 8.
The Ajax request is successful in IE 8, but the server response that didn't receive the POST variable appid.

So I wrote the code as the document said:

var config = {
    'appid': gaeAppId,
    'passwd': gaePassword,
};

$.ajax({
    url: 'http://127.0.0.1:8084/config?cmd=set_config',
    data: config,
    contentType: 'text/plain',
    type: 'POST',
    dataType: 'json'
}).done(function(result) {
    console.log(result);
});

This code not working in Chrome and IE.
The Ajax request is successful in the two browsers, but the server response that didn't receive the POST variable appid.

I think there's something wrong with your code.
Please help me.

Missing main and ignore entries in bower.json

bower jquery.xdomainrequest#~1.0.2 invalid-meta jquery.xdomainrequest is missing "main" entry in bower.json
bower jquery.xdomainrequest#~1.0.2 invalid-meta jquery.xdomainrequest is missing "ignore" entry in bower.json

IE 8: In case error, Not able to get Error Message

I am using IE 8 and CROSS
I am not able to get error message in case any API call fails. I also tried returning JSON results.

Here are complete request and response objects. How to get Error message in this case.

Request

POST http://xxx/Delete/?key=233219f4
Accept: /
Origin: http://localhost
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; WOW64; Trident/4.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; HPNTDFJS; InfoPath.3)
Host: rahul
Content-Length: 0
DNT: 1
Connection: Keep-Alive
Pragma: no-cache

Response

HTTP/1.1 417 Expectation Failed
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 101
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: *
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 21 Aug 2015 12:23:41 GMT

File Delete Operation Failed : Folder not empty

JSON response

HTTP/1.1 417 Expectation Failed
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 86
Content-Type: text/html
Expires: -1
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: *
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 21 Aug 2015 12:57:13 GMT

[{ "msg" : "Folder with fileID =233219f4 is not empty " }]

Package appears a bunch of times in bower search

Very small thing but I noticed the package shows up a bunch of times in bower search:

$ bower search XDomainRequest
jQuery.XDomainRequest git://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest.git
jquery.xdomainrequest git://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest.git
jquery-ajaxtransport-xdomainrequest git://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest.git

I just arbitrarily picked one but if possible it might be a bit nicer if it just had one (jquery-ajaxtransport-xdomainrequest seems most consistent with other package names).

Just wanted to say thank you

This isn't a bug report, but I just wanted to say thank you.

This script just saved a rather large project of mine.
If you should visit Munich or Augsburg any time, I owe you a drink.

Cheers,
Florian

v1.0.3 release

Hi, I'm using rails-assets to get bower packages into my application, and I get an error message because the bower.json file is not included in the package. I can see you included it with v1.0.3 but it's not released (tagged) yet and thus not available from rails-assets.org

It'd be great if you could release it so we could get rid of those errors ;)

Change Content-Type of text/plain to something else

First, thank you a lot for you work!

I'm having a problem, it is very clear that when POSTing data will always be sent with a Content-Type of text/plain. But I need to send a request using application/x-www-form-urlencoded Content-Type.

Are you in the future going to provide a support for others types other than text/plain?

Thank you!

Notseeing Content Type in IE

I understand on IE we default to contentType: 'text/plain' however I do not see this in the HTTP request hedder.

Jay

Text Status and Error Thrown show "error"

I am implementing a ajax call from a page generated from a wordpress website. This wordpress website loads jquery version 1.10.2 from its core. Initially the ajax call made using jQuery wasn't working. So I used the jqXHR.fail method to output the textStatus and errorThrown.
Later, I tried out crossDomain: true and also jQuery.support.cors = true statements with no success. I came to know about these statements from a discussion on StackOverflow (http://stackoverflow.com/questions/5241088/jquery-call-to-webservice-returns-no-transport-error). I ended up using jquery.xdomainrequest.min.js after being redirected here from StackOverflow.
I still face an error. I get textStatus as "error" and errorThrown as "error" inside the jqXHR.fail(function() {...}) piece of code.
Please find below the code I'm working on

            <!--[if lte IE 9]>
            <script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.0/jquery.xdomainrequest.min.js'></script>
            <![endif]-->
            <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.validate.js"></script>
            <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/dateFormat.js"></script>
            <script type="text/javascript">
            jQuery(document).ready(function() {
        jQuery.validator.addMethod("nospace",function(value,element){
            return value!="" && value.indexOf(" ")<0;
        },"No spaces allowed.");

            jQuery("#mktForm_1012").validate({
            rules: {
                Email: {required: true, email: true, nospace: true},
                uPassword: {required: true}
            },
            messages: {
                Email: {required: "Email is required.", email: "Must be a valid email."},
                uPassword: {required: "Password is required."}
            },
            onfocusout: false, onkeyup: false, onclick: false,
            success: function(label) {
                label.html("");
            },
            submitHandler: function(form) {
                //alert("submitHandler");

                        //ajax call 
                        //jQuery.support.cors = true;//if jQuery.ajax({crossDomain: true}) doesn't work below
                    jQuery.ajax({
                        url: "<?php echo $PRODUCTION_URL; ?>/ExampleService", 
                        type: "POST",   
                        //crossDomain: true,
                            data: {
                                action: "getHash",
                                    //tried following looking at issue #25 at https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/issues/25
                                    Email: jQuery("#Email").val()//function() { return jQuery("#Email").val(); }
                                    },
                            success: function(data) {
                alert(data);//isn't showing up

                //do stuff with data here.

                //submit the form
                  form.submit();
                    },
                        dataType: "text"
                    }).done(function(data, textStatus){
                        alert("success:" + textStatus);//isn't showing up
                    }).fail(function(jqXHR, textStatus, errorThrown){
                        alert("failed with : {textStatus: " + textStatus + ", errorThrown: " + errorThrown + "}");//textStatus: error, errorThrown: error is the output
                    });//End ajax call
                }//end submitHandler
        });//end jQuery(form).validate()

    });//End jQuery(document).ready(...) call


            </script>
            ```

I am looking for getting this resolved at the earliest and I have run out of options.

HTTP Post with formData

Hi,
Without FormData POST is working fine IE8,IE9.
But when i provide form data it is failing.
Can you update your example with form data.

Why Always asynchronous?

Is there any reason of keeping the ajax request asynchronous while using ajaxTransport-XDomainRequest.

I have following request to make -

       $.ajax({
            type: 'GET',
            async: false,
            url: url,
            dataType: 'text',
            success: success,
            error: error
        })

But the request fails on IE9 with following error Access is denied.
And when I removed async check in the if condition in jquery-ajaxTransport-XDomainRequest.js

if (options.crossDomain && getOrPostRegEx.test(options.type) && httpRegEx.test(options.url) && sameSchemeRegEx.test(options.url)){

And it works perfectly.

IE8 Always Failing

I have included your plugin and am trying to run something like this:

$.ajax({
    type: 'GET',
    url: 'http://10.0.0.2/',
    dataType: 'text',
    data: getParams(),
    success: successCB,
    error: errorCB
});

I continuously get an error. For some reason xdr.onerror is always called. Do you know what the issue is?

responses.html set instead of responseText

In my project I use this plugin for cross domain and ie9 but when I get a text/html respons the responses.html is set and not the responses.reponseText.
When I check the Ajax response the responseText is null in this case.
Looking at the XMLHTTPRequest docs, responseText is the correct property to use.
When I change:
if (userType === 'html' || /text/html/i.test(xdr.contentType)) {
responses.html = xdr.responseText;
}
to:
if (userType === 'html' || /text/html/i.test(xdr.contentType)) {
responses.responseText = xdr.responseText;
}
all works fine here.

I see in previous changes "Accommodate HTML dataType, as requested in PR 13" you added this

Bower package

Hi,

Thanks for this script, it works like a charm!
I just wanted to know if you considered registering it as a bower package?

Cheers

Issue with gzip compressed data

Hi,
This plugin is amazing and it worked for me except for one situation. When the return data is gzip compressed it is not working. Please look in to this issue and give me a solution.

IE9 aborts requests

IE9 will sometimes abort requests. This is a know issue and the fix is to define a handler for all events.

POST body not sent

On lines 75 and 76 there are two versions of the xdr.send call, one commented and one not. The one that is there will not send an HTTP POST body with the request.

Bower ignores un-minified version

Why is the debug version of the script ignored in the bower file? I prefer to pull in debug versions of bower dependencies and handle bundling and minification in my own release process. This prevents that. Can you remove the ignore for that file?

Post request not working in IE9

I've set up a cross domain POST request that is working in all browsers except IE9 (not worried later versions of IE). When the request is sent from IE9 Developer Tools show the correct request body was sent but when it shows up on the server side the request body is empty.

I should mention that I'm using a Backbone model to submit the request with Model.save() and I have the following ajax setup:

  $.ajaxSetup({
    cache: false,
    crossDomain: true,
    contentType: 'text/plain',
    dataType: 'json'
  });

On the server side I have the following headers:

"Access-Control-Allow-Origin", "*"
"Access-Control-Allow-Headers", "X-Requested-With, Content-Type"
"Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"

code bug

if(... !sameSchemeRegEx.test(options.url))

This code is not crossdomain?
This plugin does not work on ie8.
sample:
sameScheme = "http://"
options.url = "https://blabla.com"
this logic always false

PUT, DELETE

Hi, is it possible to patch this code to be able to do PUT and DELETE requests too?

Suggestion : Add progress events

Something such as

    xhr : function() {
            var xhr = new window.XMLHttpRequest();
            //Upload progress
            xhr.upload.addEventListener("progress", function(e) {
                if (e.lengthComputable) {
                    var progress = e.loaded / e.total;
                    //Do something with upload progress
                    console.log("Up", progress);
                }
            }, false);
            //Download progress
            xhr.addEventListener("progress", function(e) {
                if (e.lengthComputable) {
                    var progress = e.loaded / e.total;
                    //Do something with download progress
                    console.log("Down", progress);
                }
            }, false);
            return xhr;

Useful when uploading/downloading large files.

Thanks for your great script!

::Guillaume::

Post Not working in IE9

XDomainRequest does not support Content-Type header anymore.
Server can not read Content-Type header any more

Parse error when loading SVG

I tried to get some SVG from via CORS and the ActiveXObject seems to be unable to parse it. I double checked with http://validator.w3.org/ to make sure it's valid.

Since the oldest IE I have to support is IE9 I just switched to DOMParser and that worked just fine, but maybe there is another way to fix this for people who need to support older versions of IE.

Request fails when dataType not specified.

Hi, thank you SO MUCH for this plugin, works nicely, just one detail:

jQuery.ajax({
            url:"http://example.com/test.php",
            dataType: "text",
            type:"POST",
            success:function(responseText)
                {
                    alert(responseText);
                },
            error:function(jqXHR,txtStatus,txtError){
                alert('error: ' + txtError + txtStatus);
            }
        });

The code above gives a "No transport" error when I do not specify "dataType: "text"" rather than guessing the datatype as specified by jQuery.

Tested in IE 9 on Vista. Works perfectly in at least Chrome (not tested others, but should work.)

Working example GET JSON not working

When I click the link for GET JSON the page just alerts "error". I looked at the used url and it seems that the JSON you used to get there is not on the server anymore.

XDR Post

I am attempting to POST a form.serialize(); but the page receiving the post gets nothing.

I know the call works because I can echo 'Test'; and it alerts me back with Test but when I am trying to grab the posted items its empty.

I tried changing content types but no luck. This is only happening in IE9. I have not tried anything less then that but above this works fine.

Any help would be appreciated. Thanks!

Doesn't work with protocol-relative URLs

Right now the module is hard-coded to enforce the usage of HTTP/HTTPS, as well as ensuring that the current page and request URL have matching schemes. This is just done using simple regex, and doesn't account for a protocol-relative URL that doesn't specify the protocol (http://www.paulirish.com/2010/the-protocol-relative-url/).

I find these types of URLs useful and use them frequently. Just thought I'd mention it! Works beautifully once I removed the checks, so thanks!

Joel T

POST XDR With Headers and jQuery

Hi Everyone,

Moonscript, I found my way to #1 upon encountering an error 500 using your inplace XDR.
It does seem to go a bit further than vanilla $.ajax, so it's a little better.

On 11th of October, you pointed out that content-type as text/plain was a requirement of XDR, and supplied a few links:

@jeroenooms More info in item number 4 on this page about posting as text/plain.

I'm about to parse as json server side, and wrap all text/plain calls in this little preprocess -step, but I'm hesitating, because the link you supplied states that "No custom headers may be added to the request"
Now, do I have to work around this as well, effectively turning the entire request into a plain-text message?

Thanks in advance, and thank you for your work.

sends no data

Hi,
First of all thank you firs this lib! It has already saved my life once.

But I need your help so it saves my life a second time.

I have a js/html5 app that uses this lib and everything works well.

I tried to use it with requirejs and suddenly it does not work :( My server does get a call but with no data instead of the parameters needed. Do anybody have an idea why? what should I do ?

Issue with empty response

I get an parserrerror, when the response is empty.

In detail, I send a JSON request to the server. The response is
204 No Content
Content-Length:0

In this case the xdr.contentType is "text/html". Therefore htmlRegEx.test(xdr.contentType)) is true. So responses.html is set, and the later concversion to JSON fails.

I fixed it with an additional check for empty responses:

if (userType === 'json' && xdr.responseText.length == 0) {
status.code = 204;
status.message = "No Content";
responses.json = null;
} else if (userType === 'html' || htmlRegEx.test(xdr.contentType)) {
responses.html = xdr.responseText;
} ...

Maybe you can add it (or something similar) also to your coding?

[enhancement] Add missing bower.json.

Hey, maintainer(s) of MoonScript/jQuery-ajaxTransport-XDomainRequest!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library MoonScript/jQuery-ajaxTransport-XDomainRequest is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "MoonScript/jQuery-ajaxTransport-XDomainRequest",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Headers missing

Hi everyone,

It's strange - when i included jQuery.XDomainRequest, IE discards (some) of the headers. Not as many as if I did it directly through XDR, in which case I wouldn't get any custom headers.
I send off my request as such:

$.support.cors = true;
 return $.ajax({
  type: "POST",
  async: true,
  url: _url,
  cache: false,
  crossDomain: true,
  contentType: "application/json; charset=utf-8", // Request
  data: JSON.stringify(_data),
  dataType: "json", // Expected response (json d wrapping xml)
  success: function(msg) {
            if (msg.hasOwnProperty("d")) {
             // Leave the .d behind and pass the rest of 
             //  the JSON object forward.
             _success(msg.d);
            } else {
             // No .d; no transformation necessary.
             _success(msg);
            }
           },
  error: _error,
  beforeSend: function (request)
  {
   request.setRequestHeader("Authorization", "basic " + Base64.encode(userid+":"+pwdhashed));
  }
 });

This is the diff between the two (lines shown are what the approach has extra)
I'm not sure about the Origin and Cookie header, but I would like Referer, Authorization and Content-Type.

Original:
 Referer: http://bimco.org/common/TestPage.aspx
 Authorization: basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==
 Content-Type: application/json; charset=utf-8
 Cookie: __utma=50439994.1373781375.1408004068.1408371010.1408434254.5; __utmz=50439994.1408004068.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)

jQuery-ajaxTransport-XDomainRequest:
 Origin: http://bimco.org

Only SERVERS should set SERVER statusCodes

Mostly great work on this! However... you can't just fail to parse something and throw a 500 when it fails. I was looking in my server logs to find out what was wrong before I realized you guys were just returning 500 errors willy nilly. I would recommend that you stop that :-)

Can I pass http header with the ajax request

Is it possible to do following request

   $.ajax({
        dataType: 'json',
        method: 'POST',
        url: url,
        beforeSend: function (xhr) {
            xhr.setRequestHeader(headerKey, headerValue);
        },
        success: callback.success,
        error: callback.error,
        xhrFields: {
            withCredentials: true
        },
       crossDomain :true,
       async: true
    });

Accept header is always set to */*

Hey @MoonScript, I noticed that the Accept header is always set to */*, even when the dataType was specified.

I couldn't find the cause yet. Is that an expected behaviour?

You can reproduce this with an IE9 and your jsfiddle.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.