I have this code in jQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$("input[type=submit]").click(function() {
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
if(name=='' || problem_blurb == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else {
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
// Here can update the right side of the screen with the newly entered information
alert (dataString);
}
});
}
return false;
});
});
</script>
And I have an AJAX call that I want to make JSON so I can unpack the JSON in the success case of the call to the AJAX.
What I don’t understand is how to create the JSON and how to make the front end detect it, and how to unpack it and display it. Any advice with that?
My backend return will be simple. Just a name and description for every item returned.
Make an array of what you want to return in php, preferably an associative array but it could be integer indexed and it will work just as well.
That will render your array as output in JSON format, which your jQuery success function will pick up in a parameter. Below, I name the parameter
jsonbut you can name it whatever you like.Also note that
$.parseJSONwas not introduced in jQuery until version 1.4.1.Please see: PHP Manual: json_encode()