$.post() behaves different than $.ajax( same paramenters ) - json

I came across something weird, that I want to expose and know if someone as an explanation for it.
Some time back i had a simple post:
$.post("/Route/Save", { myObj: JSON.stringify(myObj), accessToken: getAccessToken()}, function(data)
{
//do stuff
});
and it was working nicely, now doesn't work, and only the accessToken paramenter is correctly received in the route controller
I changed it to:
$.ajax({
url: "/Route/Save",
data: '{ myObj:' + JSON.stringify(myObj) + ',accessToken:"' + getAccessToken()+'"}',
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (data)
{
//Do stuff
}
});
And now it works. I'm using firefox 4 and IE9 and believe the reason is connected to the way the browser is sending the info encoded... in the $.post() case it looks like it sends the data as application/x-www-form-urlencoded
I'll be glad to hear from you guys!
Regards,
byte_slave

I'm not sure why it was working before; perhaps a jQuery update changed behaviour?
As to your question on the content-type, $.post is a shorthand wrapper around $.ajax, and from the $.ajax api page, the default value for the contentType is 'application/x-www-form-urlencoded'.
AFAIK, you can't specify the contentType using $.post(). I could be wrong though.

The equivalent with $.ajax should be
$.ajax({
url: "/Route/Save",
data: { myObj: JSON.stringify(myObj), accessToken: getAccessToken()},
type: 'POST',
success: function (data)
{
//Do stuff
}
});

Related

How to Post JSON Data to server in phonegap

hi i write in this code but i get Error like UNdefined how we can resolve this issue if any one know this answer plz let me know
$.ajax({ type: "POST", contentType:"application/json; charset=utf-8", dataType: "application/json", url:"some url",
data :{familyVoterId:'0',boothId:'0',voterId:'59136604',previousEnrollmentNumber:'29422415',casteId:'62',street:'hamlet',voterRelationId:'8',cadrePrevYear:'',relativeName:'DESSAPPA',previousRollesList:[{fromDateStr:'2012-10-24',cadreRoleId:'1',cadreCommitteeId:'1',cadreCommitteeLevelId:'1',toDateStr:"2013-10-24"}],partyMemberSinceStr:"2001-10-24",uniqueKey:"10d11073-a8b1-4764-bf2f-e2c0a269e9cd",nameType:"Voter",panchayatId:"0",age:28,surveyTimeStr:"2014-10-24 15:05:15",gender:"M",relationTypeId:8,bloodGroupId:3,dobStr:"1968-02-02",nomineeGender:"1",photoType:"VOTER",voterCardNumber:"UXN0862806",longititude:"78.413",aadheerNo:"987654321",candidateAadherNo:"12345678910",educationId:"2",nomineeAge:"21",previousParicaptedElectionsList:[{"electionTypeId":17,candidateId:"30126",constituencyId:"461"}],voterName:"RAMAKRISHNA",occupationId:"1",houseNo:"3-60",cadreFamilyDetails:[],createdUserId:"152",refNo:"TR-T-9999-12985",constituencyId:"282",latitude:"17.4278",nomineeName:"nominee",mobileNumber:"9999999999"},
success: function(data)
{
alert("success");
},
error: function(msg)
{
alert(msg.message);
}
});
Also, in addition, the reason it is failing in the first place is because you need to do a cross-domain post. In order to do this correctly through jQuery, you need to use the following options:
dataType: 'jsonp',
cache: false,
I reproduced your error. In Chrome if you click inspect element and then select the Console tab you can see the error message :
XMLHttpRequest cannot load file:///D:/DeleteME/pyMail/some%20url.
Cross origin requests are only supported for protocol schemes: http,
data, chrome-extension, https, chrome-extension-resource.
As mentioned before you need to specify the data type as jsonp if your are posting to another domain.
Example:
$.ajax({ type: "POST", contentType:"application/jsonp; charset=utf-8", dataType: "application/json", url:"http://www.google.com",
data :{familyVoterId:'0',boothId:'0',voterId:'59136604',previousEnrollmentNumber:'29422415',casteId:'62',street:'hamlet',voterRelationId:'8',cadrePrevYear:'',relativeName:'DESSAPPA',previousRollesList:[{fromDateStr:'2012-10-24',cadreRoleId:'1',cadreCommitteeId:'1',cadreCommitteeLevelId:'1',toDateStr:"2013-10-24"}],partyMemberSinceStr:"2001-10-24",uniqueKey:"10d11073-a8b1-4764-bf2f-e2c0a269e9cd",nameType:"Voter",panchayatId:"0",age:28,surveyTimeStr:"2014-10-24 15:05:15",gender:"M",relationTypeId:8,bloodGroupId:3,dobStr:"1968-02-02",nomineeGender:"1",photoType:"VOTER",voterCardNumber:"UXN0862806",longititude:"78.413",aadheerNo:"987654321",candidateAadherNo:"12345678910",educationId:"2",nomineeAge:"21",previousParicaptedElectionsList:[{"electionTypeId":17,candidateId:"30126",constituencyId:"461"}],voterName:"RAMAKRISHNA",occupationId:"1",houseNo:"3-60",cadreFamilyDetails:[],createdUserId:"152",refNo:"TR-T-9999-12985",constituencyId:"282",latitude:"17.4278",nomineeName:"nominee",mobileNumber:"9999999999"},
dataType: 'jsonp',
success: function(data)
{
alert("success");
},
error: function(msg)
{
alert(msg.message);
}
});
Message is not a property of the XHR object msg in your error callback function. That is why it shows undefined in your alert box. You can try to alert msg.statusText and see the status text.
Please check the documentation http://api.jquery.com/jquery.ajax/
(The jqXHR Object section)

Cross domain ajax call is not working in IE

I am doing a cross domain ajax call.
This is inserting data in the mysql database.
var urlsearch = "http://192.168.10.113:8080/collective-intellegence/StoreClicks?userid=" + userId + "&query=" + query;
$.ajax({
type: 'POST',
url: urlsearch,
dataType: 'json',
success: function (data) {
}
});
When I run the above code it is showing an error message this
XMLHttpRequest cannot load http: //192.168.10.113:8080/collective-intellegence/StoreClicks?userid=1&query=python&url=http://www.ourgoalplan.com/KLMS/TipView.aspx?id=1785. Origin http: //192.168.9.185 is not allowed by Access-Control-Allow-Origin.
but data is successfully inserting the database in all browser except IE.
Please help to solve the problem
Thanks in advance.
As #davidrac suggested, you can use JSONP as below:
jQuery.ajax({
type: 'POST',
url: urlsearch,
dataType: 'jsonp',
jsonp: 'json.wrf'
success: function (data) { }
});
You have to add the json.wrf parameter to your query string with name of your callback function, to get properly padded response from Solr.
You should probably use JSONP or some other workaround.
See here and here for explanation of the problem.
When you are outputting the response from the server, add this header:
Access-Control-Allow-Origin: *
This will make the XHRs in IE to allow. For more information, please check HTTP access control (CORS).
In case of PHP, you can do it this way:
<?php
header("Access-Control-Allow-Origin: *");
?>
This code should work as long as IE is 8+ and the server response include the Access-Control-Allow-Origin: [Allowed origins] HTTP header.
If (XDomainRequet) {
//just an example
var xdr = new XDomainRequest();
xdr.open("post", url);
xdr.send();
}
else
{
$.ajax({
type: 'POST',
url: urlsearch,
dataType: 'json',
success: function (data) {
}
});
}

data binding in Kendo mobile

I am doing a kendo mobile application and I'm trying to bind data from database for listing using json call. I tried with the following code,but its not working Pls help me with this...thanks in advance...
my code is here:
$(document).ready(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "WebService/listing.php",
contentType: 'application/json; charset=utf-8',
datatype: "json"
}
}
});
dataSource.bind("change", function () {
$("#content").html(kendo.render(template, dataSource.view()));
});
dataSource.read();
console.log(dataSource.view());
});
You could try to use the changefunction of the dataSource directly:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "WebService/listing.php",
contentType: 'application/json; charset=utf-8',
datatype: "json"
}
},
change: function() {
$("#content").html(kendo.render(template, this.view()));
}
});
Just some things to consider:
I'm assuming your JSON is correct
You're sure you use POST to get the data
your template is as well defined correctly
You're calling dataSource.read() AFTER the data is loaded (to make sure you're doing this, call read() within $(document).ready(function(){dataSource.read();}); and define the dataSource itself first
I guess the last point is the most crucial ;)
That's all I am doing, so if it doesn't work that way there might be some mistake in the data format itself or in the template definition. Anything like console errors?Cheers

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);
}
},
});