Skip to content

Instantly share code, notes, and snippets.

@rrd108
Created July 7, 2018 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrd108/390504f4a6efa23323f70a1afadbe731 to your computer and use it in GitHub Desktop.
Save rrd108/390504f4a6efa23323f70a1afadbe731 to your computer and use it in GitHub Desktop.
CakePHP ajax example with jQuery
<?php
// src/Controller/LanguagesController.php
namespace App\Controller;
use App\Controller\AppController;
class LanguagesController extends AppController
{
public function index()
{
$languages = $this->paginate($this->Languages);
$this->set(compact('languages'));
$this->set('_serialize', ['languages']);
}
}
<?php
// src/Template/Languages/search.ctp
echo $this->Html->script('search.js', ['block' => true]);
?>
<?= $this->Form->create($languages) ?>
<?= $this->Form->control('name', ['url' => 'languages/search']) ?>
<?= $this->Form->end() ?>
$(function() {
$('#name').on('blur', function() {
$.ajax({
type: 'POST',
url: $('form').attr('action'),
dataType : 'json',
data: {name : $('#name').val()},
success: function(data, textStatus, jqXHR) {
// do whatever you want
},
error: function(jqXHR, textStatus, errorThrown) {
// do whatever you want
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment