$.getJSON parsererror trying to call API - javascript

I'm trying to use the Clipped API (http://clipped.me/api.html) that returns JSON but am running into some trouble. I'm using getJSON, and in Chrome's JS console I get these error messages:
Resource interpreted as Script but transferred with MIME type text/html: "http://clipped.me/algorithm/clippedapi.php?url=callback=jQuery1910859611126…emo-day-2013-still-looking-for-the-next-airbnb-or-dropbox/&_=1364420105379".
Uncaught SyntaxError: Unexpected identifier
Request Failed: parsererror, Error: jQuery19108596111265942454_1364420105378 was not called
And here's my JS:
var clippedAPI = "http://clipped.me/algorithm/clippedapi.php?url=[URL]callback=?";
$.getJSON(clippedAPI, "http://pandodaily.com/2013/03/26/y-combinator-demo-day-2013-still-looking-for-the-next-airbnb-or-dropbox/" ).done(function(json) {
console.log("JSON Data: " + json.title );
}).fail(function(jqxhr, textStatus, error){
var err = textStatus + ', ' + error;
console.log("Request Failed: " + err);
});
This is my first time trying to make something with an API or JSON at all, so I'm really not sure what to do here. I've tried Googling around but can't find anything. The data that I'm actually sending is getting cut off by this jQuery notice that appears when I add callback=?

Your parameter will not simply "guess" what the [URL] param is. Try this:
var clippedAPI = "http://clipped.me/algorithm/clippedapi.php";
$.ajax({
url: clippedAPI,
type: "GET",
dataType: "JSONP",
data: {
url: "http://pandodaily.com/2013/03/26/y-combinator-demo-day-2013-still-looking-for- the-next-airbnb-or-dropbox/"}
}).done(function(json) {
console.log("JSON Data: " + json.title );
}).fail(function(jqxhr, textStatus, error){
var err = textStatus + ', ' + error;
console.log("Request Failed: " + err);
});
Even this fails, however, as your API endpoint does not seem to understand/support JSONP and does not provide a Access-Control-Allow-Origin header. You therefore have two choices:
You can reverse-proxy the API locally to get around the cross-domain issue and go through standard JSON
You can...ehm... get a better API? Lodge a ticket with the devs to get it sorted.

Related

Unexpected Identifier with api url

My code takes input from the users, and saves them by functions in local storage to global variables first_name, last_name and domain. I try to pass these variables to the hunterIO api in my code through the function ajaxing using jquery. For some reason the code throws up an unexpected identifier in the url part of the code.
document.querySelector('#url_But').addEventListener("click", ajaxing, false);
function ajaxing() {
$.ajax({
f_url = "https://api.hunter.io/v2/email-finder?
domain="+domain+"first_name="+first_name+"&last_name="+last_name+
"&api_key=[REDACTED]"
// Error gets thrown here ^^ 'Unexpected identifier'
url: f_url,
type: 'GET',
}).done(function(dataObj) {
console.log(dataObj.data.first_name);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error: " + xhr.status + " " + textStatus);
})
};
I am also worried that after fixing this issue another will be thrown up. Because learning api querying through jquery has been a journey from hell.
You have two issues. Firstly, you cannot define a variable inside an object. Move the f_url declaration outside of $.ajax(). Secondly, you cannot have line breaks in a string. You can either place it all on one line, concatenate the separate lines, or use a template literal. Try this:
document.querySelector('#url_But').addEventListener("click", ajaxing, false);
function ajaxing() {
let f_url = "https://api.hunter.io/v2/email-finder?domain=" + domain + "&first_name=" + first_name + "&last_name=" + last_name + "&api_key=[REDACTED]"
$.ajax({
url: f_url,
type: 'GET'
}).done(function(dataObj) {
console.log(dataObj.data.first_name);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error: " + xhr.status + " " + textStatus);
})
};
Finally note the missing & before the first_name property in the URL.
You must pass the url as first param in $.ajax() not declare it inside it as it is a function.
Just declare f_url before the $.ajax() and pass it to the url parameter.

Undefined parameter in AJAX

I'm trying to rewrite an AJAX request of mine so I can debug it's responses, so I have moved code from the responses into individual functions. In my original code I was able to get the result returning from the AJAX call, and output it in the success response.
Since moving that code into a separate function and then trying to call that function in the success response, I get the error 'result is undefined'. I'm not familiar enough with JavaScript to know why this is happening, please help.
$.ajax({
type: 'GET',
url: '/api/auth/api/Homepage/GetLinks',
success:displayLinks(result, jqStatus, error),
error: showPolicyLinkError(result, jqStatus, error)
});
function displayLinks(result, jqStatus, error){
$('#numbercontrol').html(result);
console.log("Success Log - Satus:" + jqStatus + " Error:" + error);
}
function showLinkError(result, jqStatus, error){
$('#numbercontrol').html("<p>Unable to return any links.</p>");
console.log("Failure Log - Result: " + result + "Satus:" + jqStatus + " Error:" + error);
}
You should only pass function names without arguments:
$.ajax({
type: 'GET',
url: '/api/auth/api/Homepage/GetLinks',
success: displayLinks,
error: showLinkError
});

Error in JSON when I am doing a AJAX call in jQuery

I'm getting the following error in the console when I am trying to return a string of JSON from a AJAX call.
Uncaught SyntaxError: Unexpected token
I have added a codepen with the code I am using.
If you click the convert button and look in the console you will see the error.
I cannot for the life of me figure it out.
Thanks.
JB
http://codepen.io/anon/pen/XJvyWq
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + data);
}, 'json')
});
First remove the "=" .
for a string display in the console you can use the methode stringify of the JSON object
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log("Data: " +JSON.stringify(data) );
}, 'json');
});
or for display an object in the console you can juste write :
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback", function(data){
console.log(data );
}, 'json');
});
the result :
Object {To: "CAD", From: "EUR", Rate: "1.3138"}
Remove json at the second parameter as #SnehalShah said and it'll work
$('.convert').click(function(){
$.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("Data: " + JSON.stringify(data));
});
});
http://jsfiddle.net/1z20m3pL/
Try this way::
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD&callback=?", function(data){
console.log("To: " + data.To);
console.log("From: " + data.From);
console.log("Rate: " + data.Rate);
});
});
Remove the callback=? from the end of the URL you are providing OR remove the 'json' from the .get() method call.
jQuery('.convert').click(function(){
jQuery.get("https://rate-exchange.herokuapp.com/fetchRate?from=EUR&to=CAD", function(data){
console.log(data);
});});
This is because jQuery assumes that when you pass a "callback" parameter in URL and type 'json' that the response will be JSONP. But in this case the server sends a JSON string. Instead of passing "?" if you pass the name of an existing function the error will not be thrown.
The current response by the server is:
{"To":"CAD","From":"EUR","Rate":"1.3138"}
If the Server was responding with JSONP and if the callback you passed was "test" then the response would have been:
test({"To":"CAD","From":"EUR","Rate":"1.3138"})
http://codepen.io/tejzpr/pen/yymQNz?editors=101 explains both cases.

JSON Request appended with [object%20Object] in jQuery

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.

Array of Objects via JSON and jQuery to Selectbox

I have problems transferring a dataset (array of objects) from a servlet to a jsp/jquery.
This is the dataset sent by the servlet (Json):
[
{aktion:"ac1", id:"26"},
{aktion:"ac2", id:"1"},
{aktion:"ac3", id:"16"},
{aktion:"ac4", id:"2"}
]
The jsp:
function getSelectContent($selectID) {
alert('test');
$.ajax({
url:'ShowOverviewDOC',
type:'GET',
data: 'q=getAktionenAsDropdown',
dataType: 'json',
error: function() {
alert('Error loading json data!');
},
success: function(json){
var output = '';
for (p in json) {
$('#'+$selectID).append($('<option>').text(json[p].aktion).attr('value', json[p].aktion));
}
}});
};
If I try to run this the Error ('Error loading json data') is alerted.
Has someone an idea where the mistake may be?
Thanks!
If the error function is running, then your server is returning an error response (HTTP response code >= 400).
To see exactly what is going on, check the textStatus and errorThrown information that is provided by the error callback. That might help narrow it down.
http://api.jquery.com/jQuery.ajax/
The way you are setting the data parameter looks a bit suspect (notice JSON encoding in my example below). Here is how it would look calling a .Net asmx
$.ajax({
url: "/_layouts/DashboardService.asmx/MinimizeWidgetState",
data: "{'widgetType':'" + widgetType + "', 'isMinimized':'" + collapsed + "'}"
});
Also the return data is by default placed in the .d property of the return variable. You can change this default behavior by adding some ajax setup script.
//Global AJAX Setup, sets default properties for ajax calls. Allows browsers to make use of native JSON parsing (if present)
//and resolves issues with certain ASP.NET AJAX services pulling data from the ".d" attribute.
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
success: function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
},
dataFilter: function(data) {
var msg;
//If there's native JSON parsing then use it.
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
//If the data is stuck in the "."d" property then go find it.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
handleAjaxError(XMLHttpRequest, textStatus, errorThrown);
}
});

Categories

Resources