Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

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>

2 Answers

Instead if using data: dataStr, use:

data : {param: value, param2: value2}

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

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

like image 114
kgiannakakis Avatar answered Jul 12 '26 08:07

kgiannakakis


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.

like image 40
Manoj Avatar answered Jul 12 '26 07:07

Manoj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!