jQuery ajax jsonp call always get unexpected token error - javascript

I've been wasting a great deal of time for something I think is so simple, yet there are no good examples that illustrate how and what the ajax call is doing.
This is my javascript code:
$.ajax({
type: 'GET',
url: 'https://maps.googleapis.com/maps/api/timezone/json',
dataType: 'jsonp',
data: {
location: myLoc,
timestamp: myTime,
sensor: true
},
success: function(){alert('OK');},
error: function(){alert('FAIL');}
})
}
The variables "myLoc" and "myTime" are not the problem. In fact if I cut and paste the URI into my browser it works just fine and shows the data: https://maps.googleapis.com/maps/api/timezone/json?callback=jQuery18307430207263678312_1354817349576&location=36.7468422%2C-119.7725868&timestamp=1354817353&sensor=true&_=1354817353398
From what i've been reading, the "callback" parameter is automagically generated and somehow the code should be smart enough to call the success function or error function.
The error that chrome returns is "Uncaught syntax error unexpected token ':'"
The javascript code always calls the error function no matter what I try. I added a jsonpCallback parameter (didn't work), json parameter (didn't work), changed dataType to "json" (didn't work due to cross domain error).
Please help.

$.ajax({
type: 'GET',
url: 'https://maps.googleapis.com/maps/api/timezone/json',
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
data: JSON.Stringify({
location: myLoc,
timestamp: myTime,
sensor: true
}),
success: function(){alert('OK');},
error: function(){alert('FAIL');}
});

Related

How do you send a webhook request via a google docs add-on?

I'd like to create a google-docs add-on that sends an ajax call to a webhook.
I've tried the below, but I get the following error
Error
ReferenceError: "$" is not defined. (line 5, file "")
Code
function myFunction() {
var arr = 'data'
$.ajax({
url: 'webhook_url',
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function () {
alert('Success');
}
});
}
If ajax can't be used here is there any other way to make a request to a server-side resource
This is an OLD question, so I don't know if you still have the issue, but, from the error you're getting Jquery is either not added, or not available.
You could try doing it with vanilla js, see this link for a walkthrough: https://www.sitepoint.com/guide-vanilla-ajax-without-jquery/

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....

JQuery AJAX call, IE9 issues with JSON

JSFiddle: http://jsfiddle.net/D2s2M/1/
I cannot figure out why this does not work in IE9. I've seen other questions here on Stack with similar issues, none of which have solutions that seem fix my problem.
This issue is specific to IE9, it does work in FF and Chrome. However, I am seeing some oddities in Chrome that do not make sense: if I append the contentType:'application/json' inside of the attributes, it breaks functionality inside of Chrome.
Here is the code that is in fiddle:
$('document').ready(function(){
$.ajax({
dataType: 'json',
type:'GET',
url: 'https://freegeoip.net/json/?callback=',
//contentType: 'application/json',
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
$('#text').text(ct);
},
error: function(a,b,c) {
$('#text').text('Error: '+' '+b+' '+c);
},
timeout: 3000
});
});
Thanks
Change
dataType: 'json',
to
dataType: 'jsonp',
Solution: http://jsfiddle.net/D2s2M/2/
I'm not precisely sure why this cross-domain issue was IE specific nevertheless, JSONP did lead to resolving the issue.
The service I'm using does support JSONP, in the url there is a querystring variable to specify the name of the callback you wish to use. (JSONP requires that the data either be wrapped in a callback inside of the file itself, or set and passed an object inside of the JSON file.. this is required because JSONP loads everything in the head of the DOM to bypass cross-domain restrictions).
Revised Code:
$('document').ready(function(){
$.ajax({
dataType: 'jsonp',
type:'GET',
url: 'https://freegeoip.net/json/?callback=func',
contentType: 'application/json',
async: false,
jsonpCallback: 'func',
success: function(data){
console.log(data);
},
error: function(a,b,c) {
$('#text').text('Error: '+' '+b+' '+c);
},
timeout: 3000
});
});

SyntaxError: missing ; before statement jquery jsonp

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

Using same callback for two ajax() request yields "parsererror"

So, I've been battling with Javascript for a little while now and I have a weird error which is probably something simple. I have an ajax request like so:
$.ajax({
url: 'http://www.hahaha.com/api/v3/acts',
crossDomain: true,
jsonpCallback: 'handlejson',
async: false,
jsonp: 'callback',
dataType: 'jsonp',
type: 'GET',
success: handleActs,
error: handleError
});
Which works fine and calls the callback with no problems. Now, if I add this request directly underneath:
$.ajax({
url: 'http://www.hahaha.com/api/v3/performances',
crossDomain: true,
async: false,
jsonpCallback: 'handlejson',
jsonp: 'callback',
dataType: 'jsonp',
type: 'GET',
success: handlePerformances,
error: handleError
});
I get a "parsererror" on the first request and the second one succeeds. Anyone have any ideas as to why it's doing this? Can a jsonpCallback only have one request called on it?
I don't think it works to have two AJAX calls referring to the same jsonpCallback - I think jQuery puts a callback function in the global namespace, then removes it when it's called - so it won't be around for the second set of loaded data. I wouldn't have thought this would matter with async set to false, but it looks like it does.
At first I couldn't figure out why you were setting jsonpCallback at all, but testing seems to indicate that the API you're using strips anything other than [a-z] from the callback name :(. So you might try this with jsonpCallback set to 'handlejsona' in the first call and 'handlejsonb' in the second call.
This approach seems to work here: http://jsfiddle.net/nrabinowitz/H7zYt/

Categories