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

How to Send JSON Data to PHP Using AJAX?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 07:39:02899browse

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>

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>

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>
<code class="php">$obj = $_POST['myData'];</code>

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!

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