JSON issue with jQuery (JSONP) - javascript

I have a strange issue using jQuery and JSON, especially JSONP.
My goal is to simply GET JSON data, but I always end up with the following error:
Uncaught SyntaxError: Unexpected token
Here is the code:
<script type="text/javascript">
$(document).ready(function() {
var myurl = "someurl";
$.ajax({
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType : 'jsonp',
success: function(result){
//Do something with JSON result
}
});
</script>
And of course the JSON (raw format):
{"result":[{"targetView":"powerUsage","myData":{"someItems":["9","5","8"],"someItems2":[{"text":"protoText","currentRecord":"45.38","absolute":100}]}}]}
I tried the webservice with the Advanced Rest Client App in Google Chrome and it is working perfectly. I have no clue why this simple example gets this syntax error message.

Your Ajax code looks like fine. I think you are trying to make a Cross domain call as JSONP is a hack for dealing cross domain ajax call. If you Server code if ready for dealing with JSONP request then you must have send a callback parameter like
?callback=my_callback_method
than you service will return result with a callback see below links for more details:
https://learn.jquery.com/ajax/working-with-jsonp/
http://stackoverflow.com/questions/11736431/make-cross-domain-ajax-jsonp-request-with-jquery

You missed to put ready function close, that is }); at the last before script tag close:
<script type="text/javascript">
$(document).ready(function()
{
var myurl = "someurl";
$.ajax(
{
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType: 'jsonp',
success: function(result)
{
//Do something with JSON result
}
});
});
</script>

Related

Accessing data from a remote JSONP Object

I have this JSONP object displayed on a site that generates 3 random numbers. I am trying to access it using the following script embedded in a HTML document.
<script>
var url = 'http://dev.apalfrey.me/workspace/te2006-te2801/';
$.ajax({
type: 'GET', //uses GET function
url: url, //stored URL in var
data: {
'callback': 'randomNum'
},
jsonpCallback: 'randomNum',
contentType: 'application/jsonp',
dataType: 'jsonp'
}).done(function(response) {
console.log(randomNum.num1); //ERROR IS HERE randomNum.
});
</script>
The JSONP object looks like this:
Currently I am getting an error. "Can't find variable: randomNum" That tells me that I am not targetting the object correctly.
It is also important to note that the JSONP object does appear in my resources when I hit F12.
Any suggestions on how to target the remote JSONP object?
The issue is in your done() handler. You're attempting to use a variable named randomNum which doesn't exist. Instead you need to use the response variable as passed to the handler function.
Also note that response will be an array, so you need to access the required item by it's index, eg response[0].num1. Try this:
var url = 'http://dev.apalfrey.me/workspace/te2006-te2801/';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'randomNum',
dataType: 'jsonp'
}).done(function(response) {
console.dir(response);
console.log(response[0].num1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also note that if your intention is to simply generate a random number then AJAX is huge overkill. You can just use Math.random().

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/

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.

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

Trying to trigger jQuery Mobile ajax call

I'm sure this is a basic syntax error but I'm trying to make a rest call using jQuery mobile ajax (code below) and as far as I can tell the ajax is not triggering.
function triggerCall() {
alert("function triggered");
$.ajax({
type: "GET",
dataType: "jsonp",
url: REST Url,
success: function (data) {
alert(data);
}
});
Any help would be appreciated
if you're actually writing url: REST Url, then you must change it to either a var, or a string.. that would be a problem
I believe that if you're using JSONP, you need to specify the callback in the $.ajax request and then again in your REST file return. Here is an example of what I've been using succesfuly (It's not perfect though, I'm sure).
$.ajax({
url: 'www.domain.com/string/to/your/REST/api',
data: {
dataToBeSent: variable,
dataToBeSent: sessionStorage.getItem('local/session Storage'),
dataToBeSend: "or a string"
},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data){
alert("Huzzah!");
},
error: function(){
alert("Boohisssss");
}
}); //end ajax call
And then in the url, I'd place this code at the bottom of the file:
header("Content-type: application/json", true);
echo $_GET['jsoncallback'] . '(' . json_encode($data) . ');';
exit;
Where data is a array that is JSON encoded, using json_encode() in PHP, and then wrapped up in a callback function (the $_GET['jsoncallback'])
Like I said, it's not perfect, but it's been working for me.
Check for errors in browser console. eg. in chrome menu>tools>javascript console.
Also recommend adding an error handler to your ajax call: http://api.jquery.com/error/
Determine which method, JSONP or CORS, to use for your restful ajax calls: So, JSONP or CORS? .

Categories