0

How do I send values in a JSON array to PHP? Im stuck with how I actually go about making the request to physically post the values to the PHP file.

I have:

 var myArray = ["john","28","theworld","blue"]; //javascript array

 myArray = JSON.stringify(myArray); //to JSON

I understand what to do once the php file has it, so its just the passing.

Many thanks.

jord49
  • 542
  • 2
  • 17
  • 37

2 Answers2

1

Try this hope it will help you.

    var myArray = ["john","28","theworld","blue"]; //javascript array

    myArray = JSON.stringify(myArray); //to JSON

    var request = $.ajax({
          url:'script.php',
          type: "POST",
          data: {"myArray":myArray},
          success: function(data){
             console.log(data);
          }
    });

Get post value from ajax in script.php

    <?php 

     //get post value from ajax
     if(isset($_POST['myArray'])){

        print_r(json_decode($_POST['myArray']));

     }

    ?>
Vijay
  • 421
  • 3
  • 12
  • Thanks very much. Appreciate the responses from yourself and the guy below, but found this most useful. – jord49 Mar 26 '15 at 15:00
0

This would typically be done with AJAX. You can write an AJAX request manually in JavaScript, but it's usually better to use an existing library (e.g. jQuery) to handle this for you.

Below is an example that uses jQuery's post() to post individual values to the imaginary page named somepage.php:

$.post("somepage.php", {
    name: 'John',
    age: 28,
    sky: 'blue',
    pants: 'on'
}).done(function (data) {
    alert("Data submitted: " + myArray);
});

If for some reason you still want to use your json string and post it, you could pass it as a single value named 'data':

var myArray = ["john", "28", "theworld", "blue"]; //javascript array
myArray = JSON.stringify(myArray); //to JSON

$.post("somepage.php", {
    data: myArray
}).done(function (data) {
    alert("Data submitted: " + myArray);
});
Benjamin Ray
  • 1,855
  • 1
  • 14
  • 32