2014-02-27 31 views
0

我想用lastInsertId上的成功事件。請求工作正常,我可以插入一個新的元素,但沒有任何回報。阿賈克斯/ PDO回報lastInsertId不工作

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

<?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(); 
} ?> 

我錯過了什麼?

編輯:

通過改變解決: return $bdd->lastInsertId(); 到: echo $bdd->lastInsertId(); 感謝邁克爾Berkowski。

+5

從PHP腳本,而不是'return'ing的價值,你將需要'回聲$ bdd-> lastInsertId();'將其發送到輸出緩衝區,即JavaScript接受它。 –

回答

-1

如果你被導致:

$bdd->lastInsertId(); 

嘗試使用的dataType PARAM在你的Ajax請求(數據類型: 「JSON」)

$.ajax({ 
    url:"edit.php", 
    type:'POST', 
    dataType: "json" 
    data: mydata, 
    success: function(f) { 
     alert(f); 
    }, 
    error: function() { 
     alert('error try again'); 
    } 

而在服務器端,當你得到結果,你應該編碼到json並回顯給瀏覽器。例如:

$req_add->execute(array(
     'posx' =>$positionx, 
     'posy' =>$positiony, 
     'width' =>$lar, 
     'height' =>$haut, 
     'type' =>$typ 
    )); 
    $result = $bdd->lastInsertId(); 
    echo json_encode($result); 
+0

您還可以使用回打印$ bdd-> lastInsertId(); –

-1

服務器端,您可以使用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; 

和客戶端,您可以使用dataContent財產的jQuery AJAX來處理結果:

$.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'); 
    } 
+0

他已經解決了他的問題。不需要進一步的幫助。 –