2015-12-02 63 views
-3

我想插入一些数据到mySQL数据库使用AJAX和jQuery $ .post。我试图测试功能如下

的index.html:代码片段(已使用jQuery许多其他功能)

$.post( 
    "updateDatabase.php", 
    { name: "Zara" }, 
    function(data) { 
     //$('#stage').html(data); 
     alert('Success'); 
    } 
); 

updateDatabase.php

<?php 
if($_REQUEST["name"]) { 

    $name = $_REQUEST['name']; 
    echo "Welcome ". $name; 
    echo "<script>alert('Im here')</script>"; 
} 
?> 

什么我越来越是一个“成功”的警报,没有别的(这是$ .post的回调函数)。我已经研究了很多,发现了一些相似但不同的问题。但是我的问题没有解决,因为对于这个特定问题没有令人满意的解决方案。

+0

试试这个安全的方法ajax调用不像导入,da来自updateDatabase.php的ta以成功函数的数据变量的形式传递给ajax – madalinivascu

+0

好的。现在我明白了。我想我必须使用数据变量来获得输出。 –

+0

你是对的我的回答 – madalinivascu

回答

1

您正在呼应字符串echo "alert('Im here')";。所以,

  1. 它不能被视为一个JavaScript函数。
  2. 您没有在成功回调中使用回复。

你可以做的是:

function(data) { 
    alert('Success: '+data); 
    // outputs: Success: Welcome Zara I'm here 
} 

,并在PHP:

echo "Welcome ". $name . " I'm here"; 
+1

现在我知道我犯的错误。对不起。这是我第一个$ .post。 –

+0

@danimvijay不要担心它发生在这里,当你是新的。 – Jai

0

更改此

echo "alert('Im here')"; 

echo "Im here";// no need of alert. 

function(data) { 
    alert(data); 
      ^// will alert Im here 
} 

您还可以使用

.done(function() { 
    alert("Success"); 
}) 

最终代码

$.post("example.php", function() { 
    alert("success"); 
}) 
.done(function() { 
    alert("second success"); 
}) 
0

使用JSON作为返回数据

$.post( 
    "updateDatabase.php", 
    { name: "Zara" }, 
    function(data) {//data is all the echoed text from the updateDatabase.php in our case a json string 
     alert(data.message); 
    } 
); 

<?php 
if($_REQUEST["name"]) { 

    $name = $_REQUEST['name']; 
    echo json_encode([message =>"Welcome ". $name]) 

} 
?>