I have a modal view (the one from bootstrap) in the front end.
Upon clicking the submit button the user will be going to a function in controller:
Route::post('post_question', array('uses' => 'QuestionController#postQuestion'));
And at the end of the postQuestion i want to redirect to another page.
I tried:
return Redirect::to('mywebsite/question/1');
return Response::make( '', 302 )->header( 'Location', 'mywebsite/question/1' );
return Redirect::route('question/'.$question_id)->with("question",Question::find($question_id));
header("Location: mywebsite/question/$question_id");
none seem to work though.
The thing is, i can see the request in XHR but just that the page is not redirected.
Is the modal somehow blocking the behavior?
You can redirect with an AJAX request. However, you will find that the results will not be quite what you expected.
On a redirect, Laravel will should set your response code header as a redirect response and then the content of the redirected page would be sent.
You could do one of two things depending on how you wanted to handle things.
Send a JSON response back to the submitted form with a meta data parameter and then use this meta data in your success function to set window.location.
Your Laravel controller responding to the post would look a bit like this:
public function postQuestion()
{
// DO stuff to set your $question
return [
'question' => $question,
'meta' => [
'redirect_url' => url('mywebsite/question/'.$question->id),
'status' => '400',
// Any other meta data you may want to send
],
];
}
Then assuming you are doing some jQuery AJAX call, change your success callback (I'm calling it questionSubmitSuccess here):
questionSubmitSuccess = function (data) {
// Anything you may want to do before redirecting the user
if (data.meta.redirect_url) {
// This redirects the page
window.location = data.meta.redirect_url;
}
}
Continue redirecting from your controller and then do something a bit more similar to rails turbo links and replace the entire page with Javascript:
You can do this a few ways: using [Modify the URL without reloading the page browser History API), or using jQuery.load to submit your form.
The browser history API might work a bit easier as it would still allow you to handle response errors, but it only works in more modern browsers.
jQuery.load would likely require rewriting a bit of your AJAX submitting code and is harder to handle things like errors (it will replace your page content no matter the status code from what I can tell), but it has better browser support.
IMO, the first approach is a bit more maningful as the API endpoint is usable by something other than this single implementation.
Also, there are fewer points of failure and error states to manage compared to trying to replace your entire DOM without a page reload.
U can put button inside form and when u submit that button pass data from page to controller and from controller call the another page with that data
like return View::make('users.index,compact('data'));
Related
I am using an API from a payments-provider.
At some point, I show the user a page where he can authenticate himself (enter a code that the payment-provider will send him).
Note that on this page, I render a div element that the payment-provider has given me through an API request I made previously (I used Guzzle for this).
After the user enters the code and clicks submit, the payment-provider redirects him to one of my pages - let's say /redirect.
So, in my web.php I have a route:
Route::post('/redirect', 'OrdersController#redirect');
In my OrdersController I do this:
// do various stuff like updating the order status
return redirect("orders/$order->id");
There is another route in web.php:
Route::get('/orders/{order}', 'OrdersController#show');
And here is the show method:
return view('orders/show', [
'order' => $order,
'page_title' => 'Order Receipt',
]);
Two things go wrong:
The user gets shown the orders/show view but it seems like it is in an iframe:
The URL of the page does not change. It does not show myapp.test/orders/435 for example. Instead, it still shows the URL of the previous page (the one where the user authenticated himself) - something like myapp.test/authenticate let's say.
Any ideas why this is happening?
Update with screenshot:
So I have an ajax call to bring down several dozen chunks of data all several megabytes in size, afterward storing the data locally via the html5 filesystem api.
I wanted to prevent the user from navigating away from the page before the ajax calls were done. I decided to explore the onbeforeunload event, to have it notify that the user should stay on the page until the ajax calls are complete. I set the following before the AJAX call and at the end/success of the AJAX call I reset the window.onbeforeunload.
window.onbeforeunload = function(){
return "Information is still downloading, navigating away from or closing "+
"this page will stop the download of data";
}
When I attempted to close the page or navigate away from the page, the pop-up message comes up as expected informing the user to stay. However, once I confirm that I want to stay on the page, the ajax calls do not resume where they left off. Is there a way to prevent the ajax calls from pausing/stopping or to continue on/restart with their executions?
I'm open to any ideas to implement desired functionality described in the title of this post.
Pretty sure you can create a global in the .js file like...
var request;
Then assign your ajax call to this variable.
request = $.ajax{
//Ajax
//Stuff
//Goes
//Here
}
Now inside your window.unbeforeunload function, add this conditional statement.
window.onbeforeunload = function(){
if(!request){
return "Request not initiated";
}else{
//Request is in progress...
//You can use request.abort() if you need
}
}
EDIT: To elaborate on on some of the methods you can use on the request object, check out this page. (for example, .done or .always may suit your circumstances)
Although I read dozens of answers I could not find a solution.
I'm using MVC 3 with Razor. I have a simple Form with client validation via ajax. This part works fine. My problem is: In the update Action of my Controller I want to redirect to another Action. If the user disables Javacript, this works fine. But with javascript/ajax enabled, the redirectaction doesn't seem to work. Instead it looks like if some kind of partialview or something like that is executed.
My Controller/Action-code:
Function UpdateItem(Item As CItem) As ActionResult
' some validation code, save etc.
if everythingok then
Return RedirectToAction("Updatesuccess")
else
Return RedirectToAction("EditItem")
endif
End Function
My html page looks like (shortened/pseudo):
Logo image
H1
some text
<form>....</form>
When the form is submitted via ajax the new html code is added beyond "some text", so the form is replaced but everything above the replaced form stays on the page.
When ajax/javascript is disabled then after submit a whole new page is loaded. I checked the http headers and noticed, that with ajax there is no redirect (which is logical in some way because it is ajax).
What can I do? I want to redirect to a new page.
Is it possible to disable the ajax-submit and only use the "normal" form-submit?
I like the client validation via ajax while the user enters data and I want to use this, but for me it would be good enough, if the submit would be a "normal" submit.
I hope someone understands what I want and can help me.
Thanks.
I'm not a 100% sure I understand your question, but what the heck, don't downvote me :)
The problem is, redirect works via sending a HttpResponse with the redirect indicated in the headers, which the browser understands. If you submit via AJAX, it's not the browser that handles the request, it's your OWN JS code.
Here is the trick: instead of returning a redirect, return the Url (preferably as json), and then redirect manually using window.location.
I'm not fluent in VB, here is how I'd do it in C#:
var url = new UrlHelper(this.ControllerContext.RequestContext);
var link = url.Action("UpdateSuccess");
return Json(new {link});
and then in jQuery:
$.ajax({ method: 'POST',
url: 'your post url',
success: function(result) {window.location = result.link; },
// ... (passing form etc)
});
From my view I am sending via $.ajax a JSON object to my controller to save it in the database.
If all succeeded i want to redirect to another action which will show a diferent view.
If i use this code:
return RedirectToAction("CreatePage", "Survey", new {id = question.PageId});
The execution goes to the Survey controller which returns a view but it is not shown.
I have read some post which said that it is not posible to redirect via ajax.
The solution I use so far is to redirect via javascript like this:
success: function (ret) {
window.location.href = "/Survey/CreatePage/" + $("#PageId").val();
}
Although this always works, sometimes i need to refresh the CreatePage view to show the last changes made.
Any idea of how to solve this problem better?
Thanks in advance
As mccow002 suggested, I wasn't really needing to make the call via AJAX for that part. After studying the solutions suggested, i realized that i could simple submit it in a form. My confusion came because I have a save and continue editing and a save. For the save and continue I use the AJAX call, but for the save option with the form being submitted is ok.
Thanks very much for your help.
Instead of redirecting to a new page, you can send a rendered html from .net code back to client and load that html in page, like this $("#main").load(renderedHtml).
But for refreshing the page you can write a simple script that run at specified intervals and refresh the page contens.
You could use [OutputCache] on the CreatePage action so that it doesn't cache the page or only caches for so long.
output caching
What is the best way to address an AJAX script that sends data to POST in codeigniter? Right now I am loading a view with the AJAX through $this->load->view('AJAX', $data); however there is no UI or user actions in the view. It's simply running through the script and returning POST data a little after the script loads. I receive the POST data in my model where I input the values into the DB and output some other values based on the data.
I need to open a real view, set metatags and re-direct the user to another website afterwards.
How do I address this?
The problem I'm facing is that I cannot open up another view because the AJAX view is the one that's in focus but I need this AJAX view to be temporary that basically does it's thing and sends to POST.
Is there any convention that I can lookup/research to what I'm describing? Let me know what kind of clarification is needed if any.
Some people like to write "ajax" controllers and post to them exclusively, but you don't need to do that. You can handle the request in the same controller that handles the non-ajax request. Personally, I exclusively return json, but you can return chunks of HTML if that works better for you.
Your exact problem is vague (actual code would help clarify), but I think you are on the wrong track. Don't use a view for processing anything ever. Use your Controller layer, this is for handling input and requests.
Example of controller method responding to either ajax or non-ajax request:
function edit_user()
{
$data['status'] = $this->user_model->save();
if ($this->input->is_ajax_request())
{
// return json string with our update status
// Something like: {"status":true}
echo json_encode($data);
exit;
}
// Load the non ajax view with the same data
$this->load->view('users/edit', $data)
}
$this->input->is_ajax_request() is a function of the Input class that reads $_SERVER['HTTP_X_REQUESTED_WITH'] and checks if it's value is XMLHttpRequest. This should only be true if it's an "ajax" request.
You can make life easier by wrapping this in a class or function. No matter what you decide to do, don't use the view layer for processing data.
I think my problem is, how do I address javascript without a view? how do I call the script and/or where do I put the JS code in the controller? I felt it was the wrong direction to address the code in a view but I didn't see how else to do it.
Whenever possible, you should put javascript code in a .js file and use a <script> tag to load it, in an HTML document. The only other exception is putting it in a "view" file (a file that's only purpose is to construct your final HTML output). In other words, follow the same rules of HTML as to where to put javascript, and follow the usual conventions of MVC of where HTML belongs (in the view). Javascript code does not belong in your controller. Javascript is not processing your data, it is sending the data to the server.
I need to open a real view, set metatags and re-direct the user to another website afterwards.
If you want to load a view, then redirect (after a certain amount of time I assume), you can do it with javascript or a <meta> tag (but don't use a meta tag, use js).