as title you see, I meet some problem with my website,
I use ajax to read my API, and after ajax success, I need to reload page to display some data,
Unfortunately, the page sometime will blink and then reload, but sometime will not.
And I use setTimeout to achieve that, because I’m writing shopping cart page,
It allow user edit their shopping carts’ goods.
My idea is: after user stop click plus or minus button or stop typing quantity about 1 second,
ajax will execute to read my API, after ajax success, reload page.
So, is there have any ways to prevent page blink?
Or maybe I can made a loading gif to display on the page?
My code will be like:
var timeout = null;
$('.num').on('keyup', function() {
var newNum = $(this).val();
var pid = $(this).attr("name");
clearTimeout(timeout);
timeout = setTimeout(function() {
if(newNum <= 0){
alert("At least 1 product!");
$(this).val("1");
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: 1
},
dataType: "json",
success:function(data){
window.location.reload(true);
},
});
}else {
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: newNum
},
dataType:"json",
success:function(data){
window.location.reload(true);
},
});
}
}, 1000)
});
3
Answers
You can add a loader gif as you want then remove when document loaded.
What is Ajax
If you want to reload page then don’t use ajax call,
but if you want to load data using ajax then update your html using JavaScript in ajax success message.
What is the point in using
ajax
when you want to reload the page to show updated data…?What is the use of above piece of code..?
For your purpose a simple
form submission
thing was enough, but you have usedajax
getting data but not using it anywhere.If you want to reload the page, then better go with solution by Şahin Ersever.
If you want a dynamic site, where data is fetched from backend in background and updated on frontend without refreshing the page, do something like this.
On
data
variable, you can echo out desired html/json or a success/error code, and handle the data/code in ajax function accordingly.Edit :-
Looking at your comment
But I check my website, if ajax success, I use console.log to print my data, it's not working, but if reload page, it can work
.I have a quick and easy solution for this.
Let’s take above example, which I have given.
Suppose if I want updated data to be displayed in
dynamic_div
what I will do, is I keep the element to be shown inside that div in separate file.eg:- updated.php
Now What I do is on success of my ajax, I will load this div in to my
.dynamic_div
like this.Now you will get updated data, as you have already updated it somewhere in backend, so
load()
will load a page inside a division, without refreshing the whole page.Comment down for any queries.