Im opening a form via ajax (using jquery) and i want to save it without reloading whole page. Where i have to change code, to get text response (eg. “ok!”) instead of redirection to edit page?
this is my js:
$("#newcatlink").click(function() {
$.ajax({
'url': "category/new",
'success': function(data, textStatus, jqXHR) {
$("#mdialog").html(data);
$("#_form_jqhide").hide();
$("#mdialog").dialog({
modal: true,
width: 500,
resizable: false,
buttons: {
Save: function() {
$.ajax({
'type': 'POST',
'url': 'category/create',
'data': $("#categoryform").serialize(),
'success': function(data, textStatus, jqXHR) {
alert(data);
}
});
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
});
});
I changed processForm action in actions.class.php like this:
...
if ($form->isValid())
{
$Category = $form->save();
if($request->isXmlHttpRequest()) {
return $this->renderText("ok!");
} else {
$this->redirect('category/edit?id='.$Category->getId());
}
}
but it didnt change anything. How to do this?
edit 8/1/12:
I’ve made changes to my code according to blowski and sakfa answers, but i get another issue: how to catch form errors? I added to processForm else to if and it works as expected but i cant get error message/code/whatever back, only a fact that error exists.
Here is code: http://pastebin.com/ppbPM88G
and this is server answer after sending form with one required field empty:
{“haserrors”:true,”errors”:[]}
Based on our conversation, I can see what’s happening. If I’ve understood your comments, it’s not redirecting the whole page, it’s just re-rendering the original form inside the dialog box?
After the user submits the form, if it’s valid, then it redirects. However, because you’re bypassing the redirect, it reaches the
$this->setTemplate('new')bit of code instead, so shows thenewform again, populated with the data from the just-completed form.To get around it, use something like this in the create action:
You’ll also want to change your Ajax request to specify that it’s expecting a JSON response. Then, if the form was valid, close the dialog box (or whatever you want to do after the save).