Please consider the following code snippet:
$(function () {
$.ajax({
type: "GET",
url: "http://mosaicco.force.com/siteforce/activeretailaccounts",
dataType: "jsonp",
crossDomain: true,
jsonp: "callback",
error: function(jqXHR, textStatus, errorThrown) {
alert('Error Message: '+textStatus);
alert('HTTP Error: '+errorThrown);
},
success: function (data) {
var i = 0;
//Process JSON
$.each(data, function () {
var name = this.locname;
var lat = this.lat;
var lng = this.lng;
var address = this.address;
var address2 = this.address2;
var city = this.city;
var state = this.state;
var postal = this.postal;
var phone = this.phone;
var web = this.web;
web = web.replace("http://", "");
var distance = GeoCodeCalc.CalcDistance(orig_lat, orig_lng, lat, lng, GeoCodeCalc.EarthRadiusInMiles);
//Create the array
locationset[i] = new Array(distance, name, lat, lng, address, address2, city, state, postal, phone, web);
i++;
});
}
});
});
I am pulling JSON cross domain and for some reason I keep getting a parseerror returned:
HTTP Error:Error: jQuery17209875996995251626_1343943259805 was not called
I am able to see the data just fine on the page - and the callback looks like this:
callback:jQuery17209875996995251626_1343943259805_:1343943260015
Please help me to diagnose what I am missing - thanks!
var data = $.parseJSON(data);
Since you are doing a JSONP request, you will get an object literal passed into the callback function. You can't use parseJSON on that. Anyway, jQuery is intelligent and always does the parse for you if the content-type is known.
Not sure whether that triggers the error message, but to the question jQuery JSON response always triggers a ParseError this was the solution.
OK, that's simple. Look at the script it loads: That is no valid JSONP - it misses the callback padding. Also, the mime-type is wrong: For a JSONP script, it should be text/javascript or application/javascript, for the JSON they deliver it should be application/json.
jQuery does detect the load of the "script", but as nothing gets executed it throws an the error that "the given callback was not called although the file was successfully loaded" - parseerror suspected.
Are you sure that the webservice supports JSONP at all?
Related
I have created a common Javascript file for all my ajax calls. I am trying to use this as a common way to keep track of all ajax calls. Below is the code for the same.
function doAjax(doAjax_params) {
var url = doAjax_params['url'];
var requestType = doAjax_params['requestType'];
var contentType = doAjax_params['contentType'];
var dataType = doAjax_params['dataType'];
var data = doAjax_params['data'];
var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
var successCallbackFunction = doAjax_params['successCallbackFunction'];
var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
var errorCallBackFunction = doAjax_params['errorCallBackFunction'];
//Make the ajax call
$.ajax({
url: getBaseURL() + url,
crossDomain: true,
type: requestType,
contentType: contentType,
dataType: dataType,
data: data,
success: function (data, textStatus, jqXHR) {
console.log(typeof successCallbackFunction);
debugger
//if (typeof successCallbackFunction === "function") {
successCallbackFunction(data);
//}
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof errorCallBackFunction === "function") {
errorCallBackFunction(errorThrown);
}
}
});
}
This code takes a list of parameters and creates an ajax request based on the parameteres. This code is saved in a file APIHandler.js.
I am trying to call this function from multiple files. An example call is below.
function RedirectToDashboard() {
var params = $.extend({}, doAjax_params_default);
params['url'] = `profile/5`;
params['successCallbackFunction'] = `testsuccess`
doAjax(params);
}
function testsuccess() {
alert("success");
}
When I run this function, I am able to make the call successfully. The only issue comes with the reference to callback function. console.log(typeof successCallbackFunction); returns string instead of function.
I thought maybe order of JS made a difference. I am loading APIHandler.js and then the page specific js. And this ajax call happens at button click, so both JS files are loaded before the ajax call is made.
Other than that, I think maybe I am sending the parameters wrong. That might be causing JS to consider function name as string. But I checked most of the google suggestions on how to pass function, and it seems it needs just the name.
Is there anything else that I might be missing here?
Damn it. I just figured out why it was causing the error. I used quotes when assigning the callback function. Right after posting the question, I realised what was wrong.
params['successCallbackFunction'] = 'testsuccess'
is supposed to be changed to
params['successCallbackFunction'] = testsuccess
So I'm having some trouble with my code. It seems that when I get the reCAPTCHA response it loads when I alert the variable, but AJAX isn't wanting to get it.
var url="";
if (DEPOSIT) {
url = "/get_inv?" + opts;
} else {
var g = grecaptcha.getResponse();
url = "/get_bank_safe?g-recaptcha-response=" + g;
}
alert(url);
$.ajax({
"url": url,
success: function(data) {
try {
alert(data);
data = JSON.parse(data);
Yes I've gotten a valid response from the URL variable itself, but when announcing the AJAX variable 'data', nothing is persevered. Therefore JSON cannot parse 'data'.
It even states that "url" : url.
So I'm not sure how to go about this. If there is any solution please alert me of so.
Thanks! ~LTn | mrgreen33gamer
I have been using an http.get() to make calls to the SounbdCloud API method to receive a JSON object that I would like to pass to the browser. I can confirm that the data I receive is an object, since I the typeof() method I call on the data prints out that it is an object.
var getTracks = http.get("http://api.soundcloud.com/tracks.json?q="+query+"&client_id=CLIENT_ID", function(tracks) {
tracks.on('data', function (chunk) {
console.log(typeof(chunk)); // where I determine that I receive an object
res.send(chunk);
});
//console.log(tracks.data);
}).on("error", function(e){
console.log("Got error: "+e);
});
But when I check the data I receive in the AJAX request I make in the browser, I find that the data received has a type of String (again, I know this by calling typeof())
$('#search').click(function(e){
e.preventDefault();
var q = $("#query").val();
$.ajax({
url: '/search',
type: 'POST',
data: {
"query": q
},
success: function(data){
alert(typeof(data));
alert(data);
},
error: function(xhr, textStatus, err){
alert(err);
}
})
});
I would appreciate the help, since I do not know where the problem is, or whether I am looking for the answer in the wrong places (perhaps it has something to do with my usage of SoundCloud's HTTP API)
JSON is a string. I assume you need an Object representing your JSON string.
Simply use the following method.
var obj = JSON.parse(data);
Another example would be:
var jsonStr = '{"name":"joe","age":"22","isRobot":"false"}';
var jsonObj = JSON.parse(jsonStr);
jsonObj.name //joe
jsonObj.age // 22
I'm trying to get weather data from openweathermap. This url works with coordinates I put in, and I can download the JSON when I input the url the in the browser bar. I'm trying to get this working in my page. When I run this code, in Firebug I can see the HTTP request got the 200 success code, but it's not printing the response for some reason. Am I not using getJSON properly?
var url = "http://api.openweathermap.org/data/2.5/forecast?lat="+ position.coords.latitude +"&lon=" + position.coords.longitude;
$.getJSON(url, function(res) {
console.log(res);
});
You are trying to read cross domain JSON in a function which reads JSONP.
Cross domain JSON reading is not possible.
Try a JSONP request instead;, by appending a callback
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=" +
position.coords.latitude +"&lon=" + position.coords.longitude + "&callback=?" ;
$.getJSON(url, function(res) {
console.log(res);
});
JSON response is like this :
{ 'a':22 }
JSONP response is like :
myFunction({'a':22} ) , where myFunction was the value passed as callback
jQuery does not need the name of the callback function, however needs callback to be mentioned in the URL so that it can indentify it as a JSONP request.
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
Append this ?callback=? to the url and try again like:
$.getJSON(url + '?callback=?', function(res) {
console.log(res);
});
Try this
function buildQuery() {
var str = "http://api.openweathermap.org/data/2.5/forecast?lat=27.175009&lon=78.041849";
return "select * from json where url ='" + str + "' ";
}
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
data: {
q: buildQuery(),
format: "json"
},
dataType: "jsonp",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
consol.log(data);
}
});
working Demo :-
http://jsfiddle.net/HWuDk/1/
I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.