Daniel
Daniel

Reputation: 33

How to send javascript array to php?

I've tried a lots of solution from so, but no one worked for me. So I have a javascript array and i should pass it to php for upload it into mysql.

This code is in a php page, where is an editable grid. If press enter in the grid it creates a new row, with the value of the editeble cell and this value goes into the var val=[]and this should go into mysql via `php.

I've tried two kind of pass from so as you can see below

Code I have:

<script type="text/javascript" >
    var dbs=0;
    var val=[];
    function myFunction(e) {
            if(e.keyCode == 13){
                var newId = (new Date()).valueOf();
                var value=gridbox.cells(1,0).getValue();
                gridbox.addRow(newId,value);                
                val.push(value);
                gridbox.cells(1,0).setValue('');
                gridbox.editCell(1,0);
                dbs=dbs+1;

            }
    }
    function upload(){
        var jsonString = JSON.stringify(val);
             /*$.ajax({
                type: "POST",
                url: "upload.php",
                data: {'data' : jsonString}, 
                cache: false,

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

                }
            });*/
        var jsonData = $.ajax({
                  url: "upload.php",
                  data: { 'data' : val},
                  dataType:"json", 
                      async: false
                  }).responseText;
        }
</script>

UPLOAD.PHP

And it creates new empty row in the db, so it runs, but the $data is empty

//$data = json_decode(stripslashes($_GET['data']));
$data=$_GET['data'];

  // here i would like use foreach:
/*
  foreach($data as $d){
     echo $d;
  }*/


$db_irattar = new indotekDbConnection("irattar");


for($i=0;$i<4;++$i){
$sql="INSERT INTO akt_hely(Tipus,Megnevezes) 
VALUES('2','$data[$i]')

";
}

$db_irattar->Execute($sql);
$db_irattar->Close();
unset($db_irattar);
?>

Network monitor

Upvotes: 2

Views: 4166

Answers (1)

Abu Sayem
Abu Sayem

Reputation: 1290

It seems to me that you are assigning var jsonString = JSON.stringify(val); and sending val in ajax.

try

var jsonData = $.ajax({
              url: "upload.php",
              data: { 'data' : jsonString},
              dataType:"json", 
                  async: false
              }).responseText;

Instead of

var jsonData = $.ajax({
              url: "upload.php",
              data: { 'data' : val},
              dataType:"json", 
                  async: false
              }).responseText;

And decode the json string in php like $data=json_decode($_GET['data']);

Upvotes: 5

Related Questions