简体   繁体   中英

Using AJAX when submitting forms

I'm very new to form submission with AJAX and have been following many tutorials on it's use, however I cannot seem to get it working in my current scenario.

I have a modal with a form inside of it linked to a PHP script and some JQuery AJAX.

When i submit the form the page appears white, I'm fairly sure this is because of the conditional logic in my PHP script.

So, where I have $stmt->rowCount() and the conditional logic it returns nothing as the script does nothing at this point.

Can I link this logic to AJAX success or failure or do I have to return a boolean from my script?

I know this is probably considered a silly question but some clarity would be of great use.

Form

<form id="userForm" method="post" action="test/process_data.php">
    <div class="form-group">
      <label for="email">First name:</label>
      <input type="text" class="form-control" name="forename" id="forename" placeholder="E.g John" required>
    </div>
      <div class="form-group">
      <label for="email">Surname:</label>
      <input type="text" class="form-control" name="surname" id="surname" placeholder="E.g Smith" required>
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" name="email" id="email" placeholder="someone@example.com">
    </div>
    <div class="form-group">
      <label for="company">Company:</label>
      <input type="text" class="form-control" name="company" id="company" placeholder="Company name">
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
    <a href="" class="btn btn-default">Just take me to the partner</a>
  </form>

AJAX Script

<script>

      $("#userForm").submit(function(e) {
         var forename = $('#forename').val();
         var surname = $('#surname').val();
         var email = $('#email').val();
         var company = $('#company').val();

      $.ajax({
          url: "process_data.php",
          type: "POST",
          data: {
              "forename" : forename,
              "surname" : surname,
              "email" : email,
              "company" : company
          },
          success: function(data){
            $("#forename").val('');
            $("#surname").val('');
            $("#email").val('');
            $("#company").val('');

          }
      });

        e.preventDefault(); // avoid to execute the actual submit of the form.

      }


</script>

PHP Script to handle data

if (empty($_POST["forename"]) || 
    empty($_POST["surname"]) || 
    empty($_POST["email"]) ||
    empty($_POST["company"]))
    {

    }
    else{

        $forename = $_POST['forename'];
        $surname = $_POST['surname'];
        $email_address = $_POST['email'];
        $company_name = $_POST['company'];
        $id = rand();
        $date_time = date('Y-m-d');


        try
            {
                // Construct the SQL to add a book to the database
                $sql = "INSERT INTO user_data (forename, surname, email_address, company_name, id, date_time)
                VALUES (:forename, :surname, :email_address, :company_name, :id, :date_time)";
                // Prepare the SQL and bind parameters
                $stmt = $conn->prepare($sql);
                $stmt->bindParam(':forename', $forename);
                $stmt->bindParam(':surname', $surname);
                $stmt->bindParam(':email_address', $email_address);
                $stmt->bindParam(':company_name', $company_name);
                $stmt->bindParam(':id', $id);
                $stmt->bindParam(':date_time', $date_time);
                $stmt->execute();

                // If the statement affected the database
                if ($stmt->rowCount() > 0)
                {

                }
                else{

                }

            } catch(PDOException $e){
                echo "Error: " . $e->getMessage();
            }

    }

Use serialize() method on the form to define the data property in your ajax call. Also added error handling.

  $.ajax({
      url: "process_data.php",
      type: "POST",
      data:  $("#userForm").serialize(),
      success: function(data){
          //Successful
      },
      error: function (XMLHttpRequest, textStatus, errorThrown)
      {
           if (!window.console) console = { log: function () { } };
           console.log(JSON.stringify(XMLHttpRequest), textStatus, errorThrown);
      }
  });

Use preventDefault(); before sending ajax request. Now when the form is done submitting you can do like this.

<script>

      $("#userForm").submit(function(e) {
         var forename = $('#forename').val();
         var surname = $('#surname').val();
         var email = $('#email').val();
         var company = $('#company').val();

e.preventDefault(); // avoid to execute the actual submit of the form.

      $.ajax({
          url: "process_data.php",
          type: "POST",
          data: {
              "forename" : forename,
              "surname" : surname,
              "email" : email,
              "company" : company
          },
          success: function(data){


          }
      });
$("#userForm").fadeOut(800, function()
{
     $(this)[0].reset();
}).fadeIn(800);


      }


</script>

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