使用 $.ajax 请求使用 PHP 到 MYSQL 数据库的 jQuery 表单处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/363528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:30:08  来源:igfitidea点击:

jQuery Form Processing With PHP to MYSQL Database Using $.ajax Request

phpjquerymysqlforms

提问by

Question:How can I process a form using jQuery and the $.ajax request so that the data is passed to a script which writes it to a database?

问题:如何使用 jQuery 和 $.ajax 请求处理表单,以便将数据传递给将其写入数据库的脚本?

Problem:I have a simple email signup form that when processed, adds the email along with the current date to a table in a MySQL database. Processing the form without jQuery works as intended, adding the email and date. With jQuery, the form submits successfully and returns the success message. However, no data is added to the database.

问题:我有一个简单的电子邮件注册表单,在处理时,将电子邮件与当前日期一起添加到 MySQL 数据库中的表中。处理没有 jQuery 的表单按预期工作,添加电子邮件和日期。使用 jQuery,表单提交成功并返回成功消息。但是,没有数据添加到数据库中。

Any insight would be greatly appreciated!

任何见解将不胜感激!

    <!-- PROCESS.PHP -->
    <?php
        // DB info
        $dbhost = '#';
        $dbuser = '#'; 
        $dbpass = '#';
        $dbname = '#';

        // Open connection to db
        $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
        mysql_select_db($dbname);

        // Form variables
        $email      = $_POST['email'];
        $submitted  = $_POST['submitted'];

        // Clean up
        function cleanData($str) {
            $str = trim($str);
            $str = strip_tags($str);
            $str = strtolower($str);
            return $str;
        }
        $email  = cleanData($email);

        $error = "";
        if(isset($submitted)) {
            if($email == '') {
                $error .= '<p class="error">Please enter your email address.</p>' . "\n";
            } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", $email)) {
                $error .= '<p class="error">Please enter a valid email address.</p>' . "\n";
            }
            if(!$error){
                echo '<p id="signup-success-nojs">You have successfully subscribed!</p>';

                // Add to database
                $add_email  = "INSERT INTO subscribers (email,date) VALUES ('$email',CURDATE())";
                mysql_query($add_email) or die(mysql_error());

            }else{
                echo $error;
            }
        }
    ?>

<!-- SAMPLE.PHP -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function(){ 
                // Email Signup
                $("form#newsletter").submit(function() {    
                    var dataStr = $("#newsletter").serialize();
                    alert(dataStr);
                        $.ajax({
                            type: "POST",
                            url: "process.php",
                            data: dataStr,
                            success: function(del){
                                $('form#newsletter').hide();
                                $('#signup-success').fadeIn();
                            }
                    });
                return false;
                });             
        }); 
</script>
<style type="text/css">
#email {
    margin-right:2px;
    padding:5px;
    width:145px;
    border-top:1px solid #ccc;
    border-left:1px solid #ccc;
    border-right:1px solid #eee;
    border-bottom:1px solid #eee;
    font-size:14px;
    color:#9e9e9e;
    }   
#signup-success {
    margin-bottom:20px;
    padding-bottom:10px;
    background:url(../img/css/divider-dots.gif) repeat-x 0 100%;
    display:none;
    }
#signup-success p, #signup-success-nojs {
    padding:5px;
    background:#fff;
    border:1px solid #dedede;
    text-align:center;
    font-weight:bold;
    color:#3d7da5;
    }
</style>
</head>
<body>
<?php include('process.php'); ?>
<form id="newsletter" class="divider" name="newsletter" method="post" action="">
    <fieldset>
    <input id="email" type="text" name="email" />
    <input id="submit-button" type="image" src="<?php echo $base_url; ?>/assets/img/css/signup.gif" alt=" SIGNUP " />
    <input id="submitted" type="hidden" name="submitted" value="true" />
    </fieldset>
</form>
<div id="signup-success"><p>You have successfully subscribed!</p></div>
</body>
</html>

回答by kgiannakakis

Instead if using data: dataStr, use:

相反,如果使用数据:dataStr,请使用:

data : {param: value, param2: value2}

This is the proper way to do it for POST requests.

这是对 POST 请求执行此操作的正确方法。

Also, I recommend using a form plug-in, like this.

另外,我推荐使用一个表单插件,像这样

回答by Manoj

Plus one to the form plugin, makes life much easier. I often have forms that post back to the same page. I send an extra parameter (ajax=true) which i use to alter what the page returns to the browser ie. just a page fragment that I can inject via innerHTML.

加一个表单插件,让生活更轻松。我经常有回发到同一页面的表单。我发送了一个额外的参数 (ajax=true),我用它来改变页面返回到浏览器的内容,即。只是一个我可以通过innerHTML注入的页面片段。

回答by sumi

check the response coming from the process.php file.echo and die the post values and alert the response because everything seams to be written correctly just matter of sending the post values to process.php. the syntax of Serialize could also be

检查来自 process.php file.echo 的响应并删除 post 值并提醒响应,因为一切都接缝要正确写入只是将 post 值发送到 process.php 的问题。Serialize 的语法也可以是

jQuery('#newsletter').formSerialize();