api - Not getting JSON data when using AJAX, Slim and PHP -
i learning create rest api using slim, got stuck in here. tried many things mentioned on internet still not getting value.
my ajax:
$.ajax({ type: 'post', url: 'pages/search', datatype: "json", data: {'val1':value1,'val2':value2}, success: function(data){ alert(data.val1); } }); my php using slim:
<?php require 'slim/slim.php'; $app = new slim(); $app->post('/search','getvalue'); $app->run(); function getvalue(){ $request = slim::getinstance()->request(); $values= json_decode($request->getbody()); $value1 = $values->val1; // throwing error here - slim application error $value2 = $values->val2; echo "{'val1':'".$value1."'}"; } ?>
you trying read json formatted request:
$values= json_decode($request->getbody()); and outputting invalid json response (probably default content-type: text/html response header).
but passing jquery's data plain object making standard form encoded request:
data: {'val1':value1,'val2':value2}, and forcing jquery treat response json (which isn't):
datatype: "json", assuming want make json request , respond json need to:
format request correctly:
data: json.stringify( { val1: value1, val2: value2} ), contenttype: "application/json", output response correctly:
header("content-type: application/json"); echo json_encode( array( "val1" => $value1 ) ); (nb: have no idea php framework using. header function might not right way deal setting response headers in it).
Comments
Post a Comment