We're using php-framework "slim" to build an e-shop. Now we are meeting a problem that we can send a request to server and modify the database(we checked table and it is changed indeed), whereas web end can't get the response from the database(iOS and android end can both get it). Here is the part of the code which sends the request, updates database and gets the response:
$app->post('/tblUser', function($request, $response, $args) {
get_tblUser_id($request->getParsedBody());
});
function get_tblUser_id($data)
{
$db = connect_db();
$sql = "update tblphoneverify set dtCreate = NOW() where strPhone = $data[phone]";
$db->query($sql);
$updateId = $db->affected_rows;
$db = null;
$msg = array(
'stat' => '',
'msg' => ''
);
$msg['stat'] = '1';
$msg['msg'] = 'registration success';
return json_encode($msg);
}
then this ajax segment triggers the click event to execute post and receives the state of the result:
$(function(){
$("#getcheck").click(function(){
$.ajax({
type:"post",
url:"http://192.168.1.108/blue/public/tblUser",
data: {"phone":"13331111111"},
dataType:"json",
//async:false,
contentType: "application/x-www-form-urlencoded",
success:function(data){
alert(1);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert(XMLHttpRequest.readyState);
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.statusText);
alert(XMLHttpRequest.responseText);
alert(textStatus);
alert(errorThrown);
}
})
})
})
the code always skips the "success" part and jumps to "error" directly. So what is wrong with our code? Thanks in advance.
You should send a response from a route callable. Don't json_encode
yourself, instead let Slim do it.
Firstly, return an array from get_tblUser_id
:
function get_tblUser_id($data)
{
$db = connect_db();
$sql = "update tblphoneverify set dtCreate = NOW() where strPhone = $data[phone]";
$db->query($sql);
$updateId = $db->affected_rows;
$db = null;
$msg = array(
'stat' => '',
'msg' => ''
);
$msg['stat'] = '1';
$msg['msg'] = 'registration success';
return $msg;
}
Note that you have a SQL injection vulnerability here. Change the SQL to something like this:
$sql = "update tblphoneverify set dtCreate = NOW() where strPhone = ?";
$db->query($sql, [$data[phone]]);
Next, you need to send a response as JSON from the route callable. Slim has a method to do this:
$app->post('/tblUser', function($request, $response, $args) {
$msg = get_tblUser_id($request->getParsedBody());
return $response->withJson($msg);
});
Slim will now send back your the msg
array with the correct content-type header set, which should help your JavaScript to decode it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments