Home > Backend Development > PHP Tutorial > How to Send JSON Data to PHP Using AJAX?

How to Send JSON Data to PHP Using AJAX?

Barbara Streisand
Release: 2024-11-01 07:39:02
Original
970 people have browsed it

How to Send JSON Data to PHP Using AJAX?

How to Transmit JSON Data to PHP Using Ajax

In order to convey data to a PHP script in JSON format, it is crucial to be able to send the data effectively using AJAX.

Sending JSON Data

The provided code illustrates an attempt to send JSON data using AJAX:

<code class="javascript">$.ajax({
  type: "POST",
  dataType: "json",
  url: "add_cart.php",
  data: {myData: dataString},
  success: function(data){
    alert('Items added');
  },
  error: function(e){
    console.log(e.message);
  }
});</code>
Copy after login

Receiving JSON Data in PHP

On the PHP side, access the data as follows:

<code class="php">if(isset($_POST['myData'])){
  $obj = json_decode($_POST['myData']);
  // Perform desired PHP operations
}</code>
Copy after login

Troubleshooting

If you encounter an empty array (array(0) {}) when printing $_POST in the PHP script, it is most likely due to an error in the AJAX request.

Remove the line contentType: "application/json; charset=utf-8" from the AJAX request. This is not necessary as the data is already being sent as a string.

Simplified Approach

Alternatively, you can simplify the process by omitting the JSON encoding/decoding:

<code class="javascript">data: {myData: postData},</code>
Copy after login
<code class="php">$obj = $_POST['myData'];</code>
Copy after login

This approach sends the data as a plain object, eliminating the need for additional transformations.

The above is the detailed content of How to Send JSON Data to PHP Using AJAX?. 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