JSON parseError - get json as string - javascript

I'm trying to get json data from a service, but getting parseError when I use $.ajax with datatype 'JSONP':
$.ajax({
url: url,
dataType: 'JSONP'
})
.error(function(XMLHttpRequest, textStatus, errorThrown) { ... })
.done(function(data) { ... });
If i try it with other datatype than 'JSONP' it returns 404 error.
How can i get just a string instead of parsing json, i believe there is some linebreaks in json that cause parse errors.
Here is the fiddle http://jsfiddle.net/FSEZQ/3/

That's JSON, not JSONP.
For example, this is JSON:
{"key": "value"}
This is JSONP:
callback({"key": "value"})
If the service doesn't provide JSONP, the browser prevents you from getting it (same origin security restrictions).
The way people get around same origin restrictions consist of some server utilization. You can either right code that does this in PHP, or use a service such as AnyOrigin .
Here's an AnyOrigin example.
$.getJSON('http://anyorigin.com/get?url=metservice.com/publicData/tides2MonthAuckland&callback=?', function (data) {
$('#result1').html(JSON.stringify(data.contents));
}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
$("#result2").html(textStatus);
});
... and an accompanying fiddle.
Here's an example that shows how this data can be used.

Related

Uncaught Syntax Error Unexpected token : , but the server received a valid json object from the server

I am trying to do a GET request to solr search engine using $.ajax() from jQuery. This is the code I am using for doing an ajax call:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
So I am getting a valid json object in the response but somehow the browser throws an Uncaught Syntax Error. The actual error is:
Uncaught SyntaxError: Unexpected token :
select?indent=on&q=myparam:value&wt=json&callback=…....somevalue...
The tricky part is that the response header is text/plain when I checked in the browser. How can I solve this? Please help me...
Colons require encoding in query strings.
Your url should look like this:
http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam%3Avalue&wt=json
If you're generating the query string dynamically, use encodeURIComponent() to correctly encode special characters.
I got this solved. Actually I had to use jsonpCallback:"mysuccesscallbackfunction" in the ajax call and json.wrf=mysuccesscallbackfunction in the URL. It looks like this now:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json&json.wrf=mysuccesscallbackfunction',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
jsonpCallback:"mysuccesscallbackfunction",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
and my mysuccesscallbackfunction is:
function mysuccesscallbackfunction(resp) {
console.log('inside mysuccesscallbackfunction: ', resp );
}
Now, first it executes whatever is inside mysuccesscallbackfunction and then goes to default success callback. I found it somewhere on web. I would still like to know why it worked now.

Access JSON data from different server/domain using ajax

I am trying to fetch JSON data/file from other server/domain.
My understanding is that from below code i should be able to see success alert but i see error alert
$.ajax({
url: "http://xxxx.com/zzzz",
dataType: 'jsonp',
success: function (json) {
alert("Success");
},
error: function () {
alert("Error");
}
});
In firebug console i see this error
SyntaxError: missing ; before statement
"responseHeader":{
If i open the URL in browser i can see JSON data but not able to fetch it and parse.
This is the starting part of the JSON data if i hit the URL in browser for reference
{
"responseHeader":{
"status":0,
"QTime":4576,
"params":{
"q":"*:*",
"facet.limit":"10",
"facet.field":["DataSet",
"Site",
"Year",
"Product"],
"indent":"true",
"wt":"json",
"facet":"true"}},
"response":{"numFound":260682,"start":0,"docs":[
{
Am i doing anything wrong here OR should i try differently to access JSON data from other domain.
Please suggest. Thanks in advance
Try this:
$.ajax({
url: "http://xxxx.com/zzzz",
dataType: 'json',
success: function (json) {
alert("Success");
},
error: function () {
alert("Error");
}
});
Try to change the datatype from 'jsonp' to 'json'
I think your response is a valid JSON string, but not valid JSONp. The p in JSONp stands for "padding". That means the response must be wrapped within a JavaScript function and returned with the content type text/javascript Please see the example below:
myCalllbackFunc({ my: "data" });
When you use jQuery, the library will pass a callback variable as a query parameter to your back-end. The value defines the name of your callback function.
http://your.host/json?callback=fooBarFunc
should result into this
fooBarFunc({ my: "data" });
Cheers,
Peter
BTW: beside JSONp, you could use CORS for cross origin resource sharing :) http://www.html5rocks.com/en/tutorials/cors/

Cross-domain AJAX call returning string JSON, instead of JSON object

I am making a cross-domain AJAX call, and I am not sure if I am doing something wrong or the providers of the API call is incorrectly returning the JSON. Whenever I get the response from the API call, it is a string instead of a JSON object. Here is my AJAX call.
$.ajax({
async: false,
dataType: 'jsonp',
url: 'http://cross-domain/getSummaryStat.action',
data: { minDailyDate: start_param, maxDailyDate: end_param },
success: function(response) {
map = {
gamefuse: response["ROM-GF-Live"],
facebook: response["ROM-FB-Live"],
kongregate: response["ROM-Kongregate-Live"],
yahoo: response["ROM-Yahoo-Live"]
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
When the response comes back, here is response.result
"[{"dayRetention1":"0.01453800063053","visit":"601","installs":"203"},{"dayRetention1":"0.122484891199019","visit":"33863","installs":"10949"]"
NOTE: I set dataType to jsonp because it is a cross-domain AJAX call, and I was getting an error without it.
First, It looks like the returned string isn't even in correct JSON form. It's missing a close bracket at the end.
If this doesn't fix it then the issue here is probably on the server side. Since JSONP is JSON with padding, your return function shouldn't be:
function_name("the string that I return");
Instead you should have:
function_name({
"name":"Bob Loblaw",
"age":40
});

jQuery AJAX call not returning data

I feel a little silly here. My ajax call is running the error: function every time. I know that the data is coming back as JSON, but i've done the datatype as jsonp to allow for cross origin stuff. I don't think I can do anything differently, unless I'm forgetting something obvious. Please- whats wrong with this:
function sartleApi(type,endpoint,object,callback){
$.ajax({
contentType: "application/json",
dataType: 'jsonp',
type:type,
data:object,
url:"http://dev.sartle.com/includes/ajax_reviewcomment.php?rid=1178",
success:function(data){
callback(data);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(errorThrown);
}
});
}
Your website doesn't support JSONP.
JSONP is just a fancy way of passing a JSON object to a global callback function via a <script> tag. It circumvents cross-origin restrictions by not sending an AJAX request in the first place, but instead creating a <script> tag.
A JSON response looks like this:
{"foo": "bar"}
But a JSONP response is:
some_callback({"foo": "bar"})
That PHP script doesn't wrap the JSON response in a callback function (whose name is usually specified via the callback GET parameter), so you simply can't make a JSONP request. The request will succeed, but the global callback function will not be called, so you will not be able to use the JSON.
So, to try to circumvent the cross domain issue, using jSONP turned out to be a bad idea. I'm running these calls from a localhost, so i've changed the url in the ajax call to
url:"http://localhost/includes/ajax_reviewcomment.php?rid=1178"
I will build this url to be dynamic so that the current URL always is domain-consistent with the server, and i should be in good shape!
stlll, it seems a cross-domain issue: please try this library https://github.com/padolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js
as a jsonp the result is already a callback function with a javascript object argument. Make sure that the returned function by the server is implemented:
The server could return my_callback({...}). You need to implement my_callback function client-side.
place some alerts/console.log on both success and error functions. Always make a little debug of your own before posting the issue.
as posted in the comment: state the return code of the ajax call.
in type you need put "GET" or "POST"
$.ajax({
contentType: "application/json",
dataType: 'jsonp',
type:type, <<<<<<------ here
data:object,
url:"http://dev.sartle.com/includes/ajax_reviewcomment.php?rid=1178",
success:function(data){
callback(data);
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(errorThrown);
}
});
}

Retrieving user_timeline from Twitter in XML

I'm writing a simple app in HTML and Javascript. I'm trying to retrieve my user_timeline via jQuery's .ajax() method. The problem is that I want to retrieve my timeline in XML but I'm keep failing with this simple task. Here's my code:
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=stepanheller',
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
},
error: function(req, textStatus, error) {
console.log('error: '+textStatus);
}
});
Weird thing is that when I try exactly the same thing but with JSON instead of XML then the script works.
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=stepanheller',
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
},
error: function(req, textStatus, error) {
console.log('error: '+textStatus);
}
});
Can you give me some hints what I'm doing wrong with the request? I know that I'm using old version of API but I won't deal with OAuth right now. Thanks.
It is generally impossible to send a Cross-domain ajax request. It's the general rule.
JsonP is the classic way to work around this limitation, and there is no equivalent for Xml according to my knowledge. Depending on your browser compatibility constraints, you can use XHR2 to achieve this.
Otherwise, the only solution is to set up a server proxy.
Client --Ajax--> Your server --HttpRequest--> Twitter

Categories