JavaScript
Article
By Sam Deering

jQuery to PHP via AJAX using JSON

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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.

--ADVERTISEMENT--

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.

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?