jQuery Cross Domain Post in IE with Data - javascript

CORS works perfectly in my application right now for Chrome, Firefox. Using this plugin https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
I was able to get CORS requests working in IE also like so:
$.ajax({
url: url,
type:"POST",
dataType: "json"
});
However when I try to send data in the POST request, such as:
$.ajax({
url: url,
type:"POST",
dataType: "json",
data: {test: 5}
});
It does not work. Has anyone managed to get IE to make CORS requests that have POST data in them?
Thanks!

I noticed in the jQuery-ajaxTransport-XDomainRequest source, the send function call which passed userOptions.data was commented out and the active send() call has no parameters:
I was running into the same issue with POST and no data getting to the server. So I uncommented the send with data call as so:
xdr.send(userOptions.data);
//xdr.send();
However it still did not send data. So I changed the type from 'POST' to 'GET and updated my server code to handle it. Well it actually worked! I have not done more testing and I'm not sure if GET will be acceptable for the code I'm developing.
UPDATE: I tested further and using send() or send(userOptions.data) seems to make no difference on IE. It was the change to GET that made it work so POST is still an issue if you must use POST in your ajax code.
Since I'm new to cross domain ajax posting of data (IE being the problem), I'm hoping others will post their findings so it works for POST as well as GET. Thanks for all your help!

Related

Cross domain request using jsonp: from https to http

I have following problem: I need to send some data from page on my site (https://test.com) to another one (for example http://anotherdomain.com). User just enters data to the text box and clicks a button. Script on this page will handle click event and send GET request (using jQuery ajax method) to the http://anotherdomain.com.
var enteredValue = $('#MytextBox').val();
function jsonpCallbackFunc(data)
{
}
$.ajax({
url: 'http://anotherdomain.com/qwerty/ajaxpage.php',
data: { valuefield: enteredValue },
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallbackFunc',
success: function (json) {
// some code
}
})
I received next error using FireFox - "Blocked loading mixed active content http://anotherdomain.com/qwerty/ajaxpage.php...".
The same situation for IE9 and Chrome.
Question: how can we resolve this issue? Can we just allow this script for only one site or maybe we can use another piece of code (not jQuery+jsonp)?
Thank you in advance for the help.
P.S. From "http"-site this code works as expected.
Update:
We resolved the issue using another "https"-url (https://anotherdomain.com/qwerty/ajaxpage.php). We had tried use it before, but it had untrusted certificate. Now it works correctly. Thank you for the help and advice.
This happens due to CORS. When you request to other domain, a preflight request may happen on condition for the ajax calls. You are using jQuery and hence custom header will set in your request. So use
Access-Control-Request-Headers
Access-Control-Allow-Origin
Access-Control-Allow-Methods
Please refer cors and its implementation.
This should also need to be allowed in server, try to add this where you process your request
<?php header('Access-Control-Allow-Origin: *'); ?>
Hope this may help

Chrome shows Access Control Allow Origin error

I'm using jquery to post data to a server, the server received the data, but the chrome still shows the error :
XMLHttpRequest cannot load `myServer:63373/api/sendData`. Origin `myServer:63385` is not allowed by Access-Control-Allow-Origin.
Here is my js code:
$.ajax({
type: 'POST',
url: 'myServer:63373/api/SendData',
crossdomain: true,
async: true,
data: myData,
dataType: 'json',
success: function(){ alert('success'); }
});
The strange thing is that the 'success' shows up after the request, and the server did receive the data, but then the error message shows up in the console. Is there any way to avoid this message?
Thanks for all you answers above but I think I've found the way, before I solve this I was trying to use two ways, Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method
with the 87 votes and 32 votes, I found the answers at two different places, and both applied them, but it didn't work. Early this week, I tried to delete the code in the web.config and just left the code in C#, it works! Can't believe these two solutions have confliction.
Anyway, hope this could help others.
"not allowed by Access-Control-Allow-Origin" is the reason. Put simply, you can't normally do an XHR call to a different domain/port/protocol from those of the webpage your javascript was included into.
Modern browsers allow you work around this with permission from the server administrator.
You make your Ajax request with the XHR2 API (http://www.html5rocks.com/en/tutorials/cors/)
The on the server side, you need to emit the following headers to allow access from the domain that served the page that included your javascript:
Access-Control-Allow-Origin: http://your-page-domain.com
Access-Control-Allow-Credentials: true
if situation are
your script is hosted on another server
or subdomain
or try to hit url with another port
this is cross-domian request. jquery can not fulfill cross-domain request.
if this is your issue , then you should use jsonp for this "jsonp " allows cross domain request.
try to do this with using jsonp.
for jsonp every call has a callback means there will be a value in url
and you have to send respnse with this call back in php
means try this:-
$.ajax({
type: 'POST',
url: 'myServer:63373/api/SendData',
crossdomain: true,
async: true,
data: myData,
dataType: 'jsonp',
success: function(){ alert('success'); }
});
and in php
wrap your response in $_GET['_callback']."(".$response.")"; and echo it
you will get response in json .

$.ajax and $.getJSON for json and jsonp fail to properly get response from 3rd party server

As the title says I'm attempting to retrieve a json from an api given by the site. I've tried a variety of things now and have gotten varied results. I want to be able to retrieve and parse the json to get the information that I want out of it. Here's what I've tried:
1) $.ajax()
Code chunk (runs when a button is clicked):
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
alert('Success!');
}
});
This produces a "Origin null is not allowed by Access-Control-Allow-Origin." error and does not get a response from the server (for Chrome or FF, I don't care about IE since this is a small project for my use). Looking around I thought the problem might be that I need it to be a jsonp dataType since I am trying to connect to an outside website. This lead me to try #2
2) $.ajax with jsonp dataType
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function(data) {
alert('Success!');
}
});
I also appended "&callback=?" to the end of "url" that I give to the function. Using Chrom's Dev Tool I can see a response from the server this time but the alert never displays. I used JSONLINT to confirm that the response was a proper json (it is) and I've tried setting the json to a variable so I can play with it (along the lines of initializing a variable earlier in the script tag [var response;] and trying to assign the json to it[response = data;]). This produced undefined when I tried to alert(response); later on (I don't believe the response=json; bit ever got called for some reason).
I've also tried using $.getJSON but looking at the api for it it apparently just runs $.ajax anyway (I luckily got the same responses/errors when trying json vs jsonp for $.getJSON as I did when trying $.ajax). When I try as a jsonp Chrome (FF doesn't produce this error) shows a "Unexpected Syntax Error: Unexpected token :". This makes me think that the site I'm trying to talk to doesn't have jsonp working and I can't access the third party site as just a json request. The link talks about how setting the server to return as application/json rather than text/html, like I get from my response, fixed the problem for them (but again, I'm trying to access a third party site and thus I can't access the server).
I've tried this in Chrome and FF and looked at Dev Tools/Firebug for each and seen the same thing (though FF doesn't produce the origin error, but that's apparently a bug with Chrome anyway).
Also: I've taken the json response returned and run $.parseJSON on it and been able to grab various pieces but how can I access the json once I get $.ajax/$.getJSON working?
Any thoughts/solutions would be greatly appreciated.
I once got the Unexpected Syntax Error: Unexpected token : error too.
It seems like the site doesn't support Cross-Domain-Loading.
What API are you trying to use?
More than likely the response is valid JSON, but not valid JSONP. The 3rd party server has to support JSONP for you to get a JSONP response. If you do not have control of the 3rd party server, your only real option is to use a server-side proxy or YQL.
Don't use JQuery AJAX for JSONP.
Use <script type='text/javascript' src=' URL_GOES_HERE&callback=BLAH '></script> which will surround the json object with a javascript method call, and you can then use the data from the 3rd party source.
http://en.wikipedia.org/wiki/JSONP
Try the JSONP plugin. It's one of the few plugins I recommend, only because it's light and does what it should. It also allows you to check for responses other than success. Works great for JSONP, and resolved an issue I had with using a subdomain and not getting proper error responses (which subsequently just halted the code).
Get it Here.
Did you tried this way ?
$.getJSON( url + "?callback=?", function(data) {
console.info(JSON.stringify(data, null, 2));
});
This is basically how I'm managing my JSONP callback to http://freegeoip.net/json/

JSONP communication in a Google Chrome extension

I'm writing a Google Chrome extension. I want to use jsonp cross-domain communication with jQuery. Here is the ajax code:
$.ajax({
type : 'POST',
url : $(this).attr('action'),
data : $(this).serialize(),
contentType: 'application/json; charset=utf-8',
dataType : 'jsonp',
success : function() {
alert('A');
}
});
This calls this URL:
http://sgsync.dev.kreatura.hu/api/signup/?callback=jQuery1710883696963544935_1327347078860&nick=&pass=&_=1327347087371
The server answers 200 OK with this data:
jQuery1710883696963544935_1327347078860({"messages":["Minden mez\u0151 kit\u00f6lt\u00e9se k\u00f6telez\u0151!"],"errorCount":1})
After that, i got this error message:
Can't find variable: jQuery1710883696963544935_1327347078860
I tried everything and i can't understand the problem. Please help me!
Note that i programed the server-side code, so there could be a problem with that too.
Thanks in advance!
Part of the reason this is so confusing is because jQuery API confuses the issue of Ajax calls vs JSONP calls. When using $.ajax with dataType: 'jsonp' this does not do an Ajax call (no XHR communication is used) it instead uses dynamic script injection with a callback. This means that the type: 'POST' will have no meaning (since dynamic script injection only works as a GET would work) and that all of the data will be encoded into the URL of the request as opposed to being send over as a post body. If this is truly intended to "POST" data then JSONP should not be used (since sensitive data will be sent in clear text).
As mentioned in one of the comments, this issue was addressed in this answer with regards to JSONP requests from Chrome content scripts and using XHR from a content script.
JSONP request in chrome extension, callback function doesn't exist?
With regards to Chrome Extensions, they do force you into a sandbox when using the "conten scripts" in a chrome extension. You can remove the dataType: 'jsonp' form the request in the Chrome Extension content script and this call should work. If that does not work, you might trying making the call directly using the XHRHttpRequest:
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.open("POST", $(this).attr('action'), true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert("A");
}
}
xhr.send($(this).serialize());
With regards to other browsers, I am not sure how each of their specific plugin enviroments handle making cross domain XHR calls (or if they even allow it in the first place). This is something that is NOT allowed from normal browsers (unless using something like easyXDM).
Have a look at this question and my answer as I think it might give you a solution...
Auto-load bookmarklet when in webpage as a Google Chrome extension
Basic concepts of JSON-P:
Insert a script tag which loads an external javascript file.
That file does nothing else than execute a pre-defined function, with the data from the server.
How to make it work:
First create a function, bound to the global object (window):
window.processMyData = function processMyData(data) {
console.log(data);
}
Then insert a script tag to the page:script = document.createElement("script");
$('<script></script>')
.prop({'type': 'text/javascript', 'src': 'http://your.url?with=possible&data=in_it'})
.appendTo('body');
You see? No need for the $.ajax wrapper, JSON-P works differently.
Good luck!
Edit: as a response to Duskwuff I would like to add that I don't mean to say $.ajax is bad, or not useful. I am not here to give you a jQuery code snippet, I am trying to let you understand your problem, with the help of a bit more basic javascript / html. JSON-P is not just JSON with a P added, it's completely different from a normal request.

jQuery 1.5 only sends GET requests in ajax method

I am trying to make a PUT request to a RESTful web service, however, it appears that jQuery 1.5 does respond to any changes in the 'type' setting. The request is sent as a GET no matter the value in 'type'. In jQuery 1.4 this isn't a problem.
Here's my code:
$.ajax({
type: "PUT",
url: "https://api.somesite.com/v1.0/people/" + individualID + "/",
dataType: "jsonp",
data: $("#editProfile").serializeArray(),
cache: "false",
success: function(data,textStatus,jqXHR) {
$.modal.close();
},
error: function(jqXHR,textStatus,errorThrown) {
alert("Error!");
}
});
As far as I'm aware, you can't make a JSONP request via PUT. Since JSONP works by injecting a <script> element pointing to the remote domain, that request will always be a GET request.
If you absolutely must make a PUT request to a remote domain, you'll need to either use a server-side proxy on your local domain or look into CORS if you don't need IE support.
From the jQuery.ajax() docs:
The type of request to make ("POST" or
"GET"), default is "GET". Note: Other
HTTP request methods, such as PUT and
DELETE, can also be used here, but
they are not supported by all
browsers.
Perhaps with some additional browser info we can figure out what is causing the problem, but for now it seems jQuery does not want to guarantee functionality except on GET and POST. This is surprising for me to find out =)
How do I PUT data to Rails using JQuery maybe?
edit: oups, you didnt say the webservice was in Rails. But it might support something like that too. Did you try just sending a POST request?
I was struggling with something similar. I have been able to send a PUT successfully pre 1.5 but stopped working with 1.5. I know there was a big change to how the ajax stuff in handled in 1.5 so I'll look into that next.
When it did work it worked fine for me in safari, firefox & chrome. When it works you'll first get an OPTIONS being sent and as pointed out before your server side will have to response satisfactorily to the OPTIONS request a la CORS. Here is a piece ot test code that does work for me pre 1.5 so it is possible. As an aside I was not able to get firefox to cache the OPTIONS response client side. The other browsers did.
http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
var url = 'http://api.example.com/rest/action?key=123ABC&data={"value":55}';
$.ajax({
type: "PUT",
url: url,
data: {},
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(msg){
console.debug(msg);
}
});

Categories