Action generating partial view realizes whole page must be replaced. How to redirect? - ajax

This is a partially hypothetical question, as I don't actually need to do this at the moment. I'm just anticipating that I might.
My MVC3 app has a page that has a partial view that is refreshed using MVC3 Ajax and AjaxHelper.BeginForm(). It all works nicely.
But, it's possible for the action that generates the partial view to realize that rather than see a refresh of the partial view, the user needs to be sent to a completely different page. In other words, rather than returning a PartialViewResult, the action method needs to return a RedirectResult or a regular View.
This, as you no doubt know, won't work: attempts to return a RedirectResult when the signature calls for a PartialViewResult won't compile.
So how can this be accomplished? Let's say for the sake of argument that the necessary decision can only be made server-side and only after the information in the partial view is posted back to the server.

First, define your method to return an ActionResult, which will allow you to return either a PartialViewResult or RedirectResult, as needed.
Second, supply an OnFailure callback function in your BeginForm() method call. If the result of the AJAX call is not an HTTP 200, the OnFailure callback will be run, which you can then use to parse the redirect response and perform the redirect.

Related

Whats the difference between redirect and this in Codeigniter?

I am new in Codeigniter and it's one of the good frameworks of php. But on some conditions I'm confused. Like this one. If any of you have any clarification about my dough, it's a great help for me.
Offcouse redirects refresh the page and $this not but apart from this I want to know - anyhow both of them used to go to somewhere else on view pages or like in other controller or in same controller to other methods.
But we don't use these side by side because when getting any of them it will go to that page or method without checking the next lines.
In case of a normal difference then have lot's of but I just want to know about the condition of going to next page or method when we use redirect or $this like this -
$this->Function($value); //It's method of same controller.
redirect('Controller/function'); //It's also doing same with page reload.
Thank for looking my problem.
Redirect()
When you will call any function of helper in codeigniter then you can call function directly without using any object. Helper in Codeigniter is collection of functions.
Redirect() method is a part of URL helper in Codeigniter.
For your ref. https://www.codeigniter.com/user_guide/helpers/url_helper.html
So, just load helper using $this->load->helper('url'); or you can also mention in autoload.php file.
$this->Function(); used to call a function from same controller
$this->Function(); used to call a function from same controller
redirect()
While building a web application, we often need to redirect the user from one page to another page. CodeIgniter makes this job easy for us. The redirect() function is used for this purpose.
redirect($uri = '', $method = 'auto', $code = NULL)
The first argument can have two types of URI. We can pass full site URL or URI segments to the controller you want to direct.
The second optional parameter can have any of the three values from auto, location or refresh. The default is auto.
The third optional parameter is only available with location redirects and it allows you to send specific HTTP response code.
Redirect means jumping to another function mentioned in the redirect method.
$this->Function($value); => jumping to another function and you can execute the code of the same function as well as pass the value back by returning value.
When you send request to codeigniter generally CI controller gets called and then function which is mentioned in uri segment. like below... So this will be another request.
redirect('Controller/function'); //It's also doing same with page reload.
But when you have to call another function within the same request then you can use below approach
$this->Function($value); //It's method of same controller.
This will execute the given function and return the value within same request.

Redirect in controller using RedirectToAction malfunction

Normally google is my best friend but this problem I can't figure out or even understand.
I have an action in my controller that I use for selecting which follow up action in my controller to use, based on user input (see image)
This redirect work like a charm, it's when the action I'm redirected to is finished as the problem arises. In my action I fetch some much needed data for the web site. When tha data is fetched the action are supposed to redirect to a generic action, that in turn will present my view. The "middleware" action redirect correctly and it also send the parameters but the "recieving action" don't handle or recieve the parameters.
I'm totally clueless here, is it not possible to redirect to an action that in turn redirect to another action or what is the problem?
The route specification looks a bit odd.
I think it should be possibly:
[HttpGet("Customer/Device/{id}")]
public IActionResult Device(string id, bool like)
{
}
Now the URL it tried to redirect you to should work. Id from URL, and the like parameter from query.
If you want both in URL:
[HttpGet("Customer/Device/{id}/{like}")]
public IActionResult Device(string id, bool like)
{
}

Laravel Session data not written/update/availabe in View when using AJAX

When I add things to the Session with Session::put() in my controller action, then that data is not available in my view, with Session::get() when doing AJAX request.
The same problem goes for the Former package, which I use for nice form building. It relies on passing some info via the Session, which is used to mark fields as valid/invalid. This functionality is also not working when using AJAX.
I set a view like always, in my View:
$this->layout->content = View::make('account.login')
For AJAX requests, I do NOT render the normal way with layout, but instead get the specific "content" section of the template and return it:
$this->layout->content->renderSections()['content']
When I do a "normal" request, then Session data works fine.
When I do an AJAX request, then Session data set in the controller DURING the AJAX call is ignored. Any Session data set BEFORE the AJAX call is available.
I'm wondering if Laravel has some issue with Session under AJAX calls, or with the the "renderSection()" method above?
I have checked all the obvious problems:
AJAX request uses the same session ID as non-AJAX request.
GET/POST verbs are used correctly etc.
Replicate:
In CONTROLLER action: Session:put('foo','bar');
In VIEW file (in the content part): Session:put('foo2','bar2');
In VIEW file (in the content part): var_dump(Session::get('foo','bar')); // Returns 'bar' in non-AJAX calls, but returns nothing for AJAX calls (!!!)
In VIEW file (in the content part): var_dump(Session::get('foo2')); // Returns 'bar2' in both AJAX and non-AJAX calls as expected.
It seems like the Session values set in the controller action ARE LOST when it renders the view. Therefore my question if this is 1) an AJAX vs. SESSION issue in Laravel, or 2) an Session vs. renderElement() problem that I am not aware of?
I had the same problem and just found a potential solution:
I found a similar problem relating to laravel 3. For the session to persist in an ajax call you need to return the response correctly.
return json_encode($response);
This is causing the problem. It's not it appears a valid response to enable the session to persist. Change it to:
return Response::json($response);
This enables the session to persist!
For some reason a normal form submit or call to the method allows the first one but ajax does not.
I've seen references elsewhere about echo statements in the method affecting the session - the return I suppose must behaving similar to an echo
This is the post that triggered the solution:
http://forumsarchive.laravel.io/viewtopic.php?id=1304

Hiding Query String Parameters

I have a GET action for creating records. Because the page is somewhat dynamic, I don't use a model to hold the data. I go off to do some OAuth, only to return to the create screen later on. In order to pass the data back, I am redirecting with a query string. I parse the query string in the GET action, and then show the view. The thing is, the query string is showing up in the browser. This displays pseudo-sensitive data.
Since I am only using the query string for transferring data, I am wondering if I can throw the query string away to prevent it from showing up on the browser.
Otherwise, is there a way to go to another action without redirecting? I've found, if I call the "other" action method directly, it tries to find the view of the original action. I can explicitly change the return View(viewModel) line to return View("create", viewModel) but that seems really dirty.
You should consider changing the action to accept POST requests. At least this will prevent the sensitive information from appearing in the browser. For extra security, your site should be served via SSL.
The other thing you can try is encrypting the sensitive values or the entire query string. The only problem is that this, too, will be preserved in the browser's history unless you require users to log in.
It looks like your action method is trying to do too much. Authentication/authorization is a separate concern which should not be part of the action method. It is better to move the authentication work in to an action filter.
Create an class that extends authorization attribute and override its OnAuthorization method to do your authorization work.
This frees your controller action method to accept POST requests.

Use CodeIgniter form validation in a view

I have footer view that's included on all my pages which contains a form. I would like to be able to make use of CI's form validation library to validate the form. Is that possible?
Currently the form posts back to the current page using the PHP_SELF environment variable. I don't want to get it to post to a controller because when validation fails it loads the controller name in the address bar, which is not the desired behaviour.
Any suggestions gratefully received.
Thanks,
Gaz
One way, whilst far from ideal, would be to create a "contact" function in every controller. This could be in the form of a library/helper.
CI doesn't natively let you call one controller from another, although I believe there are extensions that enable this.
Another option would be an AJAX call instead, which would allow you to post to a generic controller, validate etc whilst remaining on the current page.
In this use case, I would definitely go for an AJAX call to a generic controller. This allows you to show errors even before submitting in the origin page.
Another way (slightly more complex), involves posting your form data to a generic controller method, passing it a hidden input containing the current URL.
The generic controller method handling your form can then redirect to the page on which the user submitted the form, passing it the validation errors or a success message using flash session variables: $this->session->set_flashdata('errors',validation_errors()) might do the trick (untested)
The good thing about this is that you can use the generic form-handling method for both the ajax case (suppressing the redirect) and the non-ajax case
AJAX would be best, just like everyone else says.
I would redirect the form to one function in one controller, you could make a controller just for the form itself. Then have a hidden value with the return URL. As far as errors go you could send them back with flashdata.
Just remember to never copy paste code, it a bad practice and guarantees bugs.
//make sure you load the proper model
if ($this->form_validation->run() == FALSE){
// invalid
$redirect = $this->input->post('url');
$this->session->set_flashdata('errors',validation_errors());
redirect($redirect);
} else {
/*
success, do what you want here
*/
redirect('send them where ever');
}

Resources