SyntaxError: missing ; before statement jquery jsonp - javascript

I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.

If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});

the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON

Related

Why error function is always fired on my ajax call? [duplicate]

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

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.

Access JSON data from different server/domain using ajax

I am trying to fetch JSON data/file from other server/domain.
My understanding is that from below code i should be able to see success alert but i see error alert
$.ajax({
url: "http://xxxx.com/zzzz",
dataType: 'jsonp',
success: function (json) {
alert("Success");
},
error: function () {
alert("Error");
}
});
In firebug console i see this error
SyntaxError: missing ; before statement
"responseHeader":{
If i open the URL in browser i can see JSON data but not able to fetch it and parse.
This is the starting part of the JSON data if i hit the URL in browser for reference
{
"responseHeader":{
"status":0,
"QTime":4576,
"params":{
"q":"*:*",
"facet.limit":"10",
"facet.field":["DataSet",
"Site",
"Year",
"Product"],
"indent":"true",
"wt":"json",
"facet":"true"}},
"response":{"numFound":260682,"start":0,"docs":[
{
Am i doing anything wrong here OR should i try differently to access JSON data from other domain.
Please suggest. Thanks in advance
Try this:
$.ajax({
url: "http://xxxx.com/zzzz",
dataType: 'json',
success: function (json) {
alert("Success");
},
error: function () {
alert("Error");
}
});
Try to change the datatype from 'jsonp' to 'json'
I think your response is a valid JSON string, but not valid JSONp. The p in JSONp stands for "padding". That means the response must be wrapped within a JavaScript function and returned with the content type text/javascript Please see the example below:
myCalllbackFunc({ my: "data" });
When you use jQuery, the library will pass a callback variable as a query parameter to your back-end. The value defines the name of your callback function.
http://your.host/json?callback=fooBarFunc
should result into this
fooBarFunc({ my: "data" });
Cheers,
Peter
BTW: beside JSONp, you could use CORS for cross origin resource sharing :) http://www.html5rocks.com/en/tutorials/cors/

How to get the response text from an AJAX request using jQuery

I am trying to make a JSONP request to a server. This is my code:
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function() {
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});//code indentation
When I run the code it errors. But if I open the developers tools in Chrome (ctrl+shift+I) I can see the request under "network". Clicking on it shows the correct response (and shows the request was accepted).
Apologies is there is a really obvious solution (I have tried searching, but with no luck), but at this point I am well and truly baffled. Any help would be really appreciated.
::EDIT::
changing the error function to:
error: function() {
console.log('error', arguments);
},
returned the message "jsonCallback was not called" Thanks to Aaron Digulla below.
The response from the server is JSON, not JSONP (checked with JSONlint)
When you say "it errors", my guess is that you get alert(2). To find out why, log the function arguments to the console:
...
error: function() {
console.log('error', arguments);
},
...
jQuery will pass additional information (like the error message) to the function. That should help you understand why it fails.
The same is true for the success function which gets the server response, for example.
[EDIT]
I get the error jsonCallback was not called
That means your server isn't returning JSONP. JSONP looks like name({...}) while normal JSON looks like {...}. Please check your server's configuration and make sure it actually supports JSONP and that the response looks correct.
I should have seen this from your code:
dataType: 'jsonp'
headers: {
'Accept': 'application/json', //this is required by the server
}
That means you're sending a JSONP/JSON mix which can't work. If you use a certain dataType, then let jQuery build the correct headers.
The success function has argument and from that argument you can get the response text.
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function(response) {
alert(response);
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});
You cannot set async: false for a jsonp request due to nature of it, adding script tag to handle response method.
dataType: 'jsonp
as you mentioned,the type of data that you're expecting back from the server is jsonp but may be your server will return any other format rather than jsonp.. so check it which type of response your server is returning in under Network in browser console... then if it is not jsonp format, change your respons return type....

JSONP via getJson not working?

I have getJson like this:
$.getJSON(userUrl+'scanp?callback=?', { 'someparametar': 100 }, function(data){
console.log(data);
});
and I do get a response from my url, and it looks like this:
'"jQuery1110010384737118147314_1401820556204({'hasWon':'false','code':'120580e9fce67a4921f31af7ffa358cc10c83b10','defaultReward':'{\"secure_url\":\"https://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"url\":\"http://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"resource_type\":\"image\",\"format\":\"png\",\"height\":960,\"width\":640,\"signature\":\"a8ca9bb867e0a3d99e1666b7891e8f918d81e627\",\"version\":1401318096,\"public_id\":\"k6jrm2pehwycmehrkicz\"}''}"'
Any idea why I don't get any response when I console.log it?
With 'callback' in your querystring, JQuery wraps the response with a randomly generated method name. To get JSON (without method name), remove 'callback=?' from querystring.
If your server supports JSONP, you can make a call like this :
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(JSON.stringify(json));
},
error: function(e) {
console.log(e.message);
}
});
Hope this helps.
Well I figured it out, the request I wrote was perfectly fine. The thing that was causing the the problem was response I was getting from server.
It was JSON stringified before return.

Categories