Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send array with Ajax to PHP script

I have array made by function .push. In array is very large data. How is the best way send this to PHP script?

   dataString = ??? ; // array?
   $.ajax({
        type: "POST",
        url: "script.php",
        data: dataString, 
        cache: false,

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

script.php:

  $data = $_POST['data'];

  // here i would like use foreach:

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

How is the best way for this?

like image 325
Paul Attuck Avatar asked Jan 25 '12 10:01

Paul Attuck


2 Answers

Encode your data string into JSON.

dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString}, 
        cache: false,

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

In your PHP

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

  // here i would like use foreach:

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

Note

When you send data via POST, it needs to be as a keyvalue pair.

Thus

data: dataString

is wrong. Instead do:

data: {data:dataString}

like image 69
xbonez Avatar answered Nov 18 '22 05:11

xbonez


 dataString = [];
   $.ajax({
        type: "POST",
        url: "script.php",
        data:{data: $(dataString).serializeArray()}, 
        cache: false,

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

http://api.jquery.com/serializeArray/

like image 9
John x Avatar answered Nov 18 '22 03:11

John x