#Edit I use CakePHP 2.3.5
I would like to know what is the problem with my Ajax request and Controller behaviour. These are the issues i encounter:
I don't really know what is going up, i will be grateful for any kind of help!
Here's the source code:
My ajax request
$('.addUser').on('click', function(){
var data = $('#UserAddForm').serialize();
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: 'Users/add',
data: data,
success: function (){
$('#regInfo').html("User was created");
$('#regInfo').css('color', 'darkgreen');
},
error: function(){
$('#regInfo').html("User was not created");
$('#regInfo').css('color', 'darkgreen');
}
});
})
My UserController in CakePHP
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
And in my AppController
public function beforeFilter(){
if ($this->request->is('ajax')) {
Configure::write('debug', 0);
$this->autoRender = false;
$this->layout = 'ajax';
}
}
There are a few things you can do here for debugging:
1 -- First, make sure that your requests are reaching the right controller function. I notice you have url: 'Users/add',
in your ajax function. Generally, that would be url: '/Users/add',
or find another way to get the base path before you call the controller/view
You can do simple tests to make sure it's reaching the controller view function:
$('.addUser').on('click', function(){
var data = $('#UserAddForm').serialize();
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: 'Users/add',
data: data,
success: function (data){
console.log(data);
}
});
})
public function add() {
$this->layout = 'ajax';
$this->autoRender = false;
echo json_encode(array('this is some' => ' json data'));
}
2 -- If #1 works fine then, start double checking your posted data:
public function add() {
$this->layout = 'ajax';
$this->autoRender = false;
//just checking for request data because you
//may be doing a put and not knowing it
if ($this->request->data) {
echo json_encode($this->request->data);
}
}
use chrome or firefox and check the output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.