I’m using CakePHP for a small web app and on one form page there’s a dropdown to select a job number. I’d like to update two text fields based on the job number selected in the dropdown using jQuery (I’m also open to using the default ajax helper but I didn’t have a lot of success with it).
Here’s my jQuery snippet:
<script> $(document).ready(function() { $('#job_id').change(function() { $.post('/surveys/jobdetails', {id: $(this).attr('id')}); }) .change(); }); </script>
jobdetails is a method in my controller that gets the current job based on the job id passed in. However, it doesn’t get called when the dropdown changes value. I tried substituting an alert function in place of .post and that worked, so onchange is being called correctly.
Here’s the <div> I’m trying to update:
echo '<div id='job_details'>'; echo $form->label('jobtitle', 'Job Title'); echo '<input type='text' name='jobtitle' id='jobtitle'>'; echo $form->label('department', 'Department'); echo '<input type='text' name='department' id='department'>'; echo '</div>';
I want to set the value of each text field to be the corresponding value for the job returned from the ajax call. There’s a lot of really good jQuery and CakePHP documentation but I haven’t found anything that quite covers what I’m trying to do. Can anyone see what I’m doing wrong? Is there a better way to use ajax to update a div with CakePHP?
Right now, it appears that the AJAX request hits the ‘/surveys/jobdetails’ URL, but does nothing with the results. You need to add a callback to your AJAX request, like so:
There is also a convenience function in jQuery called load() which simplifies it even further, getting the contents of a URL and applying it to the selected element: