I’m trying to build a system where I can submit data to a database using AJAX. I can do this, and it works really well.
However, I’m struggling to do a similar thing when trying to delete a record. I am new to using Ajax, especially with CakePHP, and I’m finding the whole concept quite overwhelming. I can delete a record using just pure HTML, passing the ID to the controller and then redirecting to the original page. It is just the Ajax thing I’m struggling with, and obviously using Ajax would be a huge benefit.
This is the code I have in my view:
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Content</th>
<th> </th>
</tr>
<?php foreach ($testing as $test) { ?>
<tr>
<td><?php echo $test['Testtable']['id']; ?></td>
<td><?php echo $test['Testtable']['title']; ?></td>
<td><?php echo $test['Testtable']['content']; ?></td>
<td><?php echo $this->Html->link('Delete', array('controller' => 'testing', 'action'=>'delete_ajax_data', $test['Testtable']['id']), null, 'Are you sure?' );?></td>
</tr>
<?php } ?>
</table>
And this is the code I have in my controller:
function delete_ajax_data($id) {
$this->autoRender = false;
$this->layout = 'ajax';
$this->loadModel('Testtable');
$this->Testtable->delete($id);
$this->redirect('/test-area/');
}
And this is the code I have so far for my Ajax:
$(document).ready(function(){
$('a.confirm_delete').click(function(event){
event.preventDefault();
$.ajax({
url:'/testing/delete_ajax_data',
type:'POST',
data: $("a").attr("href").serialize()
});
});
});
Cheers for any help with this, it is starting to stress me out!
EDIT: The code I used was wrong, and I have included the correct code now. Still not working though!
I’ve figured it out. I had several problems in the code.
The first part was in the view. Instead of using CakePHP’s link builder I used a HTML link instead:
Then, for the Ajax, I used the following code:
The new Ajax code uses GET instead of POST, which returns the ID of the record I’m deleting as an ID variable which can then be used in the controller like this:
There is probably a better way to do this than what I’ve done, but for what I’m doing this works superbly.