Javascript – PHP how to form submit using ajax

ajaxhtmljavascriptjqueryPHP

I am trying a simple ajax request that does not need to refresh the page upon submit. But I think I did it the wrong way. Any help would be much appreciated.

HTML/JS PAGE

<script>
    $(function () {
        $('form#person').on('submit', function(e) {
            $.ajax({
                type: 'post',
                url: 'addAPerson.php',
                data: $(this).serialize(),
                success: function (o) {
                          =====>    console.log(o); <=== I TRIED DOING THIS BUT NOTHING IS PRINTED
                    alert('MUST ALERT TO DETERMINE SUCCESS PAGE');
                }
            });
            e.preventDefault();
        });
    });     
</script>

<form id="person" action="addAPerson.php" method="post">
  Firstname: <input name="fname" />
  Lastname: <input name="lname" />
  <input type="reset" style="float:right"name="cancel" value="cancel"/>
  <input type="submit" name="submit" value="save"/>
</form>

addAPerson.php

<?php
  $fname = $_POST['fname'];
  $lname =$_POST['lname'];
  $con = mysql_connect("localhost","root","");
  mysql_select_db("person",$con);
  $sql = "INSERT INTO person(firstname, lastname) VALUES('$fname', '$lname')";

  mysql_close();
?>

Best Answer

if you have more than one form on the page, you need to change:

$('form').serialize(),

to:

$(this).serialize(),

Otherwise it will include fields from all the forms in the parameters to this script.

I'd also recommend that the PHP echo something to indicate whether it was successful or not, which the AJAX success function can then display.

You should also sanitize the inputs to the script, and convert from the mysql_xxx functions to mysqli_xxx or PDO, preferably using parametrized queries.