ajax call to cross domain using jsonp - ajax

Hello I am struggling to get this work.
var url = 'http://xxxx/getCustomerCardInfo?requestor_email=honey#gmail.com&callback=?';
$.getJSON(url, function(data){
alert(data);
});
The ajax call is successful. But this url gives the JSON in response i.e
{"targetRequestUri":"/getCustomerCardInfo","javax.servlet.request.key_size":256,"outputMap":{"emailId":"honey#gmail.com","orderList":[{"orderId":"ST210340","orderDate":"2013-04-24 07:12:54.187","orderStatus":"ORDER_COMPLETED","totalMoney":1}],"partyId":"10810","customerName":"honey goyal","telephoneNumber ":"9023605155"},"_FORWARDED_FROM_SERVLET_":true,"javax.servlet.request.cipher_suite":"DHE-RSA-CAMELLIA256-SHA","thisRequestUri":"json"}
But my Firefox error console gives the error in JSON:-
SyntaxError: invalid label
on second character of beginning of JSON, i mean on " in
{"targetRequestUr
And I does not get any alert. Any idea what i was doing wrong.
I think this need only JSONP response and padding is missing in above JSON.

Got the solution. I need to append padding before the JSON from web Server.
But this is not perfect solution according to me because it force me to change third party code. Still waiting for the perfect one so it can work by only changes to client side scripting. like
functionName({"firstName": "John","lastName": "Smith","age": 25});

Related

reCaptcha invalid json response

Using the recaptcha javascript client ( http://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit ) the automatic request (GET https://www.google.com/recaptcha/api2/userverify?k=XXXXXXXXX) after you select the correct images returns an invalid json which afterwards is sent to back to google and their json validation fails. This worked as expected for months now. Not anymore :(
Server side library used reCaptcha PHP (1.1)
Response
)]}'
["uvresp","03AHJ_Vuup5SJJ583dSIfezFl80dp2AlJ_rZpz3vqGWlOTmbjZqH8izwjruJASNhQI0tOOnmj2Pzg14xMw7dryeqVfTGhx6dg_x2i0PRA1ZeDyrBNn8DX-w5S262Zb3_ZWKj5JDBiqPVnXtNLGbyBxjd97VHanspJWU_-qKWLSWVKxLK6n3lm9Biw33oUCEiGA39GNa09Z6TSAEtnolQCf_LPPRWKoE_e50f2s5ZpUVG5GNVdX7qGBRwphTgcUhwOjA8uYTzmA9co3Jwk2KR5UQ0zzVRJzRZZTBuK9km3PE1WV05ACAwrJi29niDpVaRmpooAnIkHNgGyGBu7u3W7gU6YAHtwya8PYhdF__G_MMG8XpVFDTBa196hKD6hxw-E2PsxmoIQJrU1K89mmzNIh-xLNQ7KJvrBMzVf8A5FHyUQgL5UNDWVwSkWCdC_3swxBzi7R3p8VIrUtkIqJFA_GSAxy0cBRJ8J55Pfs5rzhfR8j-x1hGCzi_6vJrbrwfNesoLEB7GWJtElcljhBYvcDNzU_B_VJ7Sck-6i1Nd0qdmtSiCRZYNyaZ8uGLoDdNgCY-0Oi4802AlI26H7TjGBcKnr4gmaHXTNRf1W7x_3FV05DxVsTqeAlo8zGqmiVqcgmX64BbLK4fD9Xoait1_Lp5vK26fCaOQmGKF7CJaYPuxnX-zXgSkfZDCG6rs6xv1CfZQnIKD0W3Yz522VD4YdNfATb3FywhFWbZuxoBIt6vslZDlPXh2MYOkAmYfIPIo8WoWazMoLI_8iNBZPiMlRL0PS5aQiLSrvbf-sknMHhfM2MJYsfrQjC52aDRaHYdcZbY6Wxlhw0tQEknX8B47_DAQzCKkpoFsecO1eMHuInIykZ1l7TOdZMytI-NzGg21KeKAE8dK6ZWee0UEqDJvCkj5aH5TQcBA--ygbOS186bAptUP5n6WvORx1Nb2ZU_AF9fB23PJWH1xvB4gZoNDvhLmdpkE1Po9Lyim1P61E2rrgYjWgPRwT4jUo",1,120]
Any ideas?
Thanks
I think it's a duplicate of https://stackoverflow.com/a/36862268/2140017
And here is my answer from that link:
Actually the value returned is not valid json but well parsed by the
Google's API.
Is it a protection ? I don't know, but if you look at the javascript,
you can find that:
var jm=function(a,b,c,d,e,g,h,l,r){this.xl=a;this.$c=c||"GET";this.Ka=d;this.Gg=e||null;this.Td=m(h)?h:1;this.ye=0;this.xh=this.Nh=!1;this.uh=b;this.Mh=g;this.md=l||"";this.Zb=!!r;this.Wf=null};f=jm.prototype;f.getUrl=function(){return this.xl};f.ug=function(){return this.$c};f.Ca=function(){return this.Ka};f.fi=function(){return this.Zb};f.bi=function(){return this.md};var nm=function(){G.call(this);this.nj=new hm(0,mm,1,10,5E3);H(this,this.nj);this.ad=0};x(nm,G);var mm=new Nh;nm.prototype.send=function(a){return new Lc(function(b,c){var d=String(this.ad++);this.nj.send(d,a.Uf.toString(),a.ug(),a.Ca(),mm,void 0,u(function(a,d){var h=d.target;if(Xk(h)){var l=a.ml;h.B?(h=h.B.responseText,0==h.indexOf(")]}'\n")&&(h=h.substring(5)),h=Hg(h)):h=void 0;b(new l(h))}else c(new om(a))},this,a))},this)};var om=function(a){y.call(this);this.request=a};x(om,y);
especially take a look at:
var l=a.ml;h.B?(h=h.B.responseText,0==h.indexOf(")]}'\n")&&(h=h.substring(5)),h=Hg(h)):h=void 0;`
The parser explicitly checks that the value begins by )]} and strips
it.
I suggest you to just apply the same substring on the "json" string

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.
Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}
Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):
$.ajax({
type: 'GET',
url: 'http://username:api-key#www.kanbanpad.com/api/v1/projects.json',
contentType: 'application/json',
dataType: 'jsonp',
converters: {
'jsonp': jQuery.parseJSON,
},
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log(textStatus+': '+errorThrown);
}
});
If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.
It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")
So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.
It works just as well, it just requires an extra step is all.
Just for anyone that was looking for a solution.
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering
function to sanitize the response. You should return the sanitized data. The function
accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
I would change the content type in the dataFilter interceptor to json. Bear in mind this affects all ajax calls, so use info from data to decide which ones you want to convert.
Verify that your server is sending a jsonp response. This means the json should be enclosed with a string of your callback.
The callback name is passed in the parameters, and if you're not setting it explicitly, looks something like: jQuery15102810791094068532_1300988427891 (As per http://www.json-p.org/)
On your server, you need to format the response:
jQuery15102810791094068532_1300988427891({...json response ...});
Where you use the callback defined in your GET parameter 'callback'.
You might try setting the type to "json" and see if it works. I've had a number of parsererror's with the jquery's jsonp - you might try http://code.google.com/p/jquery-jsonp until it's a bit smoother.
Try changing your content-type to this
contentType: "application/json; charset=utf-8",

JQuery ajax calls not working in Firefox browser

I am trying to test Jquery ajax calls in Firefox but it it not working. I mean my server is not receiving any requests. But when I test in IE8 it works fine. Here is my ajax call:
$("#getWeatherReport").click(function(){
$cityName = "New York";
$.ajax({
type: "POST",
dataType:"xml",
url: "http://localhost:8080/Test/WeatherServlet",
data: "cityName="+$cityName,
success: function(data) {
alert($("report", data).text());
},
error: function(xhr, textStatus, errorThrown) {
alert('ERROR['+xhr.statusText+']');
}
});
});
It is not even calling error function. And from my server code(java) I am setting content type as "text/xml".
Any suggestions?
Your string is not correctly serialized, I'm not sure if that's the issue, but it may be and it's definitely a potential one for later, try this for an immediate test:
var $cityName = "New+York";
As a more permanent solution, pass data as an object, like this:
data: {cityName: $cityName},
Have you installed Firebug?
Your best bet would be to install Firebug, which comes with a console that'll notify you of any javascript errors. You can also use it (via the "Net" tab) to monitor all requests made by your page.
From what I can see, your code looks OK (other than the possible issue pointed out by #Nick Craver)
Also, why the '$' on your cityName variable? The '$' prefix in Javascript is meant to be reserved for machine-generated code (so that it has no chance of conflicting with user code).
try installing firebug plugin in ff :: https://addons.mozilla.org/en-US/firefox/addon/1843/
Then check the :::: Net Tab >> All selected
Refresh the page and see is your ajax call actually getting called. If yes is there any syntax error in the call or any variable null error. If all is fine then you can think of further issues
Usually, when I end up with a parseerror that means that the return header type is wrong or that somehow the server sent extra data with the response. For instance, if I'm looking to get JSON back and I get the JSON and some HTML from x-debug.
Also, The OPTIONS request is for cross-domain requests which is what #Nick was alluding to.
A helpful link to get you started.

Why do I get this 501 Not Implemented error?

I am performing the following AJAX call:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': 'me#mydomain.com',
'api_key': 'MYAPIKEY',
'user': 'me#mydomain.com',
'category': 'MY_CATEGORY'
},
function(response){
alert('received response');
}
);
});
and I get no alert message as expected. Instead, Firebug says I get "501 Not Implemented."
Why? What do I need to do to fix this?
If I go to the URL corresponding to the AJAX call in Firebug, I get a JSON file as a download, and it contains the expected data.
One thing I've noticed is that firebug says OPTIONS instead of GET:
alt text http://grab.by/grabs/b1a13d92a4fc69aa310880a5d7a06b95.png
I don't know if this is related, but generally when requesting JSON on the client to a server in a different domain you'll need to use JSONP instead of JSON due to the Same Origin Policy. Unfortunately, it doesn't appear that their API supports using JSONP -- so they must expect you to interact with their site from your server. In that case you'll need proxy methods on your server to translate the calls to their API so that the client calls are made to a server in the same domain as the page.
As this is the top Google match for "jQuery 501 (Method not implement)" I thought I'd share what worked for me when experiencing this on the same domain (which is not your problem).
My problem was that I was not returning valid JSON, I was just returning "1". So to fix this, either:
Ensure you return valid JSON, or if you don't require a JSON response,
Swap your call to use $.ajax instead of $.getJSON, or
If you're already using &.ajax, remove type: "json"
Hope that helps some people.
I had the same problem, and realized it was an encoding problem. It was solved by encoding the values of the data sent to the server. Try something like:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': encodeURIComponent('me#mydomain.com'),
'api_key': encodeURIComponent('MYAPIKEY'),
'user': encodeURIComponent('me#mydomain.com'),
'category': encodeURIComponent('MY_CATEGORY')
},
function(response){
alert('received response');
}
);
});
end then decode the data on backend. Hope it helps someone.

jquery ajax error json response

i have jquery global error event set, like following:
$("#message_alert").ajaxError(function(event, XMLHttpRequest, settings, thrownError){
ajax_error(XMLHttpRequest);
});
and ajax_error method gets the XMLHttpRequest parameter totally fine init. now the request which XMLHttpRequest gets, it also have json data from the backend in XMLHttpRequest.responseText
now i want to know, how can i parse this json data, i tried doing
eval("var request = "+XMLHttpRequest.responseText);
which for some reason was working fine, but dose not work anymore and i know for sure that data is getting back to ajax response. maybe something im doing wrong.. well firebug shows following error from it, i dont know what im doing wrong
Error:
missing ; before statement
http://basit.io.im/javascript/global.js
Line 127
btw this is the same eval line number. any ideas?
Have you tried -
eval("var request = XMLHttpRequest.responseText");
That should fix the error you are getting.

Resources