0

I am using AJAX to send inputs from a webpage to a PHP file to then be entered into a database. Here is my JavaScript file:

var pageLoaded = function () {
var submitButton = document.getElementById("submit");
if (submitButton) {
    submitButton.addEventListener("click", submit, true);
}
};

var submit = function () {

var xhr, changeListener;


var form = document.getElementById('item_form');
var inputs = form.getElementsByTagName('input');

// create a request object
xhr = new XMLHttpRequest();

// initialise a request, specifying the HTTP method
// to be used and the URL to be connected to.
xhr.open("POST", "../php/add_item.php", true);
console.log(inputs[0].value); // debugging

// Sends the inputs to the add_item.php file
xhr.send(inputs);
};

window.onload = pageLoaded;

Here I am trying to send inputs from a form to a PHP file called add_item.php located "../php/add_item.php" in my file system. I am pretty sure this code works and sends the inputs to the PHP file in an array.

My question is, how do I then use $_REQUEST within that file to be able to use the inputs within the array to send to a database? Or, what is the best way of doing this?

benharris
  • 587
  • 3
  • 10
  • 19

3 Answers3

2

The xhr.send() method only accepts a string. If you want to send an array you have to flatten it into a string before posting. You can do this easily using the JSON.stringify() method in javascript, then use json_decode() function in PHP on receiving it.

Also for PHP to receive the data properly in the $_POST[] variable (or $_REQUEST if you must, but not recommended) you need to set a name for the POST variable and URL-encode your JSON text like this:

var json_array = JSON.stringify(inputs);    
xhr.send('myJSONData=' + encodeURIComponent(json_array));

On the PHP side you shouldn't need to use urldecode() because the server stack expects to receive POSTed name-value pairs url-encoded. But you will need to use json_decode on the posted variable to get the array back, e.g.:

php_array = json_decode($_POST["myJSONData"]);

You will see other methods to do this, including setting the xhr POST content-type header to JSON, but in my experience this is the path of least resistance.

Also note whilst it is possible to send an "array" of objects in an HTML form like this:

<input type="text" name="myArray[]" value="val1">
<input type="text" name="myArray[]" value="val2">
<input type="text" name="myArray[]" value="val3">
<input type="text" name="myArray[]" value="val4">
  • which will result in an array being available within PHP in the variable $_POST["myArray"], there is no easy equivalent of this using the XHR object (AJAX method). JSON.stringify() is IMO the easiest way to go.
  • `Uncaught TypeError: Converting circular structure to JSON` I did consider using json before though! Do you know what would be causing this? – benharris Dec 19 '13 at 14:07
  • Probably because you're trying to stringify more than the array of values. The array you're trying to pack in above example is the array of DOM objects returned by getElementsByTagName(). The objects will have a ref to e.g. parent, which itself will have refs to its children, hence circular references. There's a couple of examples of getting around this here: [link](http://stackoverflow.com/questions/9382167/serializing-object-that-contains-cyclic-object-value) and [link](http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json) – James Firth Dec 19 '13 at 14:55
0

The variables inside the $_REQUEST are stored as an array. To access them you would do something similar to this:

echo $_REQUEST['input_1'];

To view all the variables (in a nice format) sent by the JS you could use this code:

echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
MrHunter
  • 1,892
  • 1
  • 15
  • 23
  • Thank you, your second example prints out `Array()` on the page... I'm guessing this is because `$_REQUEST` is an array holding my array of inputs, I don't know how to take each of those array elements and flatter them out into their own variables again – benharris Dec 19 '13 at 13:57
  • That means it's an empty array and nothing is being passed to the $_REQUEST variable. – MrHunter Dec 19 '13 at 13:59
  • I assume it is empty because of what @james-firth has just said about "xhr.send() method only accepts a string" – benharris Dec 19 '13 at 14:08
  • Most likely, try looking at this thread to get a better understanding to accomplish this using jQuery: http://stackoverflow.com/questions/7426085/jquery-getting-form-values-for-ajax-post – MrHunter Dec 19 '13 at 14:12
0

You can't do it in the way you are doing it. You send "input" array which is incorrect. You should prepare array of input values. Morover, I'd recommend you to use JQuery.

 $(function (){
  $("#submit").click(function (){
   //the way to get input values and names
   var arr = [];
   $("input").each(function (index,value){});
       arr.push([$(value).attr('name'), $(value).val()];
   });
   // it can be replaced also via serialize() funciton

   //ajax
   $.post( "../php/add_item.php", arr)
   .done(function( data ) {
      //data has been send response is in data object
   });
  });
 });

In PHP you can get these values via $_POST. $_REQUEST is not needed here because you use POST method. For example if you have input

<input name="xxx" value="test">

to print value of this input in PHP you need use this code

echo $_POST['xxx'];

If you don't want to use JQuery then you still need loop through inputs and prepare proper array to send it via XHR.

Robert
  • 19,800
  • 5
  • 55
  • 85
  • I haven't met JQuery yet which is making this hard to understand... What code would this replace? Or where would this be called? – benharris Dec 19 '13 at 13:28
  • would it go `var submit = function () {...` instead of this function? so would look like `var submit = $function (){...`? – benharris Dec 19 '13 at 13:30
  • it can replace whole code of yours. Check www.jquery.com there are many samples of code. – Robert Dec 19 '13 at 13:37
  • but I only want this code to be executed when the submit button on the page is pressed, that's why I have the eventlistener at the top so surely thats needed? – benharris Dec 19 '13 at 13:43