after ajax success refresh / reload page but prevent page blink - javascript

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)
});

You can add a loader gif as you want then remove when document loaded.
<div class="loader-fix" style="position:fixed;height:100vh;width:100vw;background:#ffffff;">
<img src="your.gif" />
</div>
<script>
$(window).on('load', function (e) {
$('.loader-fix').fadeOut('slow', function () {
$(this).remove();
});
});
</script>

What is the point in using ajax when you want to reload the page to show updated data...?
success:function(data){
window.location.reload(true);
}
What is the use of above piece of code..?
For your purpose a simple form submission thing was enough, but you have used ajax 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.
<html>
<body>
<h1> Dynamic load using AJAX </h1>
<div class="dynamic_div">
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
</div>
<button onclick="letsload()">Load</button>
<script>
function letsload(){
$.post("someurl",{ data1: "value1", data2 : "value2"},
function(data, status){
if(status == "success"){
$('.dynamic_div').html(data);//Loading updated data
}
});
}
</script>
</body>
</html>
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
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
Now What I do is on success of my ajax, I will load this div in to my .dynamic_div like this.
success:function(data){
$('.dynamic_div').load("updated.php");//Load the inside elements into div
}
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.

AJAX Read data from a web server - after a web page has loaded
Update a web page without reloading the page
Send data to a web server in the background
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.

Related

Submitting a form for use with php inside content loaded with AJAX

I've been search for a solution to this for a while and haven't been able to find one.
My company has quite a few webtools that we use for our jobs and I have been tasked with combining them all into a dashboard page. One of my coworkers started this project but never finished it before he left, so now I have to figure it out and there are quite a few problems.
The dashboard page is composed of a couple of sidebars, plus a "main" element. The sidebar includes a bunch of links that when clicked load specific php pages into the "main" via a call to jQuery AJAX. Here's a simplified example:
<html>
<head>
<script>
$(function() {
$("#pageToLoad").click(function() {
$.ajax({
url: "some_directory/pageToLoad.php",
success: function(result) {
$("#main").html(result);
}
});
});
});
</script>
</head>
<body>
Load Page
<main id="main"></main>
</body>
</html>
The problem here is that most of our tools use forms that are submitted via POST and then parsed with PHP (has to be php because it connects to our database to get information needed). Here's a simplified example of a tool page:
<?php
$action = htmlspecialchars($_SRVER["PHP_SELF"]);
function getResults() {
if(isset($_POST["infoForQuery"])) {
//Do some sort of query to database and print out results
}
}
?>
<body>
<form action="<?php echo $action;?>" method="post">
<input type="text" name="infoForQuery">
<input type="submit" value="submit" />
</form>
<div>
<?php getResults();?>
</div>
</body>
I need to be able to use these tools inside the dashboard page, but whenever I try to submit a form, it just reloads the entire dashboard page, resulting in the POST data not existing (maybe this is because the PHP code is run before ajax loads the content into the dashboard page? not sure).
I know I can use AJAX to send the POST like so:
$(function() {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});
However, this does not allow me to use the data collected in the form to query a database and print results out on the page.
Is it possible to accomplish this without having to leave the dashboard page, and if so, how?
Edit: I believe I've figured it out! What I wasn't realizing was that when I overrode the submit function and used ajax to send the post instead, I could actually retrieve the result of that post and put it into my page. Here's what I did:
<script>
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'some_directory/pageToLoad.php',
type: 'post',
data: $('form').serialize(),
success: function(result) {
$("#main").html(result);
}
});
});
</script>
Could be because the submit event is not firing. Since your forms are loaded dynamically do it like this:
$(function() {
$(document).on('submit', 'form', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});

Load .php site in to div without reloading

I am trying to create the following scenario:
A form in my index file collects input from a user, which is used to do some computation. The results of this computation should be echoed to him in a nice interface on the same page without reloading.
Currently, the results.php page is receiving the inputs correctly. Now, I just want to show it back inside the results div on the main page without reloading the results.php. .load is the wrong command for that. I need something like ".show"... Any ideas?
html:
<form action="results.php" method="post" class="ajaxform">
//all the inputs
<input type="submit" value="see your results" class="button"/>
</form>
<div id="results">
//here he should see the results.php output
</div>
jQuery
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
alert('Form is successfully submitted');
setTimeout(function() {
$('#results').load('results.php');
}, 1000);
},
error : function(){
alert('Something wrong');
}
});
return false;
});});
change this
$('#results').load('results.php');
To
$('#results').html(data);
if the returned results in data variable.
If i understood your problem correctly, results.php recieves the output you would show in the div #result.
To use the return-data from ajax-request you have data as javascript variable. To show the result in the div you need the following statment in the success function from ajax-call.
$("#result").html(data);

Using ajax to refresh a div content

I'm using JavaScript to handle my form submission and an Ajax call to refresh a certain div only "not the entire page", the form submission is successful but the value inside of the div doesn't refresh. I've tried other methods/solutions on stack overflow but they all seem to load the entire page or the content of the div is hidden on form submission.
ajax.js
$(document).ready(function () {
$('.ajaxform').submit(function (e) {
e.preventDefault(); // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType: 'html',
url: "info.php", // the file to call
cache: false,
success: function (response) { // on success..
$(".ld").load("info.php .ld"); //this hides the content of the div
// $('.ld').html(response);----This loads the entire page inside the div
}
});
return false; // cancel original event to prevent form submitting
});
});
info.php
<html>
<head>
</head>
<body>
<?php
...................
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" id="ajaxform" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
echo '<div id="emailform"></div>';
}
?>
</body>
</html>
i am trying to refresh the variable "$likes" inside the div tag, without refreshing the whole page, right now my current code hides the variable on form submit. i have to refresh manually to view any changes to "$likes".
You are sending an XMLHTTPRequest to a whole document and not to a portion of PHP (It is the latter that you need as I understand from your question). Additionnaly, you are sending the request to the same current page info.php, it is better to separate the concerns by splitting your PHP code to two parts (the one the renders the intial form and the one that is intentended to process it server side).
As a result, the AJAX will return all result of info.php (static markup + generated markup) and return all the final HTML and load it in .ld.
What I suggest is to create two files: form.php and process-form.php.Your AJAX call will be performed when document returened by form.php is ready and will be sent to process-form which will return required data after form processed.
And this should work without refreshing the page (the main purpose of using AJAX).

How to make a post request processed in the background

I've currently got the following button:
<input class="submitbutton" name="start" type="button" value="start"
onClick="window.location='vservermanage.php?_v=<?=$this->vid;?>'">
This button starts the current state of the 'service' - Either offline/online etc.
The page then loads & using if statements I can read whether it's offline or online. (PHP)
How do I make this post in the background instead - and once the result is returned process a javascript code, The following code also occurs when the page refreshes.
<?php if($this->msgsessuccess) { ?>
<div id="successbox"><?=$_lang[$this->msgsessuccess];?></div>
<?php } ?>
<?php if($this->msgseserror) { ?>
<div id="errorbox"><?=$_lang[$this->msgseserror];?></div>
<?php } ?>
I also have the following code which I want to do the same with HOWEVER I want to make this one automatic instead (every 2 seconds)
<input class="submitbutton" name="refresh" type="button" value="refresh"
onClick=" window.location='vservermanage.php?_v=<?=$this->vid;?>'">
The above code refreshes the state of the service.
There are a few elements to this but all can be achieved quite easily with JQuery. I assume you are including JQuery in your HTML head.
To illustrate you can tap into the click that happens on your submit button and then trigger an AJAX post, then do something with the results. Some example code:
$('.submitbutton').on('click', function(e) {
// Stop the browser from doing anything else
e.preventDefault();
// Do an AJAX post
$.ajax({
type: "POST",
url: "vservermanage.php",
data: {
_id: id_value // various ways to store the ID, you can choose
},
success: function(data) {
// POST was successful - do something with the response
alert('Server sent back: ' + data);
},
error: function(data) {
// Server error, e.g. 404, 500, error
alert(data.responseText);
}
});
});
The id_value parameter needs setting or obtaining, presumably from the original rendered page. You could for example, store the ID in a hidden form field e.g.
<input type="hidden" name="id_value" id="id_value" value="<?php echo $id;?>">
... and then include it like
_id: $("#id_value").val()
Regarding the second query, you could run the above POST within a standard JavaScript timer, e.g.
setInterval(function(){
$.ajax({
...
});
}, 2000);
I hope I've understood your question and that this helps put you on the right track.
You can use $.ajax(), or $.post(), even $.get(), but I wouldn't recommend allowing GET requests to modify data. Something along the lines:
function startProcess() {
$.ajax({
url: "vservermanage.php?_v=<?=$this->vid;?>",
type: "POST",
success: function(data) {
// proces the data if interested
// or just do what you need
}
});
}
, and you set this function as the click handler for your button.

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

Categories

Resources