html - confusion with jquery , ajax post -
i have simple html page , , using jquery/ajax , trying send simple json file php server.the behavior of script though confusing..
first of tried , have found on web(other questions) :
script1
var data = {"deviceuuid":"lssfds998", "os":"bb", "pushtoken":"l1355436gdfsfdsl"}; $.ajax({ type: "post", url: "http://192.138.4.115/server_cityinfo/register.php", data: data, contenttype: "application/json; charset=utf-8", datatype: "json" }).success(function(response, status, xhr){ console.log(response); console.log(status); console.log(xhr); });
script1 , sends empty (null) json file server.
script2
var data = {"deviceuuid":"lssfds998", "os":"bb", "pushtoken":"l1355436gdfsfdsl"}; $.ajax({ type: "post", url: "http://192.168.4.113/server_cityinfo/register.php", data: data, //contenttype: "application/json; charset=utf-8", datatype: "json" }).success(function(response, status, xhr){ console.log(response); console.log(status); console.log(xhr); });
in script2 , comment line contenttype: "application/json; charset=utf-8"
results better , on server side like: deviceuuid=lssfds998&os=bb&pushtoken=l1355436gdfsfdsl
. still not in json form need it.
script3
var data = '{"deviceuuid":"lssfds998", "os":"bb", "pushtoken":"l1355436gdfsfdsl"}'; $.ajax({ type: "post", url: "http://192.168.4.113/server_cityinfo/register.php", data: data, //contenttype: "application/json; charset=utf-8", datatype: "json" }).success(function(response, status, xhr){ console.log(response); console.log(status); console.log(xhr); });
in script3 , data variable string.. see , wrap inside ' '
. time , do json correctly on server.
however when comment datatype: "json"
line , json correctly on server. whats going on here? have feeling , cant encode data json in end have manually. wrong though? need specify datatype
, contenttype
in request? if make data fine json string , : '{"deviceuuid":"lssfds998", "os":"bb", "pushtoken":"l1355436gdfsfdsl"}'
, send without using aforementioned parameters , correct?
for fulfilling purposes how server script looks :
// use php://input raw $_post results. $json = file_get_contents('php://input'); $json_post = json_decode($json, true); //creating variables received json $deviceudid = $json_post['deviceuuid']; $os = $json_post['os']; $pushtoken = $json_post['pushtoken'];
have on following changes.
your json array should :
arr = '[ { "deviceuuid": "lssfds998", "os": "bb", "pushtoken": "l1355436gdfsfdsl" } ]'; $.ajax ({ type: "post", url: " domain/server_cityinfo/register.php", data: {data:arr}, success : function(result) { // } });
and server side :
<?php $data = $_post['data']; $json = json_decode($data); // json array ?>
hope work. thanks
Comments
Post a Comment