I have Create Products page with a url like "/product/create".
It has multiple tabs about various categories of that product. When the tab-1 data is submitted (with AJAX) a product is created on the server side (stored in DB) but the url is still "/product/create".
I want to redirect this user to "/product/{product_id}" if this user tries to reload page after the product is created (i.e after the first AJAX call on tab-1). There can be multiple AJAX requests for the remaining tabs.
I tried the flashing data using but it's lost in subsequent AJAX requests.
session()->flash('foo','bar');
Is there any way to keep data until the next reload and redirect to edit route if that product is created? Or any other possible solutions to my problem.
I'm not sure if this would be the most elegant solution, but for Chrome you can use the localStorage function. For example:
if (typeof localStorage.getItem('visited') != 'string') {
localStorage.setItem('visited', 'anything here');
} else {
localStorage.removeItem('visited');
window.location.href = 'https://www.example.com';
}
Have you tried to just redirect the user when he creates the product?
In JavaScript, supposing that the product ID is in a variable called product_id
it would be something like:
window.location.href = "/product/"+product_id;
If you don't want the page to be reloaded, use a PushState
var stateObj = { foo: "bar" }; //Something to the browser to know the state if user go back and forward again
history.pushState(stateObj, "NewTitle", "NewURL");
PushState navigation is something complex that should be added to the full webpage to give it a better look. MDN Documentation for PushState
I think since you are using AJAX for your submissions, the best way would be that you ensure that your {product_id} is returned with the AJAX response, so you can build your refresh links. In Javascript (jQuery) pseudocode this would be something like:
// AJAX function call to createProduct
function createProduct() {
$.post('ajax-url-end-point',{payload-data}, function (ajax_response){
if(response){
//build your refresh url with response
var refreshUrl = "http://<domain>/product/"+response.productid;
localStorage.setItem('refreshUrl', refreshUrl);
window.location.href = refreshUrl
}
},'text');
}
// On reload check for the refreshUrl
$.document.ready(function() {
if(localStorage.getItem("refreshUrl")){
window.location.href = localStorage.getItem("refreshUrl");
}
});
On your /product/{product_id} page, you can run a JS to erase the refreshUrl local storage item based on your own specific criteria.