Below is my AJAX code. Here I'm hitting a service with one value. The service is getting called successfully, but it is not going into the success method. It is going into the error method only. In the error method it is giving parsererror and message: Unexpected token S
$.ajax({
type: 'GET',
url: 'http://domin.com:9000/ramsweb/rest/DetailRest/addOrderContacts/123456/' + customerId,
success: function (data, status, xhr) {
console.log(data);
$("#loadingSpinner").hide();
},
error: function (jqXhr, textStatus, errorMessage) {
$('.ErrorMsg').html('<h5>An error has occurred</h5>');
},
fail: function (data) {
$('.ErrorMsg').html('<h5>data loading failed</h5>');
}
});
jQuery AJAX functions by default will try to detect the type of response depending on other pieces of data in your request and response (headers etc.)
Most likely, your endpoint serves it as JSON thus telling jQuery to internally do a JSON.parse. However, your endpoint may be serving an error page instead of JSON which can cause parse errors like this.
Related
I am working on below Ajax code in JavaScript, I am trying to pop up a dialog box when the URL could not load the JSON properly the reason may be either expired token or incorrect token, in any case, I am expecting the code to hit the error or fail but it's not happening. When the URL could load the JSON successfully, success and complete blocks are being hit as expected but nothing is being hit when URL fails. I have tried to use async: false and tried to check with a boolean variable weHaveSuccess but console.log(weHaveSuccess); which is in the last line of the code is getting executing even before success/error is being executed and it seems to me like its still loading asynchronously. I would like to know why error block is not being hit when the JSON load from URL is getting failed.
My code
function checkUser(myURL, newAccessToken, weHaveSuccess) {
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: myURL + newAccessToken,
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
},
success: function (data) {
console.log("Hello 2 " + JSON.stringify(data));
weHaveSuccess = true;
console.log('Message from Success ' + weHaveSuccess);
},
complete: function () {
console.log('Message from Complete ' + weHaveSuccess);
}
}).done(function (data) {
alert("Success");
console.log(data);
}).fail(function (data) {
console.log(data);
alert("Failed");
}).always(function () {
alert("In Always");
});
console.log(weHaveSuccess);
}
Thanks in advance!
AJAX requests are asynchronous. It takes time for a remote request to be made and responded to. You will have to write your post-response code within the success function or call another function from there, not within the same scope as where the call is initiated.
I am taking a bit of a guess here about what your server returns on failure. An AJAX request success means simply that a 200 OK response was received, without any consideration of the contents of the data. If an error is simply a change in the data you will need do one of the following to show an error:
Have the server set a status code header on failure, perhaps 400 Bad Request.
In the success function look within your data for whatever error response you are expecting and trigger the alert() there.
First of all the console.log(weHaveSuccess); fires first, because the $.ajax() is asynchronous while console.log is not so ajax will be triggered and return the promise when finishes, but the browser will continue with the script.
In the jQuery ajax docs says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
It's hard to debug without seeing the response, maybe you can add some info from the network or a URL?
How about if you try the following:
Add the jsonp setting to your $.ajax() function for the callback that will handle the response and console.log there:
function myCallback(data) {
console.log(data);
}
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: myCallback,
...
I am calling a Cross Domain AJAX Request using JSONP. Now, i am able to make it work using CORS. But, i want to know why it is not happening with JSONP. I looked at other threads with similar problem but couldnt figure out why it is not working in my case.
Here is the code:
$.ajax({
type: "GET",
url: http://XXXX:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123,
dataType: "jsonp",
jsonp: false,
jsonpCallback: "myJsonMethod",
success: function (data) {
alert(data);
},
error: function (httpReq, status, exception) {
alert(status + " " + exception);
}
});
Now, this calls my server, the data is populated and then i get an alert "parse error myJSONMethod was not called" on a callback URL http://xxxx:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123&_=1470322282936
Additionally, in the console i get the error as Uncaught SyntaxError: Unexpected token :
The response structure is:
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
When i run this JSON Output on jsonlint it says it is a valid JSON. I don't know where the JSON is getting messed up.
Your data must be like this to be valid for JSONP:
myJsonMethod({"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}});
the responsetext must be valid js code and it will run immediately when the response is over.So if you write your code
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY
EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
in a <script> tag,the console will throw an err like that
I am making a ajax post call that returns the required information in the response header an the empty response body . I am using the following code to make call
$.ajax({
url : someUrl,
type : "post",
contentType : "application/x-www-form-urlencoded",
success : function(data, textStatus, request)
{
alert("success");
},
error : function(request, textStatus, errorThrown)
{
alert("error");
},
timeout : "150000"
});
i always get error alert since the response is empty even though the status is 200 ok. Is there any workaround for the calls like this?
For example, we want to get Date header from the URL which returns error:
var get = $.get('http://stackoverflow.com/asdasdasddsadsadasde').always(function(){
alert(get.getResponseHeader('Date'));
});
success and error methods are deprecated in latest versions of jQuery. You may use done, fail and always methods.
I want to know that how can we get ajax status code in jquery.
I have this ajax block:
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success,
complete: rollup_filters(),
failure: function(){
alert("Failure");
}
}
Now in above code, in case of failure, how can i get ajax status code and some description of that status code ??
You want to use the error option to capture this. For example:
error: function (jqXHR, textStatus, errorThrown)
// Your handler here...
}
You can then use the jqXHR object to retrieve information about the failure.
From the documentation:
For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
abort()
First, you have a few syntax errors. The above is a method call, so it needs to follow $.ajax({ ... }); (with parenthesis).
Secondly, you want to supply the error property as part of the object, not failure (see docs for more information).
Third, when you do bind to an error, you are supplied three parameters: jqHXR, textState, errorThrow. These arguments will supply you the details of a failed AJAX call. (More specifically, try jqXHR.status)
Alternatively, you can bind to the $.ajaxError function as well.
Update To keep this more up-to-date, you should now be following the Deferred API (as of jQuery 1.5), which would make binding to an error look something like the following:
$.ajax({ /* options */ })
.done(function( data, textStatus, jqXHR ){
// here you bind to a successful execution.
.fail(function( jqXHR, textStatus, errorThrown ){
// Here you can catch if something went wrong with the AJAX call.
})
.always(function(){
// here you can execute code after both (or either) of
// the above callbacks have executed.
});
Change your failure callback to
error:function (xhr, options, error){
alert(xhr.status);
alert(error);
}
There is nothing like failure in ajax settings. Replace failure by error and you get 3 arguments in the error callback. First argument is the xhr object which has a status property in it.
$.ajax{
type: "GET",
url: "keyword_mapping.html",
data:"ajax=yes&sf="+status_flag,
success: callback.success;
complete: rollup_filters(),
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR.status);
}
}
I'm building a small Chrome extension that must send messages through a POST http request to a server in my company network, and I'm using jQuery 1.4.1 to speed up the development of the javascript part.
I have this code to send the request:
function send() {
$.ajax({
url: "http://mycompany.com/update",
method: "POST",
data: {status: "sometest", in_reply_to_status_id: "anId"},
success: function(data, textStatus) {
console.log("success");
console.log(data);
console.log(textStatus);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("error");
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
},
complete: function(XMLHttpRequest, textStatus) {
console.log("complete");
}
});
}
The request done this way fails, in the Chrome log I see that the server responds with a http status 400 and with the text "This methods requires POST".
If I change to code above with this:
function send() {
$.post("http://sunshine.emerasoft.com/statusnet/api/statuses/update.xml", {status: "sometext", in_reply_to_status_id: "anId"}, function(data) {
console.log(data)
});
}
everything works fine, the http status is 200 and server side I can see that the data I sent is correctly saved.
I need to use the full $.ajax() method because I need to do some work in case of success or failure, and some other when the request is complete, so $.post() is not enough.
Am I doing something wrong calling $.ajax(), or there is an issue of some kind, maybe because I am in the xontext of a Chrome extension?
Thanks
I believe the $.ajax() function takes a 'type' option, not a 'method' option.
The default type is GET.