[英]Ajax/PDO return lastInsertId not working
I would like to use the lastInsertId on the success event. 我想在成功事件上使用lastInsertId。 The request work fine I can insert a new element but nothing return. 请求工作正常,我可以插入一个新元素,但是什么也没有返回。
function.js function.js
function add_elem(i)
{
var mydata ="e1="+0+"&e2="+0+"&e3="+100+"&e4="+100+"&e5="+i+"&addelem=1";
$.ajax({
url:"edit.php",
type:'POST',
data: mydata,
success: function(f) {
alert(f);
},
error: function() {
alert('error try again');
}
});
edit.php edit.php
<?php include"inc/config.php";
$positionx=$_POST['e1'];
$positiony=$_POST['e2'];
$lar=$_POST['e3'];
$haut=$_POST['e4'];
$typ=$_POST['e5'];
if(isset($_POST['addelem']))
{
$req_add=$bdd->prepare('insert into elem (element_position_x,element_position_y,element_width,element_height,element_type)
values(:posx,:posy,:width,:height,:type)');
$req_add->execute(array(
'posx' =>$positionx,
'posy' =>$positiony,
'width' =>$lar,
'height' =>$haut,
'type' =>$typ
)
);
return $bdd->lastInsertId();
} ?>
Did I miss something ? 我错过了什么 ?
Edit: 编辑:
Solved by changing : return $bdd->lastInsertId();
通过更改来解决: return $bdd->lastInsertId();
to : echo $bdd->lastInsertId();
到: echo $bdd->lastInsertId();
Thank to Michael Berkowski. 感谢Michael Berkowski。
If you get result from: 如果您得到以下结果:
$bdd->lastInsertId();
Try use dataType param in your ajax request (dataType: "JSON") 尝试在ajax请求中使用dataType参数(dataType:“ JSON”)
$.ajax({
url:"edit.php",
type:'POST',
dataType: "json"
data: mydata,
success: function(f) {
alert(f);
},
error: function() {
alert('error try again');
}
And at server side when you get result you should encode to json and echo backward to browser. 在服务器端,当获得结果时,您应该编码为json并向后回显到浏览器。 For example: 例如:
$req_add->execute(array(
'posx' =>$positionx,
'posy' =>$positiony,
'width' =>$lar,
'height' =>$haut,
'type' =>$typ
));
$result = $bdd->lastInsertId();
echo json_encode($result);
Server side, you can use JSON to format output of your request: 在服务器端,您可以使用JSON格式化请求的输出:
$req_add->execute(array(
'posx' =>$positionx,
'posy' =>$positiony,
'width' =>$lar,
'height' =>$haut,
'type' =>$typ
));
$result = array('id'=>$bdd->lastInsertId());
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo json_encode($result);
exit;
And client side, you can use dataContent property in jquery ajax to handle results : 在客户端,您可以在jquery ajax中使用dataContent属性来处理结果:
$.ajax({
url:"edit.php",
type:'POST',
dataType: "json"
data: mydata,
success: function(data,txt,xhr) {
var myNewId = data.id;
},
error: function() {
alert('error try again');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.