如何将数据从jQuery传递到php,以便保存到数据库中?

时间:2022-05-18 21:10:29

I've read about the jQuery.ajax method and believe this should be what I need -- but so far can't get it to work.

我读过关于jQuery的文章。ajax方法,并认为这应该是我所需要的——但是到目前为止还不能让它正常工作。

I created a test mysql database with a table called "users", added rows to that table for "name" and "location", and then made sure I could save data to it using the command line, which I could. Then I made a test page with a button on it and added this copy to my scripts file (the $.ajax part comes straight from the jQuery api examples):

我创建了一个测试mysql数据库,其中有一个名为“users”的表,为“name”和“location”向该表添加了行,然后确保可以使用命令行将数据保存到该表中,我可以这样做。然后我做了一个带有按钮的测试页面,并将这个副本添加到我的脚本文件($)。ajax部分直接来自jQuery api示例):

$('#button').click(function(){
    saveData();
});

function saveData(){  
$.ajax({
       type: "POST",
   url: "process.php",
   data: { name: "John", location: "Boston" }
    }).done(function( msg ) {
 alert( "Data was saved: " + msg );
    });
}

I do indeed get an alert message, "Data was saved", but nothing has actually been saved to my database. I must be doing something wrong with process.php, but not sure what. Here's the code in process.php (I set variables for database, db_host, user, etc that I don't display here):

我确实得到了一个警告消息,“数据被保存”,但是实际上没有任何东西被保存到我的数据库中。我一定是程序出了问题。php,但不确定。这是正在处理的代码。php(我为数据库、db_host、用户等设置变量,这里不显示):

// 1. Create a connection to the server. 
$connection = mysql_connect($db_host, $db_user,$db_pwd);

// make sure a connection has been made
if (!$connection){
die("Database connection failed: " . mysql.error());
}

// 2. Select the database on the server
$db_select = mysql_select_db($database, $connection);
if (!$db_select){
die("Database selection failed: " . mysql.error());
}

// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
    $name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));

// INSERT THE DATA 
$query = "INSERT INTO user ( name, location )
              VALUES ( '{$name}','{$location}' )";
        // Confirm if the query is successful.
        $result = mysql_query($query, $connection);
}

6 个解决方案

#1


3  

It's has already been told by others, about using 'success' and 'error' which would be indeed a better method to capture the success/error callback. But that's really not the problem why nothing is inserted. Your Ajax call looks good besides that.

其他人已经告诉过它,使用“success”和“error”确实是捕获成功/错误回调的更好方法。但这并不是什么都没有插入的问题。除此之外,您的Ajax调用看起来还不错。

Another problem that i see is that you're only passing the following params:

我看到的另一个问题是你只通过了以下的参数:

data: { name: "John", location: "Boston" }

But in your PHP code you do check if a submit button was set:

但是在PHP代码中,您要检查是否设置了提交按钮:

if (isset($_POST['submit']))

This is obviously not the case because the only things that are sent are the things you pass in the 'data' attribute of the Ajax call. Instead use:

显然不是这样的,因为发送的内容是在Ajax调用的“data”属性中传递的。而不是使用:

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )

#2


1  

In this example, $_POST['submit'] is not set because you are no sending the form as usual, you are rsendin data with ajax and there isn't any variable called "submit".

在本例中,$_POST['submit']没有设置,因为您没有像往常一样发送表单,您是使用ajax的rsendin数据,并且没有任何变量被称为“submit”。

This may work better:

这可能效果更好:

if ((isset($_POST['name'])) && (isset($_POST['location']))) { // Form has been submitted.
    $name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));

// INSERT THE DATA 
$query = "INSERT INTO user ( name, location )
              VALUES ( '{$name}','{$location}' )";
        // Confirm if the query is successful.
        $result = mysql_query($query, $connection);
}

#3


0  

"Done" doesn't mean "succeeded". Instead of done:, use this to see if it finished successfully or not:

“完成”并不意味着“成功”。不要做:,用这个来看看它是否成功完成:

success: function(data)
    {
       alert(data);
    },
error:function (xhr, ajaxOptions, thrownError){
        alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
    }

#4


0  

all that

所有的

.done(function( msg ) {
     alert( "Data was saved: " + msg );
});

is telling you is that the ajax request is done. Your probably need to look at .success instead. Additionally, your code doesn't show this so I'm assuming that it's not doing this but in order for msg to have anything in your php needs to actually return something. (PHP people help me out with this I'm a .Net guy helping with the JS :) )

告诉您ajax请求已经完成。你可能需要关注成功。另外,您的代码没有显示这个,所以我假设它没有这样做,但是为了让msg在php中包含任何内容,需要返回一些东西。(PHP人帮我解决这个问题,我是。net人,帮我解决JS:)

#5


0  

Since you aren't submitting via a traditional form, but using ajax, I suspect submit isn't part of the post. Check that by putting in the following else clause to your code. If you're hitting that die statement, then remove the if test

由于您没有通过传统的表单提交,但是使用ajax,我怀疑提交不是post的一部分。通过在代码中加入下面的else子句来检查它。如果您点击了die语句,那么删除If测试

if (isset($_POST['submit'])) { // Form has been submitted.
    $name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));

// INSERT THE DATA 
$query = "INSERT INTO user ( name, location )
              VALUES ( '{$name}','{$location}' )";
        // Confirm if the query is successful.
        $result = mysql_query($query, $connection);
} else {
  die("$_POST['submit'] didn't exist");
}

#6


0  

Its a simple mistake. You left submit while posting to process.php while you are checking its existence before updating DB

它的一个简单的错误。你离开提交时,张贴到处理。在更新DB之前检查php是否存在

$('#button').click(function(){
    saveData();
});

function saveData(){  
$.ajax({
       type: "POST",
   url: "process.php",
   data: { name: "John", location: "Boston",submit:"submit" }
    }).done(function( msg ) {
 alert( "Data was saved: " + msg );
    });
}

#1


3  

It's has already been told by others, about using 'success' and 'error' which would be indeed a better method to capture the success/error callback. But that's really not the problem why nothing is inserted. Your Ajax call looks good besides that.

其他人已经告诉过它,使用“success”和“error”确实是捕获成功/错误回调的更好方法。但这并不是什么都没有插入的问题。除此之外,您的Ajax调用看起来还不错。

Another problem that i see is that you're only passing the following params:

我看到的另一个问题是你只通过了以下的参数:

data: { name: "John", location: "Boston" }

But in your PHP code you do check if a submit button was set:

但是在PHP代码中,您要检查是否设置了提交按钮:

if (isset($_POST['submit']))

This is obviously not the case because the only things that are sent are the things you pass in the 'data' attribute of the Ajax call. Instead use:

显然不是这样的,因为发送的内容是在Ajax调用的“data”属性中传递的。而不是使用:

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )

#2


1  

In this example, $_POST['submit'] is not set because you are no sending the form as usual, you are rsendin data with ajax and there isn't any variable called "submit".

在本例中,$_POST['submit']没有设置,因为您没有像往常一样发送表单,您是使用ajax的rsendin数据,并且没有任何变量被称为“submit”。

This may work better:

这可能效果更好:

if ((isset($_POST['name'])) && (isset($_POST['location']))) { // Form has been submitted.
    $name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));

// INSERT THE DATA 
$query = "INSERT INTO user ( name, location )
              VALUES ( '{$name}','{$location}' )";
        // Confirm if the query is successful.
        $result = mysql_query($query, $connection);
}

#3


0  

"Done" doesn't mean "succeeded". Instead of done:, use this to see if it finished successfully or not:

“完成”并不意味着“成功”。不要做:,用这个来看看它是否成功完成:

success: function(data)
    {
       alert(data);
    },
error:function (xhr, ajaxOptions, thrownError){
        alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
    }

#4


0  

all that

所有的

.done(function( msg ) {
     alert( "Data was saved: " + msg );
});

is telling you is that the ajax request is done. Your probably need to look at .success instead. Additionally, your code doesn't show this so I'm assuming that it's not doing this but in order for msg to have anything in your php needs to actually return something. (PHP people help me out with this I'm a .Net guy helping with the JS :) )

告诉您ajax请求已经完成。你可能需要关注成功。另外,您的代码没有显示这个,所以我假设它没有这样做,但是为了让msg在php中包含任何内容,需要返回一些东西。(PHP人帮我解决这个问题,我是。net人,帮我解决JS:)

#5


0  

Since you aren't submitting via a traditional form, but using ajax, I suspect submit isn't part of the post. Check that by putting in the following else clause to your code. If you're hitting that die statement, then remove the if test

由于您没有通过传统的表单提交,但是使用ajax,我怀疑提交不是post的一部分。通过在代码中加入下面的else子句来检查它。如果您点击了die语句,那么删除If测试

if (isset($_POST['submit'])) { // Form has been submitted.
    $name = trim(mysql_prep($_POST['name']));
$location = trim(mysql_prep($_POST['location']));

// INSERT THE DATA 
$query = "INSERT INTO user ( name, location )
              VALUES ( '{$name}','{$location}' )";
        // Confirm if the query is successful.
        $result = mysql_query($query, $connection);
} else {
  die("$_POST['submit'] didn't exist");
}

#6


0  

Its a simple mistake. You left submit while posting to process.php while you are checking its existence before updating DB

它的一个简单的错误。你离开提交时,张贴到处理。在更新DB之前检查php是否存在

$('#button').click(function(){
    saveData();
});

function saveData(){  
$.ajax({
       type: "POST",
   url: "process.php",
   data: { name: "John", location: "Boston",submit:"submit" }
    }).done(function( msg ) {
 alert( "Data was saved: " + msg );
    });
}