Why is my cross domain JSON calls not working? - json

The remote url http://remote-server/json-data.php contains data in this format:
[{"id":"1","partname":"R1","date":"10/12/2012"},{"id":"2","partname":"R2","date":"10/10/2012"},{"id":"3","partname":"R3","date":"07/12/2012"},{"id":"4","partname":"R4","date":"14/06/2012"}]
This is my jQuery that is supposed to read the above data and display it in the html or php file. This is currently not working:
$(document).ready(function () {
var url = "http://remote-server/json-data.php";
var success = function(data){
data = $.parseJSON(data);
$.each(data, function(index, element) {
$('div.outerBox').append('<div>'+element.partname+'/'+element.date+'</div>');
});
}
$.ajax({
type: 'GET',
url: url,
dataType: "jsonp",
crossDomain: true,
cache:false,
success: success,
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
When I refresh the page, I get an error message in the javascript alert box, something like this: Error: jQuery142452552225_55355545554 was not called.
I tried putting that remote file into my local server and it seems to work fine with $.getJSON() function. Not sure what I am doing wrong here.

If the server isn't prepared to handle JSONP requests it won't work.
JSONP is not strictly a client side manipulation of data, it involves server interaction
When using jsonp the responses should be enclosed in a javascript function.
So to make things simple, lets say for example you have an empty JSON object that the server will return to you. i.e. {}
To make a standard request for the object you would do
$.ajax({
type: 'GET',
url: url,
dataType: "json",
success: function(data) {
alert("Retrieved : " + JSON.stringify(data);
},
error:function(jq, st, error){
alert(error);
}
});
All that does is make a standard HTTP request and retrieve the empty object from the url.
If you want to use JSONP with the same url, you try something like
$.ajax({
type: 'GET',
url: url,
dataType: "jsonp",
crossDomain: true,
success: function(data) {
alert("Retrieved : " + JSON.stringify(data);
},
error:function(jq, st, error){
alert(error);
}
});
What this does is takes the url you have an appends a ?callback={Some Random jQuery function}. In your case the random jQuery function was jQuery142452552225_55355545554. The server has to take that empty JSON object and wrap it in the callback, so instead of returning {} it should have returned jQuery142452552225_55355545554({}) with HTTP content-type header of application/json.
Here is a fiddle of a JSON request to coderwall, which fails, and then tries a JSONP request which works successfully. JSONP Example

The remote url http://remote-server/json-data.php contains data in
this format:
[{"id":"1","partname":"R1","date":"10/12/2012"},{"id":"2","partname":"R2","date":"10/10/2012"},{"id":"3","partname":"R3","date":"07/12/2012"},{"id":"4","partname":"R4","date":"14/06/2012"}]
Well, that's the problem. Your remote url is returning JSON, not JSONP. That's why you cannot consume it. The remote server should return JSONP:
callbackFunctionName([
{
"id": "1",
"partname": "R1",
"date": "10/12/2012"
},
{
"id": "2",
"partname": "R2",
"date": "10/10/2012"
},
{
"id": "3",
"partname": "R3",
"date": "07/12/2012"
},
{
"id": "4",
"partname": "R4",
"date": "14/06/2012"
}
]);
where callbackFunctionName should be dynamically specified by passing a parameter to your server. Like this:
http://remote-server/json-data.php?callback=callbackFunctionName
When you call this url you should return a JSONP response.

Related

JSON parsing from cross domain using jquery ajax

Im trying to parse json from cross domain but im getting error like 405 (Method Not Allowed) in jquery plugin (im using latest plugin only from google) Any solution or suggestions will be great help for me.
Thanks
Basha
Here is my code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://myurl.com/webservice&callback=?",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "jsonp",
data: "{}",
Accept: "",
beforeSend: setHeader,
success: OnGetAllMembersSuccess,
error: OnGetAllMembersError,
});
});
function setHeader(req) {
req.setRequestHeader("Authentication", "Basic credentials");
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("Accept", "application/json");
}
function OnGetAllMembersSuccess(data, status) {
alert(status);
$.each(data.result, function(key, value) {
$("#result").append(key+" : "+value);
$("#result").append("<br />");
});
}
function OnGetAllMembersError(request, status, error) {
alert(status);
}
While using jsonp as dataType, you need to bind a call back function in the server side..
for example, if you need a json response like {"id":"myId"}, at the server side it should be return like "mycallback({"id":"myId"})";
Also you need to write that function in client side too.
function mycallback(json)
{alert(json);}

Web service call from .ajax, maxJsonLength error

I'm using .asmx web service and web service method can serialize to json string(3506 record) by using JavaScriptSerializer class and i don't get any error from VisualStudio.
On the other hand my phonegap app using this service and i can consume with that. But my last method contents 3506 records and when i call this method from javascript i get
"error during serialization or deserialization using the json
javascriptserializer"
error.
Should i use paging or smth on web service? If yes can anybody tell me how to do that? Like i said i can use this method from browser. i can get this error when i call on javascript.
$.ajax({
type: "POST",
url: "WEB_SERVICE_URL",
data: "{ dummyParameter:dummy }",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function() {
app.showLoading();
},
success: function(msg) {
clCard = JSON.parse(msg.d);
alert(clCard.length);
},
complete: function() {
app.hideLoading();
},
error: function(msg) {
app.hideLoading();
alert('Error');
}
});
Please have a look at this. I think helped you.

Crossdomain request

I try to load static html pages from another server.I make crossdomain request.
$(document).ready(function (){
$("div[src]").each(function(){
var staticFileURL = $(this).attr('src');
$.ajax({
url: staticFileURL,
dataType: 'jsonp',
data: {},
error: function(xhr, status, error) {
alert(error);
},
success: function() {
alert("success");
},
jsonp: false,
jsonpCallback: 'jsonpCallback'
});
});
});
But I got in chrome error "SyntaxError:Unexpected token <".
In FF "SyntaxError:Invalid xml attribute value".
What's wrong.Could somebody help me?
JSONP is to get json data from the server, it looks like you are trying to received HTML data.
Try to put your HTML data inside JSON object on the server and then read that HTML on the success callback:
for example, your json data from the server:
{ html: "<html><head>...</head></html>" }
also, your success callback should look like:
success: function(**data**){
}

how to set jsonp callback in retrieving restful web service data via jquery

I have asked a question regarding invalid label on firebug which happens when I try to retrieve data from my restful web service. Most of the answers I received was about setting a callback function. but I can't seem to get the right juice from it. can you show me an exact code on how to do it? or atleast correct the code here:
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
processdata:true,
jsonp: false, jsonpCallback: "success",
url: 'http://localhost:8732/Service1/data/10',
success : function success(data) {
jsonResponse = eval("(" + data + ")");
alert(jsonResponse)
},
error : function(req,status, ex) {
alert(ex);
}
Thanks,
Wow, you've got a lot of unnecessary stuff there. Try this:
$.ajax({
url: 'http://localhost:8732/Service1/data/10',
dataType: 'jsonp',
error: function(req, status, ex) {
// your code here
},
success: function(data) {
//your code here
// Please note: you don't need to 'eval' the json response.
// The 'data' variable will be loaded with the object that the json string represents.
// By the way, don't use 'eval', ever.
}
});
jQuery will take care of the callback on the url. See here: http://api.jquery.com/jQuery.ajax/
UPDATE
Why jsonp? If you're getting this from localhost, why not just json? As discussed in the comments below, your server currently is not capable of a jsonp response, but it can do json.

Cross Domain JSON Request Failing

I am trying to run this code in my browser's console:
$.ajax({
dataType: 'json',
url: 'http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json?callback=?',
success: function (data) {
if(data.resultcode == 1) {
console.log(true);
} else {
console.log(false);
}
},
});
However, I am getting a Cross Domain Request Error. when I try to make a simple JSON request then also same error occurs, because JSON request cannot be made on Cross Domains. however, when you go to this URL:
http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json
You'll be able to see the JSON data. However, a key point written in the documentation of this websites API says that:
json - all conversion data are returned as JSON object. Also JSONP cross domain communication supported usign jQuery.
Thanks in advance.
Use jsonp instead:
$.ajax({
dataType: 'jsonp',
url: 'http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json',
jsonp: "callback",
success: function (data) {
if(data.resultcode == 1) {
console.log(true);
} else {
console.log(false);
}
},
});