AjaxConvert throws parse error on Jsonp callback - javascript

I am making Ajax call with Jsonp DataType. And the JsonpCallback Function gets executed, while processing JsonpCallBack method, it throws error as '
parse error , MyScript.JsonpSuccessCallBack was not called'
While Debugging , i got that the error is hitted from AjaxCovert function(return statement) in jquery Library file.
var MyScript = {};
$.ajax({
url: 'https:' + domain + 'captcha/captcha-generate-token',
type: 'GET',
contentType: "application/json; charset=utf-8;",
async: true,
dataType: "jsonp",
jsonpCallback: 'MyScript.JsonpSuccessCallBack',
error:MyScript.error,
});
MyScript.JsonpSuccessCallBack = function(response){
//stuffs
}
MyScript.error = function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
I am getting a valid API response with MyScript.JsonpSuccessCallBack({"STATUS":"success","CONTENT_TYPE":"application\/json","CK":"wTnoiHvP-eLyCWO0xG-KIrJ3AXnLm7awLH-xETjLPNLd4Kkt"})
The error thrown is as below
Error: MyScript.JsonpSuccessCallBack was not called
at Function.jQuery.extend.error (http://www.someWebsite.com/web/scripts/jquery/jquery.js:248:9)
at jQuery.ajaxPrefilter.s.converters.script json (http://www.someWebsite.com/web/scripts/jquery/jquery.js:9893:12)
at ajaxConvert (http://www.someWebsite.com/web/scripts/jquery/jquery.js:8843:19)
at done (http://www.someWebsite.com/web/scripts/jquery/jquery.js:9260:15)
at HTMLScriptElement.jQuery.ajaxTransport.s.send.script.onload.script.onreadystatechange (www.someWebsite.com/web/scripts/jquery/jquery.js:9831:8)
The control reaches the JsonpSuccessCallBack method and through ajaxconvert() meth in lib file, then throws an error. I Cant get why this error is thrown.
I have googled a lot for this issue and followed the steps mentioned but cant fix this,Can anyOne please help me to Fix this issue..
Thank You in advance :-)

Related

AJAX getting error when more than a JSON is downloaded from webpage

I have an AJAX function that gets an error whenever it gets a JSON response from my other webpage that has an error printed at the end of the JSON response. When there is no error, the function reports normally, but I don't know how to get the AJAX function to ignore the error and just read the JSON part of the response.
HTML:
$.ajax({
url: 'https://example.com/quickstart_data.php',
type: 'POST',
dataType: 'json',
cache: false,
success: function(result) {
$("#timeToLeave").html(result['alarm']['timeToLeave']),
$("#timeToLeave").css({'color':result['background']['text']});
}
But the website responds something like this:
{"background":{"fill":"#202124","text":"White"},"event":{"unixTime":1607040000,"date":"4-12-20","day":"Fri","time":"10:30","dayFinish":"Fri","timeFinish":"11:30"}
Fatal error: Uncaught RuntimeException: Unable to find a speaker for this alarm in /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php:128 Stack trace: #0 /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php(74): duncan3dc\Sonos\Alarm->getSpeaker() #1 /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php(660): duncan3dc\Sonos\Alarm->soap('AlarmClock', 'UpdateAlarm', Array) #2 /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php(167): duncan3dc\Sonos\Alarm->save() #3 /var/www/GoogleAlarm/sonoscontroller.php(47): duncan3dc\Sonos\Alarm->setTime(Object(duncan3dc\Sonos\Utils\Time)) #4 /var/www/GoogleAlarm/quickstart_data.php(362): sonosAlarmUpdate('14', '08:54', false, '10') #5 {main} thrown in /var/www/html/vendor/duncan3dc/sonos/src/Alarm.php on line 128
**note I have removed irrelevant data in the JSON return because it is irrelevant to the problem
The "Fatal error:" part is not normally there unless there is a different error, however I still want the AJAX get JSON response to work. How do I do this? I do not want to turn it off in PHP.ini
If you really want to keep the error in the result parameter of success() but ignore it, do this before accessing the values of result :
let fatalErrorIndex = result.indexOf("Fatal error:");
if(fatalErrorIndex != -1) result = result.substring(0, fatalErrorIndex);
result = JSON.parse(result.trim());
Also, set the dataType to 'text' as you are manually parsing the JSON this way.
However, you should consider implementing ajax error handling. This way if anything wrong happens on the PHP side you'll be notified by the AJAX error callback:
$.ajax({
url: 'https://example.com/quickstart_data.php',
type: 'POST',
dataType: 'json',
cache: false,
success: function(result) {
},
error: function (xhr, ajaxOptions, thrownError) {
// Handle errors here
}
}
This is the correct way to handle errors. See the documentation for more info

Uncaught Syntax Error Unexpected token : , but the server received a valid json object from the server

I am trying to do a GET request to solr search engine using $.ajax() from jQuery. This is the code I am using for doing an ajax call:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
So I am getting a valid json object in the response but somehow the browser throws an Uncaught Syntax Error. The actual error is:
Uncaught SyntaxError: Unexpected token :
select?indent=on&q=myparam:value&wt=json&callback=…....somevalue...
The tricky part is that the response header is text/plain when I checked in the browser. How can I solve this? Please help me...
Colons require encoding in query strings.
Your url should look like this:
http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam%3Avalue&wt=json
If you're generating the query string dynamically, use encodeURIComponent() to correctly encode special characters.
I got this solved. Actually I had to use jsonpCallback:"mysuccesscallbackfunction" in the ajax call and json.wrf=mysuccesscallbackfunction in the URL. It looks like this now:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json&json.wrf=mysuccesscallbackfunction',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
jsonpCallback:"mysuccesscallbackfunction",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
and my mysuccesscallbackfunction is:
function mysuccesscallbackfunction(resp) {
console.log('inside mysuccesscallbackfunction: ', resp );
}
Now, first it executes whatever is inside mysuccesscallbackfunction and then goes to default success callback. I found it somewhere on web. I would still like to know why it worked now.

ajax error: Resource interpreted as Script but transferred with MIME type text/json:

I am trying to get data from a server using JSONP but I keep getting a warning in my console
Resource interpreted as Script but transferred with MIME type text/json:
Below is my ajax call
var loginData = {
"strUniqueID" : "123",
"UserName" : "UserName",
"Password" : "Password"
};
$.ajax({
url: http://domain.com,
type: "POST",
data: {'data':$.toJSON(loginData)},
contentType: "text/plain",
dataType: "jsonp",
jsonpCallback: 'jsonCallback',
success: function(data) {
console.log('Success');
console.log(data);
},
error: function(jqXmlHttpRequest, textStatus, errorThrown) {
// Display the error.
console.log('Error: ' + textStatus);
console.log('Error thrown: ' + errorThrown);
}
});
Because of the warning I am receiving I am also getting this error
Uncaught SyntaxError: Unexpected token :
In Firefox this shows up as
SyntaxError: missing ; before statement
Is this because my data isn't getting brought back in the correct format?
If I open the URL with the parameters I get the response correctly
{"response":"SESSION ID"}
But I also get an error from the ajax call
Error: parsererror
Error thrown: jsonCallback was not called
I've been racking my brains with this for a few hours now and I am stumped!
I found another question which helped me.
I needed to allow JSONP request on the service to send back the correct response

jquery ajax does not complete

I'm having a trouble with ajax requests and server responses:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true,
error: function(){},
success: function(){},
complete: function(){alert('complete')}
});
}
The thing is - sometimes I get succes, when I should get it, but sometimes I can get 500 status, and it is normal and expected.
The same ajax call works for correct requests, but fails for others.
I want to display an error message if I get a 500 server error, but for some reason the ajax does not complete. Thus, neither error: nor complete: work.
Maybe the reason for that is 'jsonp' datatype? Other datatypes do not work though.
Can someone help please?
Or maybe give me an advice on how to detect server status any other way.
jsonp requests do not trigger error callbacks by design, therefore there is no way for you to catch the error with javascript. I suggest instead implementing an error handler on your server that detects a jsonp request and returns jsonp that indicates an error has occured rather than a 500 status code.
Note that error: is deprecated as of 1.8 and is not called for JSONP however I wonder if you might have success using the Promise functionality introduced with 1.5 for deferred http://api.jquery.com/category/deferred-object/ as:
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
Example for your code:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true
}).done(function(data, textStatus, jqXHR){ //replace success
alert(textStatus);
}).always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { // replace complete
alert(textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) { // replace error
alert(errorThrown);
});
Make sure that you are accessing to your server. Maybe you are requesting in your server for an specific contentType (like application/json) and you are not using that property into your ajax call.
As you requested, to show any message if get a error (400, 404, 500...), you can use my custom function for ajax error responses:
function onErrorFunc(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status + '\nStatus text: ' + status +
'\nError thrown: ' + errorText);
}
Usage:
$.ajax({
//some options
error: onErrorFunc
});
Please, show us what error thrown your server.
Thank you all for comments. Jquery .ajax really does not give errors on jsonp requests.
The way to get error messages was to implement the jquery-jsonp plugin:
https://github.com/jaubourg/jquery-jsonp

Check for 404 error status in jquery

I use this code to get some information from twitter via their api:
$.ajax({
url : apiUrl,
cache : false,
crossDomain: true,
dataType: "jsonp",
success : function(html) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
However, if the apiUrl variable provides a correct url, this code work fine, e.i. the success object is executed, but if the url isn't correct, e.i. 404 error is returned from twitter, the error object is never executed. It doesn't log anything in console. How should I check for 404 error status in this case?
From jQuery API ajax docs:
error option
Note: This handler is not called for cross-domain script and JSONP
requests.
http://api.jquery.com/jQuery.ajax/
According to the docs, use statusCode setting in .ajax.
$.ajax({
...
statusCode: {
404: function(){
}
}
});

Categories