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:

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:

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!

Facebook Comments