简体   繁体   中英

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. The data should then be uploaded to a database upon submission.

However, the email address is not uploaded to the database and I am not sure why. A database connection is definitely established and no error messages are yielded.

I'm a real beginner at using AJAX/jQuery.

Inside index.php:

<form form id="email_submit" 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:

$username = "root";
$password = "root";
$hostname = "localhost";
$database = "emails";

$dbhandle = mysql_connect($hostname, $username, $password)
 or die("0");
echo "Connected to MySQL <br>";

$selected = mysql_select_db("emails", $dbhandle)
 or die("0");
echo "connected to db <br>"; 

$youremail = $mysqli->real_escape_string($_POST["emailaddress"]); 
echo "$youremail";
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):

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);
           }
       });
   });
 }

Output on the webpage:

Connected to MySQL 
connected to db 

Any help is appreciated.

Your script part is wrong. You have not properly closed the functions. It should be more like this

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);
          }
        });
    });
}

That is why you are getting the error

SyntaxError: Unexpected token '}'. Expected ')' to end a argument list.

First, you can put the ajax function at the end of the file between <script></script> tags. Second, edit your function and use serialize() method to submit forms thought jquery. Add a id to your form like

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

and edit the function like this

 $.ajax({
  type  : "POST",
  url   : "insert.php",
  data  : $("#email_submit").serialize(),
  datatype : 'html',
  success: function(data) {         
    alert(data);
  }
});

Also don't forget to sanitize your $_POST variable value with real_escape_string

Add this inside code(show below) script tags <script></script>

$("form").submit(function (ev) {
        ev.preventDefault(); //prevent form from default submit
        $.ajax({
            type: 'POST',
            url: "localhost:8888/insert.php",
            data: $('form').serialize()
        }).done(function (data) {
            console.log(data);
        });
    });

use ev.preventDefault() to prevent form from default submitting
Remove formdata and use $('form').serialize() , it will serialize your form inputs.

You are missing the # in your jQuery selector. It should be:

$("#email_submit").submit(function (ev) { ...

And then that might work, but it's kind of weird. You have a click handler for a button that creates a submit handler on the button's form. This has the potential to create multiple submit handlers for the form (one for each button click) which could have bad side effects. In practice, the button will usually only be clicked once, so you might get bugs that don't show up right away, and are hard to reproduce.

Instead, you should be creating the submit handler once, in the document ready handler. You don't need a click handler at all since clicking a button is just a way of submitting the form.

 $(init); // document ready event binding function init() { // document ready handler function $("#email_submit").submit(ajaxSubmit); // form submit event binding } function ajaxSubmit(ev) { // form submit handler function ev.preventDefault(); $.ajax({ type: 'POST', url: "insert.php", data: { formData: $(this).serialize() }, datatype: 'html', success: function(data) { alert(data); } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="email_submit" action="insert.php" method="post" target="_top"> <label>Email Address</label> <input type="text" name = "emailaddress" /> <input type="submit" value="Add Email"> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM