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
Release: 2024-11-13 11:48:02
Original
335 people have browsed it

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");
        }
    });
Copy after login

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;
  }
Copy after login

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!

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