ajax request parsing: SyntaxError: Unexpected token : - json

I make an ajax request:
$.ajax({
url: "http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en&jsoncallback=?",
dataType: 'json'
});
and get an error:
SyntaxError: Unexpected token :
When I click on that error in dev tools I see such an object which looks pretty ok for me:
{
"quoteText":"Reality leaves a lot to the imagination. ",
"quoteAuthor":"John Lennon",
"senderName":"",
"senderLink":"",
"quoteLink":"http://forismatic.com/en/9dceb1ebf1/"
}
Where is the problem? I'm unable to find the solution.

Putting a =? in a URL overrides the dataType and tells jQuery to make a JSONP request instead of an XHR request.
The URL you are requesting returns JSON, not JSONP, so you get an error.
Remove &jsoncallback=? from the URL.
You will then get this error:
XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en&js. No 'Access-Control-Allow-Origin' header is present on the requested resource.
… which is explained in this question.

Related

Uncaught SyntaxError: Unexpected token o in JSON at position 1 I have this exception but I don´t know what is this

some errors on Chrome after run my jsp, I don't know what happens:
adblock-onpage-icon-cs.js:172 Uncaught ReferenceError: browser is not defined
at onScriptLoad (adblock-onpage-icon-cs.js:172)
at adblock-onpage-icon-cs.js:183globalstorage:1
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at handleRequest (globalstorage:47)
This is the code in js but, the but I can't understand the mistake.
$(document).ready(function() {
alert("json");
$.ajax({
//connect to a Servlet
url: "ServletReportes",
type:"POST",
dataType:"json",
success: function( result ) {
console.log(result);
}
});
});
Just in case it helps someone else, the first error has nothing to do with your code. This error shows sometimes when you have the adblock extension installed on your browser.
It is often fixed just by uninstalling and installing again the extension, otherwise you can dismiss the error as should not affect your code.
The second error also does not seem an error in your code but in the response, probably the response of the ajax call not being a valid JSON format.

Posting from React to Flask: Uncaught (in promise) SyntaxError: Unexpected token < in JSON

Before I get linked to another thread, I've checked the other answers on this forum about this problem. My JSON is formatted correctly and the JSON doesn't contain HMTL. I know 'Key' is in single quotes but double quotes doesn't fix the problem. The request is going to local host.
Here's the POST from the react file:
fetch(URL + '/api/' + this.props.choice, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({'Key': this.state.value})
})
Here's the GET from the Flask file:
#app.route('/api/Junk', methods = ['GET', 'POST'])
def junk():
junk_request = request.get_json(force = True)
print junk_request
junk_date_var = junk_request["Key"]
The error message from Chrome Debugger:
fetch uncaught (in promise) syntaxerror: unexpected token < in JSON at position 0
Output from the terminal:
{u'Key': u'Select'}
u just means it's a unicode character. What's also strange is that this EXACT code was working a few days ago. This makes me think that some permission is off or something is going wrong with Node.
Turns out there was a get request made to '/api/Junk' with no JSON code. Milliseconds later, a second post request was made to '/api/Junk' with valid JSON.
So, python would try to decode nothing when it expected JSON, fail, then decode and print the valid JSON that came in milliseconds later.

Request Media Type[application/json] Error! Request Body is not JSON format issue for Extjs Ajax request

I am using Extjs 5.1.3. I have post request with params as-
{"root":{"countryId":"458","ruleId":"3386","ruleName":"Test1 \\","ruleType":"CELL_STORE","opType":"DETAILS"}}
I am creating ajax request as-
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
params: win.jsonData,
callback: function(option, success, response){
})
})
From server side, response is coming as-
{
"rules":[
{
"countryId":"458",
"ruleId":"3386",
"ruleName":"Test1 \\",
"ruleType":"CELL_STORE",
"ruleParts":[
{
"seq":"1",
"attrId":"6",
"attrName":"Store Type",
"op":"=",
"val":"dsafdaf",
"charType":"GLOBAL_CHAR"
}
]
}
],
"Status":{
"StatusFlag":true,
"StatusCode":"SUCCESS",
"StatusMessage":"SUCCESS"
}
}
But in Ajax request's callback function, we are receiving response.responseText as-
Request Media Type[application/json] Error! Request Body is not JSON format.
My guess is like issue is because of rulename value as "Test1 \".
So can someone please help me whats missing.
The error message is not an ExtJS error message. If you receive an ExtJS error related to invalid JSON, it will look like this:
Uncaught Error: You're trying to decode an invalid JSON String: TestTest
My best guess is that the error message comes from the server, because it expects you to send your request as JSON. Right now you are sending it as FormData. To send the request as JSON, you have to put your object in the jsonData config and leave the params config undefined:
Ext.Ajax.request({
method: 'POST',
url: appurl.fetchRuleDetails,
jsonData: win.jsonData,
callback: function(option, success, response){
})
})
For future questions regarding server-client communication, please keep in mind that you should first check in your browser network tab what you send to the server and what the response from the server really is.

Consuming broadbandmap.gov json service errors

I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?
That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.
This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).

jQuery not handling JSON response from AJAX POST

Updated: I'm posting HTML FORM data but expecting to receive JSON data. I am not trying to POST JSON data.
I am trying to get a JSON response back from doing a HTML FORM POST request. I have successfully received a JSON back when using a simple HTML FORM POST request (i.e. not AJAX). My JSON response from the HTML FORM POST is this:
{"success":true,"data":1234567}
The problem occurs when I try to handle the request and response with jQuery's .ajax().
$.ajax({
type: "POST",
url: URL,
data: data1,
dataType: "json",
success: function(data, textStatus, jqXHR) {
alert ("success");
},
error: function(xhr, status, error) {
alert ("Error: " + error);
}
});
After running the above code and debugging in Firebug, it appears that the POST request is going through, but something is going wrong on the handling of the response. Firebug tells me the following regarding the HTTP response from the POST request:
Response Headers
Cache-Control private
Content-Length 31
Content-Type application/json; charset=utf-8
...
So it appears that the 31 bytes of data is being sent. However, when debugging the actual Javascript, the error function gets called and the xhr object is this:
Object { readyState=0, status=0, statusText="error"}
I know the jQuery.ajax() document states that "In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown." However, I believe my JSON is valid as I have checked it at jsonlint.com.
What else could be going wrong?
It looks to me like you are getting a server error. I would check the status code of the response and fix whatever is causing the request to fail on the server.
your getting an error because data1 is not formatted in json, so when it receives the data it gets a parse error. data1 needs to be formatted:
data1={"apikey":apikey,
"firstname":fName
}
I was having the same problem. It seems that this is an issue with Cross Domain.
Finding this SO answer: https://stackoverflow.com/a/7605563/154513
helped me.
Some times Jquery return Internal Error 500 for currectly data.
There is example for read the same json data withour error
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqres.in/api/products/3", true);
xhr.onload = function(){
console.log(xhr.responseText);
};
xhr.send();