RedirectToRoute in Ajax Controller symfony - ajax

I have a controller that I call with Ajax.
Inside this controller I have a condition, like
if($a == 10){
return $this->redirectToRoute('form_finish');
}
But when the condition is satisfited, I don't have the redirect

You call the controller in ajax but do you manage the response.
You have to redirect from the browser if the condition is satisfied or handle the ajax response and load the content in the DOM.

I solved it by doing something like this :
In controller i put the redirect handler in Jsonresponse :
//return $this->redirectToRoute('fos_user_security_logout');
$response = new JsonResponse(array(
'route' => $this->get('router')->generate('fos_user_security_logout'),
'message' => 'You may choose on option'));
return $response;
And in ajax
success: function(response,xhr){
//This is for the redrection in front page
if(response.route) { window.location.href=response.route;}
Hope it helps someone

Related

Before redirect set validtion error to view page

i am calling the form from ajax and after submitting the form, validation error message not showing, ajax call on load.
my ajax code
$.ajax({
type:"POST",
url:"/application/workpermit",
data:dataString,
success:function(data){
$('#tabs-12 .workpermit').html(data);
//alert(data); return false;
}
});
Success return the workpermit view with form
The controller part, after submitting
if ($validator->fails()) {
return redirect("application/".$employer_maid_id."/edit?tab=tab11")
->withErrors($validator)
->withInput();
}
Please any one suggest me, how to show the validation message
if you are not refreshing the page you need to add(append) the message with js/jQuery
if you are redirecting from the page you can you Laravel's built in feature "Flash". Basically it's a one time Session laravel docs

Cakephp - Proper way to return AJAX Success response?

I have been using the trick below to return success response with AJAX:
//In controller
echo 'success';
//In Javascript
if(response == 'success'){
//redirect
window.location.href = '/users/profile/';
}
It works fine on localhost. But in web server, I got the error below everytime I want to redirect the page after success:
Cannot modify header information - headers already sent by (output started at ...
So yeah, I know it is caused by the echo before redirecting.
So, Is there proper way to return the success response? No need to be a message, just true or false is enough.
[EDIT]
By using exit('success'), it works fine, but is this the best way?
Thanks.
It is better to redirect from javascript.
//In controller
echo 'success'; exit;
//In Javascript
if(response == 'success'){
window.location = 'your-controller-action';
}
EDIT
You may have space before/after php Opening/Closing tags in controller and models. Remove all the closing tags from all controllers and models and any whitespace before opening tags. Then check the result.

Display form via Ajax

Edit
Many questions on SO are about form submission via Ajax (this one is very popular) but not about how to display a form through an ajax call.
My question is about the part in bold: the user asks for a form -> ajaxCall -> displayForm -> user submit the form -> send the form to the controller -> validates form -> send response to the user (errors or not).
The question
The ajax call being a POST, $request->isMethod('POST') always returns true when doing an ajax call. Therefore if a new form is being requested through an ajax call, it will always be validated. I have enclosed the code below, the form is displayed ok, but the following error message is displayed in the form:
The CSRF token is invalid.
The problem is that the form is being validated during the ajax call requestion the form in the controller.
On a side note, submitting the form works well, and validation works well.
Does anyone know how to display a form via Ajax without having the blank new form being validated?
My code so far:
/**
* Display the message as well as the form to reply to that message
*
* #param Request $request
* #return Response
*/
public function viewMessageAction(Request $request)
{
//Forbid every request but jQuery's XHR
if (!$request->isXmlHttpRequest()){
return new Response('', 200, array('Content-Type' => 'application/json'));
}
//Retrieve the message from the request
$messageId = $request->request->get('messageId');
$message = $this->getMessageManager->getMessage($messageId);
//Creates the form to reply to the message
$form = $this->container->get('reply_form.factory')->create($message);
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
//...
return $this->redirect($this->generateUrl('task_success'));
}
}
$answer =$this->container->get('templating')->renderResponse('AcmeMessageBundle:Message:message.html.twig', array(
'form' => $form->createView(),
'message' => $message
));
$response = new Response();
$response->headers->set('Content-type', 'application/json; charset=utf-8');
$response->setContent(json_encode($answer));
return $response;
}
EDIT: jQuery part:
<script type="text/javascript">
$(function(){
var myPath = ;//...
function getMessage(messageId){
$.ajax({
type: "POST",
url: myPath,
data: "messageId="+messageId,
success: function(returnData){
$('#message').html(returnData);
}
});
}
});
</script>
An ajax call doesnt always need to be POST. It could be GET, PUT or DELETE . So when you are making ajax call to get the form make it a GET request.
If you are using jquery here is how you do that
$.ajax({
url: "http://localhost/proj/url",
type:'GET'
})
If you are using Using XHR, you can specify the type in the open function
xhr.open( 'GET', URL)
PS: It will be a good idea to use JMS Serializer Service for serialization instead of json_encode
You might also be interessted in the FOSJsRoutingBundle, since it add a lot of comfort working with ajax and Symfony2 routes in general.

Dancer AJAX route with templates

I'm trying to show a template in an AJAX route like this:
ajax '/login' => sub {
my $user = params->{uname};
my $password = params->{upass};
my $db_inst = WebApp::Persistency::SQLiteDB->instance();
if ($db_inst->is_user_registered($user,$password) == 1) {
template "main_page";
} else {
return { res => 'Wrong' };
}
};
The user indeed validates but the template never shows.
When I use the template from a different route (non-ajax), it works.
Am I missing something here?
AJAX does not reload the whole page. How can you use a template if you are not reloading a page?
A rendered template could be returned to the AJAX request and injected into the page.

create a nested jQuery post in another post callback?

since I'm new in jquery, can you tell me how to redirect a page to another action method ?
I develop a MVC web application. I use jquery post method to do some validation, and when it return true, it will be redirect page to another one.
My problem is..when when I redirect page using window.location, it's works well in IE (IE 9). but didn't work on firefox & chrome.
So, I try to using jquery post method to redirect page from action method in my controller. I call redirect post method in a jquery post call back.
it is my code :
$.post(posturl, formData, function (result) {
if (result == 'True') {
$.post("/Controller/RedirectMethod", {_Action: 'Index', _Controller: 'Home'}, null);
}
else
alert('failed');
}
);
and this is my RedirectMethod :
[HttpPost]
public ActionResult RedirectMethod(string _Action, string _Controller)
{
return RedirectToAction(_Action, _Controller);
}
so how I should create a nested post in another post callback ?
or there is another way to redirect page ?
thanks,
You won't be able to do a RedirectToAction inside an Ajax request.
If you need the web page to change to a different location inside the Ajax response, use window.location as Ben suggested.
One thing to bear in mind is that you'll need to remove the 'HttpPost' action filter.

Resources