Home  >  Article  >  Backend Development  >  Why is my jQuery serialized form not sending data to my PHP script?

Why is my jQuery serialized form not sending data to my PHP script?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 22:25:03463browse

Why is my jQuery serialized form not sending data to my PHP script?

Serializing and Submitting a Form with jQuery and PHP

Problem:

A serialized form using jQuery fails to send data to a PHP script. The server receives no data.

HTML Form:

`




`

JavaScript:

<code class="javascript">$("#contactForm").submit(function() {
  $.post("getcontact.php", $("#contactForm").serialize())
    .done(function(data) {
      // handle response
    });

  return false;
});</code>

Server-Side PHP (getcontact.php):

<code class="php">$nume = $_REQUEST["nume"]; // empty
$email = $_REQUEST["email"]; // empty
$telefon = $_REQUEST["telefon"]; // empty
$comentarii = $_REQUEST["comentarii"]; // empty</code>

Solution:

Replace the jQuery.post() code with the following:

<code class="javascript">var datastring = $("#contactForm").serialize();
$.ajax({
  type: "POST", // method
  url: "your url.php", // action
  data: datastring, // form data
  dataType: "json", // expected response type
  success: function(data) {
    // handle response
  },
  error: function() {
    // handle error
  }
});</code>

Additional Notes:

  • Set dataType to "jsonp" for cross-domain requests.
  • Use beforeSend and complete callbacks for pre-request and post-request actions.
  • Consider using async: false for synchronous requests.
  • Disable caching with cache: false.
  • Refer to the official documentation for more details.

Update

  • var_dump($_POST) should return an empty array.
  • The issue may be server-related, such as a misconfigured PHP.ini file or disabled file uploads.

The above is the detailed content of Why is my jQuery serialized form not sending data to my PHP script?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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