Using Ajax , jQuery and JSON IN CakePHP
I am using cakephp 1.3 and intend to update a <div>
in my form (*.ctp) with the information retreived from a mysql table.
Though i have gone through several examples in this site, none of them seem to provide a complete picture. They all seem to assume some knowledge on our part and skip part of the code and give only a portion of it.
I request the knowledgeable 开发者_JS百科boarders to provide a simple complete example of cakephp controller code, cakephp view code and the jQuery script to demonstrate the functionality. I request the boarders to also highlight how to handle the error messages thrown up by the controller and display them the way cakephp normally displays.
The example could be as under:
- a
student_controller
handling the table storing theroll_no
,name
andage
andclass
of all students. - a
student_view
ctp file which will initially accept theroll_no
of the student i need to know about. This ctp file also contains an empty<div>
with provision for display of name, age and class - but it is initially hidden. a submit button to submit the roll_no. - as soon as the roll_no is entered and submit pressed, the jQuery will pass the roll_no to the controller (how is this function coded?)
- the controller will find the record and return the other details as a json-encoded. (please provide complete syntax). If the record with the roll_no is not available, the error will be returned (may be, as a json-encoded string).
The view file should display the details received in the empty div or display the error message as is normally done in cakephp (please provide the complete syntax of the jQuery script)
The jQuery part:
$('form').submit(function(event){
var roll_no = $('#StudentRollNo').val();
$.getJSON('/student/details/' + roll_no, function(data){
$('div#name').text(data.Student.name);
$('div#age').text(data.Student.age);
$('div#class').text(data.Student.class);
});
return false;
});
The cakephp part:
function details($roll_no)
{
$student = $this->Student->findByRollNo($roll_no);
echo json_encode($student);
exit;
}
精彩评论