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.
Related
I want to call an asp.net web service's from a different domain with javascript.
Ex :
I have the site "www.abc.com", I want it to call the web service on "www.xyz.com" with some javascript I load from X domain.
First I add the script with this :
document.write(unescape("%3Cscript src=%27http://myscript.com/script.js%27 type=%27text/javascript%27%3E%3C/script%3E"));
This is the script.js file :
$.ajax({
type: "POST",
url: "http://www.xyz.com/Service1.asmx/InsertIt",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: function (response) {
alert(response);
}
});
function OnSuccess(response) {
alert(response.d);
}
I know Cross-domain calls from within client-side code are a no-no in all major browsers. To achieve that, I think you can use CORS.
Use CORS, ie. set Access-Control-Allow-Origin header to
http://your-caller-domain.com in the web
In this example, I know the caller domain : www.abc.com. but in the real life, I will never know the caller domain. I know there's other way to do a Cross-Domain call, ex : JSONP. But this technique is really complexe (for me).
So I am asking is there's an easy way to achieve a Cross-Domain call ?
The best and safest method is using your server side framework to do your http requests which you can then present to your JS. This negates any cross browser annoyances that client side calls inherit.
Eg:
AJAX hits www.abc.com/getdata.ashx.
Execute your request to www.xyz.com using below method.
Return a json string or plain text. It's up to you.
WebRequest for .NET. There is an example at the bottom.
Also look at HTTP handlers (.ashx) for doing requests. Not essential, but it's good to learn.
Check the documentation bellow, u'll be able to perform cross-domain requests
http://api.jquery.com/jquery.getjson/
$.getJSON( "http://www.xyz.com/Service1.asmx/InsertIt", function( data ) {
alert(data.d);
});
I'm working on an application which use ajax call to get html from the server.
When I run it on the server, everything works fine.
But when I'm running on a localhost, I've a 'Access-Control-Allow-Origin' error.
I looked arround and it seems like using jsonp could be the solution.
So, my ajax call looks like that:
$.ajax({
url: url,
dataType: 'jsonp',
crossDomain: true,
type: 'GET',
success: function(data){
// should put the data in a div
},
error: function(){
//do some stuff with errors
}
});
I get html from the server, but I always have this error:
Uncaught SyntaxError: Unexpected token <
Is there a way to wrap the jsonp response in html?
Thanks!
You can't use JSONP to grab an HTML document. You need to wrap your HTML in a JavaScript variable. JSONP has some very specific requirements to make it work properly, including a callback function/attribute. If you're not in control of the server hosting the target page, you won't be able to make it work. This is a security precaution to prevent a random page from being able to steal your personal information from sites you're logged into via an AJAX call.
UPDATE
I read your question more thoroughly. It sounds like your problem is that you're in a development environment that doesn't have the resource in question. JSONP isn't the answer because it's a lot of trouble to get running just to make your page work in development. You should create a local copy of the target HTML and grab it using a relative or server-absolute URL such as "/the/page/i/need.html" instead of "http://myserver.com/the/page/i/need.html"
If you want to get the data by jsonp, then the server side need to support jsonp.
There is no way just change the dataType to get the data.
If the server side doesn't support jsonp, then you need to make a proxy in your localhost.
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/
I have an api set up on another domain, domain B (api.domainb.com), and want to make a call to it from domain A (www.domaina.com). However, when I do a call from domain A to domain B via jquery ajax, jquery ends up trying to call www.domaina.com/api.domainb.com which obviously will return an error. Here is the relevant javascript code
$.ajax(
url: 'http://api.domainb.com',
type: 'GET',
dataType: 'jsonp',
data: {hello: 'world'},
crossDomain: true,
success: function(data){
alert(JSON.stringify(data))
},
error: function(error){
alert(JSON.stringify(error))
});
Eventually, the code in domain A and domain B will be on the same domain, but for now, I need to make a cross-domain call. Any suggestions as to how to make this work?
You're just missing the protocol so that the Ajax call knows it's a different domain and not a relative URL. Try using url: 'http://api.domainb.com'.
You cannot make cross-domain calls; browsers simply do not allow it in general. However, the reason you're seeing the behavior you describe is that your URL is missing the "http://" prefix.
There are some things you can do with fairly new HTML5 APIs to sort-of "get permission" to do cross-domain calls.
edit #Dan points out correctly that while XMLHttpRequest (what people usually call "ajax") won't do cross-domain stuff (CORS aside), it's possible to leverage the fact that <script> tags can reference other domains in order to put together a service. The server-side code has to be different, however. (That's usually called "JSONP".)
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);
}
});