使用$ .ajax请求将jQuery表单与PHP转换为MYSQL数据库 [英] jQuery Form Processing With PHP to MYSQL Database Using $.ajax Request

查看:109
本文介绍了使用$ .ajax请求将jQuery表单与PHP转换为MYSQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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.

任何见识将不胜感激!

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>

推荐答案

如果使用data:dataStr,请使用:

Instead if using data: dataStr, use:

data : {param: value, param2: value2}

这是处理POST请求的正确方法.

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

此外,我建议使用表单插件,例如.

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

这篇关于使用$ .ajax请求将jQuery表单与PHP转换为MYSQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆