Unexpected token < in JSON at position 4 - javascript

var url="http://fsa.citop.in/lnct/service/signProcess.aspx";
var data={txtLogId: "abc#xyz.com",txtLogPass: "xyz",hdnReqType2: "sign87162"};
var success=function(data, textStatus, jqXHR) {
console.log(data);
};
var fail=function(jqXHR, textStatus, errorThrown) {
console.log("Error:" + errorThrown );
}
$.ajax({
type: "POST",
url: url,
data:data,
success:success,
error:fail,
});
This POST request gives me the error, SyntaxError: Unexpected token < in JSON at position 4, in the console of the page 'http://fsa.citop.in/lnct/' in chrome.
But if I use fsa.citop.in/lnct/service/signProcess.aspx (i.e. no http://), it gives me no error, but nothing comes back in data. On success of POST request, a JSON object is expected. Please somebody explain what is happening here and how it could be resolved.

For those who encounter this problem in AWS Lambda code editor it is most likely your session has timed out.
Try reloading the page and signing in again.
It should resolve this.

It's most likely because the response is HTML and it's trying to parse it as something else. The < at position 4 is the first < of <!DOCTYPE html....
You should try to specify dataType in your ajax call (see http://api.jquery.com/jquery.ajax/) and also make signProcess.aspx to return something more useful (currently the response content type is application/json but it prints HTML).

Related

JSONP Parse Error with valid JSON Output

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

Ajax fails 5% of time, response is "error"

I'm using jQuery to handle Ajax-calls.
I've noticed that, about 5% off the time, the ajax call fails. To make sure I get a good understanding of what's going wrong, I use this code:
$.ajax({
type:'POST',
url:'somepage.php',
data:{somedata:somedata},
success:function (data) {
var IS_JSON = true;
try
{
var newdata = jQuery.parseJSON(data);
}
catch(err)
{
IS_JSON = false;
}
if(IS_JSON)
{
//this is the part where a correct response is handled
}
else
{
//In case somepage.php gives a php-error, I put the exact error (=data) in the error-table at error.php.
window.location = "error.php?errorstring="+data;
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
//In case the ajax errors, I store the response (timeout, error, ...) in the database at error.php
window.location = "error.php?errorstring="+textStatus;
}
});
"Good" responses contain JSON, which I parse. If it's not JSON (for example just raw text from an php error) I don't try to parse it, but store the error in my database.
I would understand errors containing php errors that occured on somepage.php (since it's quiet a large page), but I'm supprised that the main errors I get, are errors of the ajax failing. The response data is just "error".
Anyone knows what the cause could be? What causes ajax-calls to fail? It's not a timeout, and it's also nothing like that somepage.php wasn't found or something. It's also not an error on somepage.php, since in that case, the Ajax-call would be successful, and the php-error would be logged in my database.
Edit: I used this obfuscator to make the script a little harder to read... Don't know if this could be causing the errors...
You should set dataType: 'json' in your ajax call. Coz if your not setting this up and your expecting a json result, the result will be treated as 'string' by default.

SyntaxError: Unexpected token : when using Ajax & Facebook JS API in Chrome

OK I'm using PHP and the Facebook JS API to post stories on users' pages with jQuery's $.ajax() function and it's working fine everywhere except in Chrome.
Chrome is returning the error "SyntaxError: Unexpected Token : ".
I have it alerting the XHR response on error and it is as follows:
{
"id" : "30800681_37922830145443"
}
which is valid JSON. It can't be anything I'm doing wrong with the JSON result because it throws the error before any parsing can be done (i.e., it's not making it into the 'success' function).
The code that's behind this is as follows:
if ($('#post-facebook').is(":checked")) {
// Do the FB post
$.ajax({
type: "POST",
url: "https://graph.facebook.com/<?= $this->session->userdata('fb_id') ?>/feed",
data: "message=" + $("#upload-caption").val() + "&access_token=<?= $this->session->userdata('fbtoken'); ?>&app_id=<?= $this->config->item('appId') ?>&link=" + post_url,
success: function(msg) {
// Save the FB post ID to the DB
var result = $.parseJSON(msg);
var result_array = result.id.split("_");
// Do more stuff here, but it's not even getting into this success function
},
error: function(xhr,ajaxOptions,thrownError) {
// This is what's executing because the thrown error is getting alerted
alert(thrownError);
}
});
}
When I add dataType: "json" in the Ajax parameters, it still goes through the Error function but the thrownError parameter is empty.
I am pulling my hair out...any suggestions? Thanks in advance,
Using jQuery with post is not possible as POST require CORS support, and that is not readily available.
Use FB.api instead, which handles all of this for you, in a much better way.

Debugging IFrame content

I'm having a problem with a page that works fine by itself, but when it's embedded in a iFrame in a corporate webpage (that I don't control) it chokes in IE9 (but not IE8).
The page uses jQuery to make an AJAX call and KnockoutJS to bind content for display. The page passes parameters in a GET request to my server with responds with AJAX, and it seems that it chokes when getting the data back from the server. The data is correct and correctly formatted, however, when this code executes:
$.ajax({
url: this.serviceURL + parameters,
dataType: 'json',
success: callback,
timeout: 3000,
error: function (jqXHR, status, errorThrown) {
if (status == "timeout") {
error("The connection to the server timed out.\nEither the server is down or the network is slow.\nPlease try again later.");
}
else {
error("An error occurred while trying to communicate with the server.\n " + errorThrown);
}
}
});
In IE9, I always hit the "An error occurred..." branch with the errorThrown of "SyntaxError: Invalid character", which tells me nothing.
Anybody got any suggestions on how to go about debugging this problem? I used Fiddler to look at what was being sent to and returned by the server, and everything looks fine on that end.
Update: After sleeping on it for a while, I started fresh today. What I've determined is that for some reason, when my page is iFramed, instead of getting the JSON response:
"{"Foo":true,"Bar":true}"
I'm actually getting (from forcing an error in the error handler so I could inspect the state of the jqXHR.responseText) is:
" {"Foo":true,"Bar":true}"
Which if, using the console, I try feeding to JSON.parse, gives me an error. So the question is, where the heck is that leading space coming from? If I run this in Firefox, I see the correct response from the server (no space) and if I run this outside of the iFrame, I see no leading space. So I don't think it's coming server side. Somewhere in the mess of JS running on the parent page and my page, it's inserting a leading space.
Update 2: A closer examination reveals that jqXHR.responseText.charCodeAt(0) is 65279, so it's not actually a space (although it displays as one) it is the byte order mark. But why is it there now (and not before) and why is it causing a problem?
I couldn't figure out the reason for this problem, so I hacked my way around it by adding a custom converter to my ajax call. So I now have this:
$.ajax({
url: this.serviceURL + parameters,
dataType: 'json',
success: callback,
timeout: 3000,
converters: { "text json": HackyJSONConverter },
error: function (jqXHR, status, errorThrown) {
if (status == "timeout") {
//alert("Timed out");
error("The connection to the server timed out.\nEither the server is down or the network is slow.\nPlease try again later.");
}
else {
error("An error occurred while trying to communicate with the server.\n " + errorThrown);
}
}
});
And my hacky converter looks like this:
function HackyJSONConverter(data) {
if (data[0] = 65279) {
// leading BOM - happens only with an iFrame in OT for some unknown reason
data = data.substring(1);
}
return JSON.parse(data);
}
It's immensely stupid, and I would be delighted if anybody has a better way!

how to get error message of failed ajax

I want to consume a webService which I get JSON Data from
$.ajax({
type: 'GET',
contentType: 'application/json',
dataType: 'JSON-P',
//the url shows the correct JSON Data when I copy the URL in my browser
url: 'http://url.com',
success: function(data){
console.log(data);
alert(data);
},
error: function(xhr, testStatus, error){console.log("Error occured: "+error+" "+xhr+" "+testStatus)}
})
In Firefox, It calls back with the error function, but I dont know what the problem is, it would be great to know the error message but my approach doesnt work.
thanks in advance
edit: In Chrome I get the following error:
Origin null is not allowed by Access-Control-Allow-Origin.
edit: It´s solved, the problem was indeed that json doesnt work cross site, and the data was not "jsonp-conform" (it had to set a function(json data...))arround the json data. This could be done by changing the url at the end "_&jsonp=successCallback. Sorry for bothering you
I think there was a JSON object syntax error. Check your JSON object syntax error with jsonlint.com.
Are you getting this error locally?
Try it on a server and if it doesn't work: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin

Categories

Resources