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

时间:2022-11-24 13:21:36

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>

3 个解决方案

#1


3  

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.

此外,我建议使用表单插件,如以下所示。

#2


1  

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),用于修改页面返回给浏览器ie的内容。只是一个页面片段,我可以通过innerHTML注入。

#3


0  

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

检查来自过程的响应。php文件。回传和结束post值,并通知响应,因为要正确写入所有内容,只需将post值发送到process.php即可。序列化的语法也可以是

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

#1


3  

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.

此外,我建议使用表单插件,如以下所示。

#2


1  

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),用于修改页面返回给浏览器ie的内容。只是一个页面片段,我可以通过innerHTML注入。

#3


0  

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

检查来自过程的响应。php文件。回传和结束post值,并通知响应,因为要正确写入所有内容,只需将post值发送到process.php即可。序列化的语法也可以是

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