php - Javascript alternative of jQuery.ajax() - facing errors -
this js object
var datas = { name: "xyz", age:21, } var datas2 = json.stringify(datas);
the below ajax request passing datas correctly
$(function(){ $.ajax({ url:'two.php', type:'post', datatype:'html', data:{data:datas2} }); });
response in developer tools:
array ( [data] => {"name":"xyz","age":21} )
now tried javascript ajax reuest
var xmlhttp; if (window.xmlhttprequest) {// code ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } else {// code ie6, ie5 xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { } } xmlhttp.open("post","two.php",true); xmlhttp.setrequestheader("content-type","application/x-www-form-urlencoded"); // xmlhttp.setrequestheader("content-type","application/json"); xmlhttp.send(datas2);
response in developer tools:
array ( [{"name":"xyz","age":21}] => )
where going wrong?
you sending 2 different values. jquery convert object {data: datas2}
string
data={"name":"xyz","age":21}
whereas xmlhttp.send(datas2)
send string
{"name":"xyz","age":21}
that's big difference! in second case {"name":"xyz","age":21}
treated parameter name instead of value see developer tools.
if want send same payload, have do
xmlhttp.send('data=' + datas2')
Comments
Post a Comment