Ajax jsonp missing ; error - ajax

I am near a solution to get json data, just get the error :
SyntaxError: missing ; before statement
My json data look like this :
{"custom1":"","dateOfBirth":null,"custom2":"","custom3":"","custom4":"","custom5":""}
I am using jsonp. this solved my problem with CORS (Cross-origin request blocked)
In the debugger i can see the data in the NET.
How close i am?
Som get me the last push to resolve my problem??
<script type="text/javascript">
function getdata() {
$.ajax({
type: 'GET',
url: 'http://myurl/api/getUser/22?_key=123456789',
dataType: 'jsonp',
//contentType: "application/jsonp",
success: function (data) {
$('#badge').append(result);
}
});
}

You have to set your ajax response type to jsonp instead of json.
Like
dataType: 'jsonp'
You can read more about it in jquery docs on $.ajax. Also as I can see, the result variable that you are trying to append in the success callback is not declared & inititalized anywhere in the code you have provided.

Related

jQuery Cross Domain Request to get JSON Response without Callback

I am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.

How to send and retrieve cross-domain ajax data in userscript

I use this code to store and retrieve ajax data via http://openkeyval.org/
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify([123,456]),
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
$.ajax({ /* retrieve data */
url: "http://api.openkeyval.org/test-key-data",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
everything work fine in Chrome javascript console but in userscript I get error like this
Uncaught ReferenceError: jQuery110208458673823624849_1375932537303 is
not defined
I try to use GM_xmlhttpRequest to retrieve data like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data",
onload: function(response) {
console.log(response.responseText);
}
});
but it seem like openkeyval doesn't accept data via POST/GET method and log result was like when you access it directly from url of browser like this
{"error":"not_found","documentation_url":"http://openkeyval.org/"}
I include jQuery and it work fine with this code
// #require http://code.jquery.com/jquery-latest.min.js
I try to use Greasemonkey/jQuery XHR bridge with out change other code by like this
// #require http://courses.ischool.berkeley.edu/i290-4/f09/resources/gm_jq_xhr.js
and try use openkeyval official javascript library with code like this
// #require http://cdn.openkeyval.org/statics/openkeyval.packed.js
and retrieve data with code like this
var ourCallback = function(value, key) {
console('The value of ' + key ' + is ' + value);
};
window.remoteStorage.getItem('test-key-data', ourCallback);
still got error ERROR: Unexpected string
Please help, I mess with it more than 10 hours. Thank you so much.
It look like $.ajax always trigger error event function
but GM_xmlhttpRequest can retrieve mistype data, so I try looking for dataType: "jsonp" in GM_xmlhttpRequest and I got that jsonp header content-type is "application/javascript" OR "application/json" and the first one work well.
my new code for retrieve data look like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data?nocache=" + new Date(),
headers: {
"Content-Type": "application/javascript"
},
onload: function(response) {
console.log(response.responseText);
}
});
and retrieve data using $.ajax even it always trigger error event function but it still send data.
I try both content-type on GM_xmlhttpRequest and still not work.
my code to store data look like this
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify(myVarObject),
dataType: "jsonp"
});
Add this into $.ajax({...})
crossDomain: true;
It is because by default cross domain ability is disabled. See http://api.jquery.com/jQuery.ajax/
EDIT:
Sometimes there will be a issue with different charset between local script and remote script. Try using:
scriptCharset: "utf-8";
Also look at JQuery AJAX is not sending UTF-8 to my server, only in IE
Elaborating my comment
The reference is to the callback function generated by jquery.
It Sounds to me the way you invoke your userscript unloads the jquery functions before the callback is executed.
Perhaps you use a link and forgot the preventDefault?
If you ajax and have
$("#linkid").on("click"
or
$("#formid").on("submit"
it is MANDATORY to continue like this:
,function(e) {
e.preventDefault();
Otherwise the link is followed or the form is submitted which may not have any visible effect, but the asynchronous scripts have been (partially) unloaded unless the form and link has a target other than the current window

Accessing stackoverflow API with jsonp gives unexpected result

I am trying to access the Stackoverflow API with jsonp as datatype by doing this:
$(document).ready(function(){
$.ajax({
url: 'http://api.stackoverflow.com/1.1/tags/php/top-answerers/month',
dataType: 'jsonp',
});
});
And once I reload, I get the following in the console:
"Uncaught SyntaxError: Unexpected token :"
What am I doing wrong here?
Right now the application is returning Content-Type: application/json.
You can fix this by overriding the callback function name to jsonp which will tell the server to return Content-Type: application/javascript instead:
$(document).ready(function () {
$.ajax({
url: 'http://api.stackoverflow.com/1.1/tags/php/top-answerers/month',
dataType: 'jsonp',
jsonp: 'jsonp',
success: function (data) {
alert(data.top_users.length + ' users retrieved.');
}
});
});
Info on jsonp ajax setting:
jsonpString
Override the callback function name in a jsonp request. This value
will be used instead of 'callback' in the 'callback=?' part of the
query string in the url. So {jsonp:'onJSONPLoad'} would result in
'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the
jsonp option to false prevents jQuery from adding the "?callback"
string to the URL or attempting to use "=?" for transformation. In
this case, you should also explicitly set the jsonpCallback setting.
For example, { jsonp: false, jsonpCallback: "callbackName" }
From https://api.stackexchange.com/docs
All API responses are JSON, we do support JSONP with the callback query parameter. Every response in the API is returned in a common "wrapper" object, for easier and more consistent parsing.
So you should use dataType: 'json' rather than jsonp.
You should also upgrade to the 2.1 API, the 1.x API has been deprecated for 6 months.

Uncaught SyntaxError: Unexpected token : , when i access tickets.com json api

I'm trying to get data from:
http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json
I'm using the jQuery $.ajax method and the code is written in my index.html file:
function getAPI() {
jQuery.ajax({
url: 'http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json',
type:"get",
dataType: 'jsonp',
crossDomain: true,
jsonp: false,
success: function(data) { console.log(data); }
});
}
When I try it in the Chrome console, there is a message
Uncaught Syntax Error:Unexpected token:
I am very confused about what the problem is, can anyone help me?
The content being returned is json, not jsonp as you specified in your dataType. Also, by setting jsonp to false, you're preventing a jsonp querystring from being appended to the URL by jquery, which is likely why the API you're using is returning json and not jsonp. I would try taking out the jsonp: false parameter.

Calling Restful service through jQuery Ajax

I am trying to access a restful web service using jQuery Ajax but getting following error:
XML Parsing Error: no element found Location: moz-nullprincipal:{cefa3a59-2437-454f-b39a-384cf1fdf072} Line Number 1, Column 1:
This how I am making the call:
function getResponse(){
$.ajax( {
type:'Get',
dataType:'xml',
url:'http://localhost:8080/RestTest/restservice/number',
success:function(data) {
alert(data);
}
} );
}
Here my response data type is xml. I understand that there is some cross domain issue but not sure how to resolve it. Please help me on this.
Use getJSON
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});

Resources