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.
Related
Trying to load an xml file and getting the xml parsing error.
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt', function() { MD.ui.editPallets.editform_definition(); } );
Should not throw any error. Note the url provided is valid and accessible from a browser directly. The function is also being called. Somehow even after the error reported on console, page loads successfully.
Do not want to see any errors reported on console.
I think Firefox expects an Content-Type and Chrome ignores it.
$.ajax({
url : "https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt",
contentType: "text/xml",
success : function(response) {
$("#analyticForm_description").html(response);
}
});
or for the load method use ajaxSetup:
Description: Set default values for future Ajax requests. Its use is
not recommended.
$.ajaxSetup({
contentType: "text/xml"
});
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/...', function() {
MD.ui.editPallets.editform_definition();
});
I was also facing a similar error and upon search i stumbled upon this post, after debugging code for a while i found out the reason.
Error shown in console
XML Parsing Error: undefined entity
Location: path-to-file.html#link3
Line Number 26, Column 29:
Here is why i was getting this error
I was dynamically generating url that i want to hit, and due to some typo i was getting undefined as the url which was used in making ajax calls resulting in this issue
$.ajax({
url: url, //this was undefined
type: "get",
data: data,
contentType: "text/xml",
success: function (response) {
//some code
},
});
Posting this as it might help someone facing the same issue.
I've been trying to get an XML response from a Dynatrace server using REST api. I have no trouble getting an XML response when I put the url through Postman, and I am able to receive a 'text' datatype response from ajax, but not an 'xml' response. I plan to parse this data into json for future use.
The code I am using so far is:
function getXML() {
basicAuth = "Basic " + id + ":" + password;
$.ajaxSetup({
async: false
});
$.ajax({
type: 'GET',
url: dynUrl, //this is the function we defined above
dataType: 'xml',
headers: {
'Authorization': basicAuth //this is for basic authentication, you've already provided UID and PWD above.
},
//when we succeed, the function below will be called.
success: function(respt)
{
data = respt;
}
});
}
This is called in the following function.
function XMLRespond()
{
getXML();
//dom = parseXml(data);
//json = xmlToJson(dom);
return data;
}
data is called and displayed by an html hosted on localhost. However, when I run this, I get a blank screen and the console says "Permission Denied". My debugger gives me:
Failed to open http://localhost:8080/api/Test.html
Any help on this issue would be greatly appreciated!
Solved the issue. Turns out IE (and I suspect other Browsers) can't straight up display data. Converting data to a string bypassed this problem.
So I'm working on a website where I have to implement a chat, currently the whole thing is running on localhost.
I'm getting this error:
SyntaxError: Unexpected end of JSON input
and can't figure out why. I have googled a little but can't find an answer, that actually works. I actually did this yesterday, on another computer and that worked super, but today it won't work and I can't figure out why.
Thank you for the great answers.
$(function() {
updateChat("updateChat", null);
$(".chat-form").submit(function(event) {
event.preventDefault();
if ($(".chat-form input").val() != "") {
updateChat("sendMessage", $(".chat-form input").val());
}
});
setInterval(function() {
updateChat("updateChat", null);
}, 3000);
function updateChat(method, message) {
$.ajax({
type: "POST",
url: "action/chat.php",
data: {
function: method,
message: message
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function (request, status, error) {
console.log(error);
}
})
}
})
Most likely there's an error or warning in your PHP code being displayed, and because you are expecting only json, that causes the syntax error.
There are a few ways to find out what's going on:
open the developer console in your browser and see what the response is the network tab
check your PHP error log
temporarily change your dataType to html and you'll see your console.log(data)
I was getting this error due to my backend php function NOT returning a response as it should have been. It was returning nothing. My parent function that should have been returning the response was calling a child function that WAS returning a response, but the parent function wasn't passing that child return back to the ajax call.
Another possible culprit for these type of errors could be an improper python "shebang" on your back-end (server side) script.
In my particular case I had ajax call to python cgi script via Apache web server and I could not find a more descriptive error message at front-end debug tools. However, Apache logs indicated that the back-end script had problems importing a one of the python scripts because the interpreter did not recognize it. After checking the "shebang" of that back-end script sure enough it had the wrong interpreter specified because I just copied a template file over and forgot to modify it..
So, check your "shebang" at the top of your script to make sure it points to correct interpreter. Example:
For MVC controller you must return a valid JsON
return new JsonResult() { Data = new { test = 123 } };
instead of
return new JsonResult();
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
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).