Skip to main content

jQuery to PHP via AJAX using JSON

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

This is how you can generate data for use with AJAX using a “POST” method which contains JSON data and then pass it to a PHP script and then decode ready to use as variables (name value pairs). In this example, I’ve used form input values to generate the data passed as a JSON string, but you can create your own JSON data to pass doesn’t have to be from a form.

jQuery / AJAX

Basic AJAX function to pass the JSON data to the server-side script.

$.ajax({
   type: "POST",
   url: targetURL,
   async: false,
   data: JSON.stringify($('#form').serializeArray()),
   success: function(data){
      console.log(data);
      return true;
   },
   complete: function() {},
   error: function(xhr, textStatus, errorThrown) {
     console.log('ajax loading error...');
     return false;
   }
});

If we take a look at the generated JSON is has name value pairs.

Generated JSON example:

data=[{"name":"product","value":"riserva shiraz wine glass"},{"name":"supid","value":"81"},{"name":"brandid","value":"60"},{"name":"blid","value":"7"},{"name":"cid","value":"381"}];

PHP Variable Dynamics

// decode JSON string to PHP object, 2nd param sets to associative array
$decoded = json_decode($_GET['data'],true);

output values:
foreach ($decoded as $value) {
   echo $value["name"] . "=" . $value["value"];
}

//set values:
foreach ($decoded as $value) {
    $$value["name"] = $value["value"];
}

//both:
foreach ($decoded as $value) {
    $$value["name"] = $value["value"];
    echo $value["name"] . "=" . $$value["name"];
    echo "";
}

Sorry, no demo, but feel free to ask questions.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!

Latest Remote Jobs