Christopher
Christopher

Reputation: 431

ajax doesn't load my php file in the background

I'm having a problem with my ajax call. I'm submitting some info via php to mySQL, the submission part works perfectly, it's adding the data to the database, but the ajax function isn't loading that php in the background, it's loading it in the window and showing the php file results.

Here's the HTML code.

<form action="upload.php" class="addItem" method="post">
      Firstname:<br><input type="text" class="firstname" name="firstname" /><br>
      Lastname:<br><input type="text" class="lastname" name="lastname" /><br>
      Age:<br><input type="text" class="age" name="age" /><br>
      Photo:<br><input type="file" name="image" accept="image/jpeg" /><br><br>
      <input type="submit" class="submitItem" value="Add Row" />
  </form>
  <a href="logout.php">Logout</a>
  </div>

  <script>
  $(document).ready(function(){
    $(".submitItem").click(function(){
    // Start AJAX send
      jQuery.ajax({
        // Enter below the full path to your "send" php file
        url: "upload.php",
        type: "POST",   
        data: data,
        cache: false,
        success: function (html) {
          // If form submission is successful
          if ( html == 1 ) {
            $('.successMessage').show(200);
            $('.successMessage').delay(2000).hide();
          }
          // Double check if maths question is correct
          else {
            $('.errorMessage').show(200);
            $('.errorMessage').delay(2000).hide();
          }
        }
      });
      });
    });

  </script>

Here's the PHP code

<?php

$name = $_POST['firstname'];
$surname = $_POST['lastname'];
$age = $_POST['age'];

if(($name === "") || ($surname === "") || ($age === "")){
    echo "please fill in all fields";
} else {
    $con = mysql_connect("localhost","user","password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    mysql_select_db("my_db", $con);

    $sql="INSERT INTO Persons (FirstName, LastName, Age)
    VALUES
    ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }

    if ($sql) { echo "1"; }
    else{echo "error";}
    }

    mysql_close($con);

?>

Upvotes: 0

Views: 623

Answers (1)

Amber
Amber

Reputation: 526543

Your handler needs to return false; to instruct the browser not to do its regular submission action.

(Also, you should really consider using the submit event of the form, rather than the click event of the button.)

<script type="text/javascript">
$(function(){
  $("form.addItem").submit(function(){
    // Start AJAX send
    jQuery.ajax({
      // ... your parameters ...
    });
    return false;     
  });
});
</script>

Upvotes: 2

Related Questions