Created
February 25, 2012 13:09
-
-
Save aslamdoctor/1908431 to your computer and use it in GitHub Desktop.
jQuery to PHP via AJAX using JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/>"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!