Home >Backend Development >PHP Tutorial >How do I Send a Large Array to a PHP Script via AJAX?

How do I Send a Large Array to a PHP Script via AJAX?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 11:48:02381browse

How do I Send a Large Array to a PHP Script via AJAX?

Transmitting Arrays to PHP Scripts via Ajax

Problem:

An array populated using the ".push" function contains extensive data. How can this array be effectively sent to a PHP script?

Best Solution:

Sending the Array:

Encode the array into JSON format before sending it via Ajax.

var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString}, // Encode the data as a key-value pair
        cache: false,

        success: function(){
            alert("OK");
        }
    });

Receiving the Array in PHP:

Decode the encoded JSON string into an array.

$data = json_decode(stripslashes($_POST['data']));

  foreach($data as $d){
     echo $d;
  }

Note:

For POST requests, data should be sent as a key-value pair. Therefore, instead of data: dataString, use data: {data:dataString}.

The above is the detailed content of How do I Send a Large Array to a PHP Script via 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