简体   繁体   English

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

[英]How can I pass data from jQuery to php for saving into a database?

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. 我用一个名为“users”的表创建了一个测试mysql数据库,在该表中为“name”和“location”添加了行,然后确保我可以使用命令行将数据保存到它,我可以。 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): 然后我创建了一个带有按钮的测试页面,并将此副本添加到我的脚本文件中($ .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. 我必须对process.php做错了,但不确定是什么。 Here's the code in process.php (I set variables for database, db_host, user, etc that I don't display here): 这是process.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);
}

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. 除此之外,你的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. 显然不是这种情况,因为发送的唯一内容是您在Ajax调用的“data”属性中传递的内容。 Instead use: 而是使用:

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

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

"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);
    }

all that 这一切

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

is telling you is that the ajax request is done. 告诉你是ajax请求已经完成。 Your probably need to look at .success instead. 您可能需要查看.success 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. 另外,你的代码没有显示这个,所以我假设它没有这样做,但为了让msg在你的php需要实际返回一些东西。 ( PHP people help me out with this I'm a .Net guy helping with the JS :) ) PHP人帮我解决这个问题,我是一个帮助JS.Net人:))

Its a simple mistake. 这是一个简单的错误。 You left submit while posting to process.php while you are checking its existence before updating DB 在更新数据库之前检查其存在时,您在发送到process.php时保持submit

$('#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 );
    });
}

Since you aren't submitting via a traditional form, but using ajax, I suspect submit isn't part of the post. 既然你没有通过传统形式提交,而是使用ajax,我怀疑提交不是帖子的一部分。 Check that by putting in the following else clause to your code. 通过在代码中添加以下else子句来检查它。 If you're hitting that die statement, then remove the if test 如果您正在使用该死语句,则删除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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM