parse error callback function not called jquery ajax error? - javascript

I have been trying all the methods that i have seen in the stack overflow asked by other users before.But none of them are working.Please hoping any of you would point me in the right direction
$.ajax({
type: "get",
dataType:'jsonp',
params:jsonData,
jsonp:false,
jsonpCallback:"callbackfn",
headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
url: "http://localhost/url?name=xxx&email=xxxxxx#gmail.com",
success:function(){
alert("sucess function");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " and<br> " + errorThrown);
}
});
function callbackfn(data) {
alert(data);
}
the response is {
"firstName":"John",
"lastName":"Doe"
}
Although the response is json,this rises an error
Parse error .callbackfn not called.

In order to use a custom callback function with JSONP, you must declare its scope to be global, i.e.
window.callbackfn = function(data) {
alert(data);
};
Why?
This is because successful JSONP responses return a new JavaScript file, that is, a JavaScript function call encapsulated in <script> tags. Since each script is independently evaluated in the global scope, any script's function you would like to be made available to another script must also be declared in the global scope. Thus all JSONP callback functions should be global.
EDIT
According to OP, the solution found here: Return JSONP via AWS Lambda/API Gateway did the trick. Issue had to do with an improper server-side JSONP response.

Make sure that your response from the server is a function call with the response data as the argument. It appears you are just outputting JSON, but JSONP expects a function call with the response data. Your server response should look like this:
callbackfn({
"firstName":"John",
"lastName":"Doe"
});
You have jsonp: false with a jsonpCallback and dataType: 'jsonp' - which is odd, because you are also supplying a jsonp callback. Perhaps if you don't need JSONP due to cross-origin requests, you should remove the jsonpCallback argument and just manually call that function with the response:
$.ajax({
type: "get",
dataType:'json',
params:jsonData,
headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
url: "http://localhost/url?name=xxx&email=xxxxxx#gmail.com",
success:function(data){
callbackfn(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " and<br> " + errorThrown);
}
});

Related

Error or fail not being reached when Ajax fails to fetch JSON

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,
...

Wrapped $.ajax issue

$.ajax is wrapped into new 'get' function.
If there is only one 'get' invoke in js file, it is fine.
But 2 calls in row fail.
More precise,
first call fails with "Uncaught ReferenceError: process is not defined",
second one is successful, BUT in success function it has data for first 'get' invoke.
As I can guess, there is some issue with 'this'/context. Could you explain it to me?
(function() {
"use strict";
function get(url, success, error) {
$.ajax({
type: "GET",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'process',
url: url,
success: success,
error: error
});
}
get('XXX',
function(data, textStatus, jqXHR) {
console.log("SUCCESS PING 1");
console.log(data);
},
function(jqXHR, textStatus, errorThrown) {
console.log("ERROR PIND 1");
});
get('YYY',
function(data, textStatus, jqXHR) {
console.log("SUCCESS PING 2");
console.log(data);
},
function(jqXHR, textStatus, errorThrown) {
console.log("ERROR PING 2");
});
})();
/*
===========================================
===============console=====================
===========================================
1. ERROR PIND WAR
2. Uncaught ReferenceError: process is not defined
at db?callback=process&_=1485184752755:1
3. SUCCESS PING DB
4. Object {data for first call here}
*/
First of all, It's better do NOT specify a custom callback name ('jsonpCallback' parameter)
http://api.jquery.com/jQuery.ajax/
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.
The thing is, that jQuery creates global function in window object with specified name and later remove it.
I didn't manage to get full picture of what going on inside jQuery library, but
the issue is definitely caused by fact that it tries to call function that just has been removed.
Removing jsonpCallback param resolve an issue

Getting "parsererror" in jquery ajax

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.

Ajax jquery call to GET application/x-javascript

How do I get content of "application/x-javascript" using jquery Ajax call?
As it keep getting me null content.
What I am trying to use for now:
$.ajax({
dataType: "json",
contentType: "application/x-javascript;charset=utf-8",
url:the_url,
async:false,
success:function(r){
console.log("el result" + r) ;
response = r;
}
});
This:
dataType: "json",
tells jQuery to ignore what the server claims it is sending back and to process the result as JSON. JavaScript isn't JSON, so this breaks it.
Remove that line.
Then you should get the data in the success function.
Asides:
This:
contentType: "application/x-javascript;charset=utf-8",
claims you are sending JavaScript. You aren't making a POST request, so you aren't sending anything. Remove it.
Even if you were sending JavaScript to the server, the application/javascript MIME type hasn't been experimental since 2006, so it shouldn't have the x- prefix on it.
async:false, is a terrible idea. It locks up the JS event loop waiting for the response. You shouldn't use it.
response = r;: assigning data to globals is usually a terrible idea. Process the data in the success event handler instead.
Try this out :
$.ajax({
url: 'my/url',
type: 'GET',
data: 'test=mytest&test2=mytest2',
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
And read the documentation, to see what each parameter is made for :
http://api.jquery.com/jquery.ajax/

jQuery invalid label jsonp

I use jQuery to get php-script result with ajax-function. Problem is php-script is on the another domain, so I should use "jsonp" as returned dataType, BUT php-script returns json, not jsonp (maybe script is not correct) and I get syntax error. How can I handle it? I suppose, that I can somehow get json string before ajax-function handles it and rises error, is it possible?
This is my ajax function:
$.ajax(
{
type: "POST",
dataType: "jsonp",
url: "http://www.pecom.ru/bitrix/components/pecom/calc/ajax.php",
data: res,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.status);
},
success: function (data) {
alert("Data Loaded: " + data)
}
}
)
Thank you!
The short answer is that you can't.
The longer one is that you have to set up some sort of proxying: make the request on the server side from a machine you control, transform the results to proper JSONP there, and connect to that server via AJAX.
(Or, in the very unlikely event that the target server supports CORS, you can use that instead of JSONP.)

Categories

Resources