jQuery to PHP via AJAX using JSON
Share
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.