I have a basic ajax form on my site utilizing the Js helper, it works fine but when there are validation errors the update callback duplicates the entire page inside of my success div.
Success div:
<div id="success"></div>
Submit button:
echo $this->Js->submit('Send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success',
'class'=>'btn btn-primary'
));
Javascript:
$(document).ready(function(){
$('#postkey, #gender, #hair, #location, #message').blur(function(){
$.post(
'/Cake_ajax/Posts/validate_form',
{ field: $(this).attr('id'), value: $(this).val() }
//handleNameValidation
);
});
});
Validate form function in my controller:
public function validate_form(){
if($this->RequestHandler->isAjax()){
$this->request->data['Post'][$this->request['data']['field']] = $this->request['data']['value'];
$this->Post->set($this->request->data);
if($this->Post->validates()){
$this->autorender = FALSE; // don't render a view
$this->set('error','');
}else{
$this->layout ="ajax";
$this->autoRender = FALSE;
$error = $this->validateErrors($this->Post);
$this->set('error',$this->Post->validationErrors[$this->request['data']['field']][0]);
}
}
}
I don’t know if this is enough information to go on, If I need to post more code, just let me know.
thanks.
I just tested your application by using your zip file.
What I observed is that this is not the whole page that is put inside your
#successdiv, but only the content of thePosts/add.ctpview.So basically this means the RequestHandler does its job correctly, meaning the layout that is used is the ‘ajax’ layout.
To get rid of anything else that the form, the add.ctp page should not contain anything else that the form. In your case
Posts/add.ctpcontains navigation links, and that’s why they get duplicated.That said, what the submit button does currently is getting the content of
Posts/add.ctpview and insert it in your empty#successdiv. But you never remove the form that was already on the page.What you could do is updating the content of a div that contains your first form, or even the content of the whole
Posts/add.ctpview.In your case, simply updating the
#contentinstead of the#successdiv could maybe suit your needs: