When I first load a page I make an ajax call to bring some data for the client-side. The call is made to a different domain and the answer comes as JSONP. The call looks similar to:
$.ajax({
type: "GET",
url: url + "?callback=?",
dataType: "jsonp",
contentType: "application/javascript;charset=UTF-8",
async: true,
success: successCallback,
error: errorCallback,
cache: true,
jsonpCallback: jsonCB
});
'application/javascript' would be the possible culprit here as I did my research on the subject but this is present in a previous version of the code which never had this problem.
On all browsers except IE I receive the following error (sometimes, usually the first time and then the problem dissappears) :
script5007 object not found - line 1, char 1
The JSONP received looks like that:
func({"result":"abc"})
The param of the func is a valid JSON as I checked this using jslint.
Any idea will be highly appreciated! Thank you!
You're missing the object brackets { } inside your $.ajax function. Modify it like so:
$.ajax({
url:'',
contentType: 'application/javascript;charset=UTF-8',
crossDomain:true
......
});
The jQuery $.ajax method either takes a url parameter and an optional parameter of additional options specified as an object, or an object parameter including the url.
Related
My Code is as below for Javascript
$.ajax({
type: "POST",
url: "page/rSales.aspx",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function (res) {
alert('Success');
},
error: function (res) {
alert('Fail');
}
});
I use http tracer tools to trace whether or not the parameter is passing on to my backend - and it is not. I have also tried adding contentType: 'application/json; charset=utf-8', adjust parameter by adding colon, but none of it is working.
My Backend code C# :
Request.Params["ListID"].ToString();
It always returns null, due to the parameter not passing on. I am wondering what is causing this problem and how should I resolve it.
The Request.Params collection does not support JSON requests, so you have to parse response body manually (or send it as form data).
https://msdn.microsoft.com/en-us/library/system.web.httprequest.params(v=vs.110).aspx says "Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items."
For firefox you declare var event; before your ajax call this is very well known issue in firefox.
I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON
I'm not sure if this is crossdomain issue or not. I'm trying to use $.ajax to load file. But some file I get readyState=4 and some file I get readyState=1
This is the path where I run my jasmine test
file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html
And in the code I used jQuery.pyte to require relevant file. But it's stuck at readyState:1 when the code comes to $.ajax
if I do something like this, it returns readyState=4 correctly and print out the content inside SpecRunner.html
$.ajax({url: 'file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html', async: false}).responseText
but if I do something like this, I only get readyState=1 and nothing is returned.
$.ajax({url: 'file:///home/myname/development/path1/path2/src/main/webapp/static/js/core/application/FileThatIWant.js', async: false}).responseText
you should avoid file:// URLs in general, because browsers do not allow them in many different places. Try XAMPP it's a simple to use local webserver, you will definitively need one.
Yes, this is a cross-domain issue. You can solve this problem by forcing jQuery to use crossdomain AJAX (JSONP).
$.ajax({
url: "yoururl",
cache: false,
crossDomain: true,
data: {}, //put your GET parameters here or directly into the url
dataType: "jsonp",
processData: true,
success: function(data, textStatus, jqXHR){
//This will be executed if it worked
},
error: function(data, textStatus, jqXHR){
//This will be executed if it failed
},
timeout: 4000, //You can put any value here
traditional: true,
type: "GET"
});
jQuery will automatically add a callback parameter containing a random string (&callback=XXXXXX).
The target URL needs to output the following:
XXXXX(your_output_encoded_in_JSON);
where XXXXX is the random string. The PHP code to do so is:
echo $_GET["callback"]."(".json_encode($myoutput).");";
Make sure that the PHP (or whatever language you're using) page ONLY outputs that!
If, instead, the page you are querying is not built dynamically, such as an HTML page, you need to add the following options to the $.ajax options object:
jsonp: false,
jsonpCallback: "mycallback",
mimeType: "text/javascript",
Your .html file will contain something like this:
mycallback("<html><head></head><body>TEST PAGE. This is a double quote: \" and I didn't forget to escape it!</body></html>");
This technique is very handy to bypass the strict crossdomain restrictions hardcoded in browsers, but it only supports GET parameters. XMLHTTPRequest v2 supports cross-domain requests, but we won't be able to assume that all users have a XHRv2-compatible browser before at least 2016.
http://caniuse.com/xhr2
So, I've been battling with Javascript for a little while now and I have a weird error which is probably something simple. I have an ajax request like so:
$.ajax({
url: 'http://www.hahaha.com/api/v3/acts',
crossDomain: true,
jsonpCallback: 'handlejson',
async: false,
jsonp: 'callback',
dataType: 'jsonp',
type: 'GET',
success: handleActs,
error: handleError
});
Which works fine and calls the callback with no problems. Now, if I add this request directly underneath:
$.ajax({
url: 'http://www.hahaha.com/api/v3/performances',
crossDomain: true,
async: false,
jsonpCallback: 'handlejson',
jsonp: 'callback',
dataType: 'jsonp',
type: 'GET',
success: handlePerformances,
error: handleError
});
I get a "parsererror" on the first request and the second one succeeds. Anyone have any ideas as to why it's doing this? Can a jsonpCallback only have one request called on it?
I don't think it works to have two AJAX calls referring to the same jsonpCallback - I think jQuery puts a callback function in the global namespace, then removes it when it's called - so it won't be around for the second set of loaded data. I wouldn't have thought this would matter with async set to false, but it looks like it does.
At first I couldn't figure out why you were setting jsonpCallback at all, but testing seems to indicate that the API you're using strips anything other than [a-z] from the callback name :(. So you might try this with jsonpCallback set to 'handlejsona' in the first call and 'handlejsonb' in the second call.
This approach seems to work here: http://jsfiddle.net/nrabinowitz/H7zYt/
I am getting a javascript error on firefox 3.5, when trying to call an ajax method.
Please find the error below:
XML Parsing Error: no element found Location: moz-nullprincipal:{1a2c8133-f48f-4707-90f3-1a2b2f2d62e2} Line Number 1, Column 1:
^
this is my javascript function:
function Update(Id) {
$.ajax({
type: "GET",
url: ROOT_URL + "/sevice/udates.svc/Update?Id=" + Id,
success: function(response) {
},
async: false
});
}
I fixed the problem by setting mimeType to "text/html"
The ajax call expects XML back (perhaps due to bad guessing) and tries to parse it and fails if nothing is returned or it is not valid XML..
Use the dataType option to specify the format of the response.
From the comments it looks like some browsers cannot handle an no-content response. So, a workaround for such cases might be to return something from your service (even a single space).
I've come across an alternative cause of this - might help someone.
If you make a $.ajax request (in my case a PUT request) that returns a 200 header but no body content I've seen this same XML Parsing error message occur - even when the dataType is set to json.
(At least) two solutions work:
Make all API PUT requests return some content, or
Return a 204 'No Content' header instead (what I ended up doing)
It's a known FireFox bug.
https://bugzilla.mozilla.org/show_bug.cgi?id=547718
to quick fix this , you maybe can return an response with html structure(but no content).
async is also part of options. Also specify the dataType as xml
function Update(Id) {
$.ajax({
type: "GET",
async: false,
dataType: "XML",
url: ROOT_URL + "/sevice/udates.svc/Update?Id=" + Id,
success: function(response) {
}
});
}
You need to send html document to the output (the output udates.svc in your case) . If you use ASP.NET, you could do the following:
Response.Clear();
Response.Write("<html xmlns=”http://www.w3.org/1999/xhtml”>");
Response.Write("<head><title></title></head>");
Response.Write("<body>");
Response.Write("your output");
Response.Write("</body>");
Response.Write("</html>");
Response.ContentType = "text/HTML";
Response.End();