简体   繁体   中英

Send the JS array with ajax to php

I have an array made by function .push . How to send this JS array from this to another php file.Below I have attached the code. The two files are game.js and gallery.php.

Game.js:

   imgarray.push({"img_name":img_name,"x":x_value,"y":y_value,"w":w_value,"h":h_value});

        var st = JSON.stringify(imgarray);
        $.ajax({
          type: "POST",
          url: "gallery.php",
          data: { data :st},

          success: function(data){
            console.log(st);
            alert("OK");

          }

      });

Gallery.php:

  <?php
  $data = json_decode(stripslashes($_POST['data']))[0];
  foreach($data as $d){
  echo($d. '</br>');
  }?>

I tried the above code, but I dont know why it produces error. The error I received is Undefined index: data, from the second file (gallery.php).

Can someone help me fix this issue and help me to send the array with ajax to php.

If in your game.js you are calling .push on an array with a certain object, then the $_POST['data] would give you that array. You need to go further inside that array to get to the "push"ed object. Here is how I changed you game.js

var imgarray = [];
imgarray.push({
    img_name: "myImg",
    x: "x",
    y: "y",
    w: "w",
    h: "h",
});

var st = JSON.stringify(imgarray);
$.ajax({
    type: "POST",
    url: "gallery.php",
    data: { data: st },

    success: function (data) {
    console.log(st);
    alert("OK");
    },
});
}

and then your gallery.php would change to

$data = json_decode(stripslashes($_POST['data']))[0];
foreach ($data as $d) {
    echo($d. '</br>');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM