Home > Web Front-end > JS Tutorial > How Can I Use jQuery Ajax POST to Submit a Form to PHP Without Page Redirection?

How Can I Use jQuery Ajax POST to Submit a Form to PHP Without Page Redirection?

Linda Hamilton
Release: 2024-12-23 16:58:13
Original
396 people have browsed it

How Can I Use jQuery Ajax POST to Submit a Form to PHP Without Page Redirection?

jQuery Ajax POST with PHP Example

Submitting Form Data Without Redirecting

To avoid page redirections caused by form submissions, jQuery Ajax provides a solution for capturing form data and sending it asynchronously to a PHP script. Here's an example:

Form (form.html):

<form>
Copy after login

jQuery (script.js):

// Prevent default form submission
$("#foo").submit(function(event) {
  event.preventDefault();

  // Serialize form data
  var serializedData = $(this).serialize();

  // Send data to 'form.php' using Ajax
  $.ajax({
    url: "form.php",
    type: "POST",
    data: serializedData,
    success: function(response) {
      console.log("Data sent successfully.");
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.error(errorThrown);
    }
  });
});
Copy after login

PHP (form.php):

<?php
  // Retrieve and process posted data
  $bar = isset($_POST['bar']) ? $_POST['bar'] : null;
  // ... perform database operations using $bar ...
?>
Copy after login

Using this approach, you can capture form data and send it to a PHP script without page redirects or browser refresh. Remember to sanitize all posted data to prevent malicious code injection.

The above is the detailed content of How Can I Use jQuery Ajax POST to Submit a Form to PHP Without Page Redirection?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template