Skip to content

Instantly share code, notes, and snippets.

@aslamdoctor
Created February 25, 2012 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aslamdoctor/1908431 to your computer and use it in GitHub Desktop.
Save aslamdoctor/1908431 to your computer and use it in GitHub Desktop.
jQuery to PHP via AJAX using JSON
JS Code
------------------
$.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;
}
});
Example result
--------------------
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 Code
--------------------
// 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 "<br/>";
}
@yawaweb
Copy link

yawaweb commented May 24, 2018

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment