Send JavaScript object via Ajax to PHP script.

This is a short guide on how to send a JavaScript object to a PHP script using an Ajax request. In this tutorial, I will use the JQuery library to send the Ajax request.

Sending the object via Ajax.

Let’s take a look at a simple example:

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var user = {
    'name': 'Wayne',
    'country': 'Ireland',
    'selected': new Array(1, 5, 9)
};
var userStr = JSON.stringify(user);
$.ajax({
    url: 'json-receive.php',
    type: 'post',
    data: {user: userStr},
    success: function(response){
        //do whatever.
    }
});
</script>

In the JavaScript code above:

  1. We included JQuery, which is a JavaScript library that makes it handy to send Ajax requests.
  2. We created an example object called user. This object contains three properties: Two strings and an array.
  3. We converted our JavaScript object into a JSON string by using the JSON.stringify method.
  4. Finally, we sent an Ajax POST request to a PHP script called json-receive.php with the JSON string in question.

Receiving the object with PHP.

Then, in our PHP file, we can do something like this:

<?php

//Retrieve the string, which was sent via the POST parameter "user" 
$user = $_POST['user'];

//Decode the JSON string and convert it into a PHP associative array.
$decoded = json_decode($user, true);

//var_dump the array so that we can view it's structure.
var_dump($decoded);

In the PHP code above, we simply took the JSON string and decoded it into an associative array.

Hopefully, you found this guide to be both short and useful!