Submit Form Using Ajax, PHP and jQuery

I’m working on a webpage that features a popup window that prompts the user for his/her email address. This data is then uploaded to a database. I’m a real beginner at using AJAX/jQuery and I have been experiencing issues.

Inside index.php:

<form action="insert.php" method="post" target="_top">

   <label>Email Address</label>
   <input type="text" name = "emailaddress" />
   <input type="submit" value="Add Email" onClick="send_data_to_server()">
</form>

Inside insert.php (once a database connection has been established):

$youremail = $_POST["emailaddress"]; 
mysql_query("INSERT INTO email_table (emailAddress) VALUES ('$youremail')");
echo json_encode($youremail);

The AJAX script (placed at the end of the index page body):

<script>
  function send_data_to_server() {

    $("email_submit").submit(function (ev) {
        ev.preventDefault();
        $.ajax({
          type : 'POST',
          url : "insert.php",

          data  : { "formData" : $("#email_submit").serialize() },
          datatype : 'html',
          success: function(data) {
          alert(data);
      }
    });

</script>

Any help is appreciated.


Source: ajax

Leave a Reply