window.location.reload(true) not reloading the page correctly - javascript

I have a PHP page which fetches data from a MYSQL database and generates HTML content based on rows returned from the database.
I am adding a new row in database on click of a button using AJAX, Jquery and PHP. After adding the new row, I am using window.location.reload(true); to reload the page. But the HTML elements corresponding to new row are not shown when I click the button. However, if I manually refresh the page using F5, the newly added content is shown.
Anyone knows why this could happen?
Below is the function which I call on click of a button. The page increaseCount.php updates database to increase the count of actors. But the HTML elements corresponding to new count are not shown until I refresh the page using F5.
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
}
} );
window.location.reload(true);
}

The problem is that you are mixing ajax with a complete page reload.
The $.ajax call by default is asynchronous (the first a from ajax...). Therefore it sends a request to increasepostcount.php and then immediatelly reloads the page - not waiting for increasepostcount.php to process the request. By the time you manually refresh the page, increasepostcount.php will have completed the processing of the ajax call, therefore its result are reflected on the page.
If you use ajax, you should not use page reloading. Use javascript to update that part of the page where these records are displayed based on the results returned by the ajax call.

You need to be sure that the ajax call has done to do what you want, in your case "window.location.reload(true);" is running before the ajax response, due to asynchronous communication between Client and Server to avoid "freezing" on the screen and an unresponsive user experience.
You have to put your refresh code on Success ajax response or on done :
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
// to do here
//window.location.reload(true);
}
} ).done(function () {
// or to do here
window.location.reload(true);
});
}

in your page increaseCount.php consider adding a header at the end.
For example:
if(isset($_POST['name'] &&
isset($_POST["image"] &&
isset($_POST["character"]) {
/* do your stuff here */
header("Location: /thePageYouWantToRefresh.php");
exit;
}

Related

window.history.pushState the pages do not update

I am using window.history.pushState() to change the url of the page and put it in the history list, everything works but I have a problem, if for example in a page I execute an operation (ajax), which changes the values ​​in the db and textually update a part of the page, if I browse elsewhere and return to this page, I find what was originally there and not the changes made, to see them correctly I have to refresh the page.
I don't currently use any caching systems
Some contents are loaded with ajax others are directly on the page
window.history.pushState() is used only in the home page in the others I don't need it even if it happens on all
in the example page I have this code
function init() {
$('#weekDays').on('show.bs.modal', function(event) {
var modal = $(this);
$.ajax({
type: 'post',
cache: false,
url: '/my_account/get_giorni_chiusura_sett',
dataType: 'html'
}).done(function(data) {
modal.find('.modal-content').html(data);
});
});
$('body').on('click', '#save-closing-days', function() {
var dataString = $('#form-weekdays-close').serialize();
$.ajax({
type: 'post',
cache: false,
url: '/my_account/set_giorni_chiusura_sett',
data: dataString,
dataType: 'json'
}).done(function(data) {
if (data.update === 'ok') {
var daysClose = $.map(data.giorni, function(v) {
return '<strong>' + v + '</strong>';
}).join(' - ');
$('#list-days-close').html(daysClose);
$('#weekDays').modal('hide');
}
});
});
}
when I arrive in the page the content is loaded without ajax and generated by php, the first function loads the content in the modal upon opening, the second one saves / updates the data on the database and updates the text on the DOM
Closing days: Saturday - Sunday
Update and become
Closing days: Sunday
Now I move to other pages from the menu and back, but I find it again:
Saturday - Sunday
If I reload the page, the data is updated
The History API doesn't maintain the state of the DOM for you. You need to do that yourself. MDN has a good guide but the short version is:
When the user clicks a link then your JS should prevent the default behaviour and call pushState to change the URL and use DOM methods to update the page to match what the server would send for that URL.
When the user presses the back button in their browser and a popstate event fires then your JS should read the URL (and state data if applicable) from the event and using DOM methods to update the page to match what the server would send for that URL (i.e. undoing the changes from the previous paragraph).

How do I reload a page without the user noticing?

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

How to perform a count statistics without wait for ajax response

I want to count number of click to particular div(#counter) and then redirect to a different site.
I did a ajax call on click event of the div with the id counter. and then on success function i'm doing a redirect on ajax complete. Here is the code
jQuery('#counter').click(function(){
var data = { clicked:'yes'
};
jQuery.ajax({
url:"stat.php",
type:"POST",
data:data
}).done(function(res){
window.location = "http://www.myurl.com";
});
});
The thing is, this is making some time to redirect such that user have to wait until the ajax complete event trigger.
Since am not care of the response i just need a request that initiates user has clicked that(#counter) div so i'll just increment the value in DB. So is there a way to redirect to a different website as soon as the ajax started? I don't want the user to wait for the response and then redirect. because the response is not needed in this case. This is only for site stat or what is the best way to count a button click and then redirect them to a different site.
Edit, updated
Try
jQuery('#counter').click(function(){
data = { clicked:'yes'
};
var redirect = function() {
setTimeout(function() {
window.top.location.href = "http://stackoverflow.com/questions/"
+ "25554598/"
+ "how-to-perform-a-count-statistics-"
+ "without-wait-for-ajax-response/";
}, 1500); };
$.when(jQuery.ajax({
url:"/echo/json/",
type:"POST",
data:{json:JSON.stringify(data)}
}), redirect())
.done(function(_data) {
alert(_data[0].clicked)
})
});
jsfiddle http://jsfiddle.net/guest271314/51g5huvq/
Just move your redirect code outside of the .done callback. This way, when you click, two things are instantly done : an ajax request is sent, and the redirection is fired. You can wrap the redirection in a short setTimeout to make sure the ajax request has been fired before redirecting the client.
jQuery('#counter').click(function(){
var data = { clicked:'yes'
};
jQuery.ajax({
url:"stat.php",
type:"POST",
data:data
}).done(function(res){
});
setTimeout(function(){window.location = "http://www.myurl.com";}, 500);
});

How to store/remember the data fetched from ajax call?

I'm retrieving some data into a JSON array, then display it into an HTML table which contains some data enclosed within hyper links. i.e. a couple of the columns' data are clickable, once clicked it displays another JSP page (say page #2) with some more data which was kept on the JSON array itself.
Now this page 2 has a 'Back' button functionality - the expected behavior is when user clicks the 'Back' button it should go back to page 1 where the HTML table data was displayed and user should be able to see the data which they first fetched too. i.e. there should be some way to remember the data fetched from my initial AJAX request and retrieve the same data which user fetched in page 1 when they go back to that page from the child page#2.
Th AJAX call is triggered when user enters an account# and the type of account - I fetch data accordingly and get the result in the 'response' object and neatly display it on html table, but after user moves from that page and again hits the back button I see the page#1 without the table. Now again I cannot ask the user to re-enter the details to see the data that they retrieved earlier. It's pretty annoying.
Please give me a solution to this problem. Thanks All.
Appreciate for taking time to read this.
Here's a part of the code:
$(document).ready(function () {
var flag = "1";
$('#accountType').bind('change', function (event) {
var accountType = $('#accountTypeSelect').val();
var account = $('#accountText').val();
jQuery.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}' + "/Page1.spr", //request page
cache: false,
dataType: "json",
data: {
"accountType": accountType,
"account": account,
"flag": flag
}, //data sent to request page
success: function (response) {
// code to display the data into the html table
},
error: (function (message) {
console.log("error message : " + message);
}),
statusCode: {
404: function () {
alert("page not found");
}
}
});
});
You can save the data in HTML5 sessionStorage or localStorage using the setItem method as follows:
success: function(response) {
sessionStorage.setItem("result", response)
// code to display the data into the html table
}
And access it later using the getItem() When you come back to the page like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// code to be executed when old dats is found
}
else{
}
Ideally you code in first pages load will be something like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// data exists : code to be executed when old dats is found
}
else{
jQuery.ajax({}) // send the AJAX request to fetch data
}
You can read more about session and local Storage here
Browser support for web storage API.
Update
If you don't have HTML5 support, you could use jQuery cookie plugin (There are plenty of others as well) for storing data at client side.
You can store data into a cookie as follows:
$.cookie("result", response);
Then to get it from the cookie like:
$.cookie("result");
You maybe can use cookie via jquery. But user have to enable the browser's cookie. It usually enabled by default setting.
To add:
$.cookie("key1", data1);
$.cookie("key2", data2);
To read:
$.cookie("key1");
To delete:
$.removeCookie("key1");
So, you can try to read cookie to load table data, if no data, call ajax:)
Another way is to save it in a hidden input:
success: function(response){
$("#hiddenInput").val(JSON.stringify(response));
}

Using ajaxForm plugin on view that is itself an AJAX response

I am building a messaging system for my site. The mailbox is flat, i.e. accessing the inbox, or sending a new message does not move to another page, it just toggles divs. When a user clicks a message, an AJAX call replaces the inbox div with the chosen thread. Inside the thread view, there is a form to reply to the message.
A few problems:
From inside this thread_view, which sends an AJAX response to a div nested inside the entire mailbox div, I don't have access to document objects outside of it. So, I can't manipulate divs outside of this view, such as the one that receives the AJAX beforeSend and Success messages. I think this may be accomplished with some kind of .load(), though I'm not sure exactly how.
My AJAX doesn't fire. I am using the Ajax.Form() plugin. I think this problem might be related to the first, but I can't say for certain. I'm not sure how to begin troubleshooting the Ajax request because I get no errors in the console.
I wonder if the problem has to do with the fact that I am trying to send an ajaxRequest from a view that is itself a response from a previous ajaxRequest, i.e. the entire view for the thread is a result of the following, in the same js file as the next request:
// compose a message function
$('#send_message').on("click", function(e) {
var send_message_options = {
type: 'post',
url: "/users/new_message",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#message').html(response);
}
};
$('#message_form').ajaxForm(send_message_options);
});
My new AJAX request, which does nothing:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
console.log("trying for reply");
var reply_options = {
type: 'post',
url: "/users/reply",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#reply_message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#reply_message').html(response);
}
};
$('#reply_in_thread').ajaxForm(reply_options);
});
I couldn't say why the ajaxForm() plugin failed, but a jquery $.post was successful. The code that worked below:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/users/reply',data,function(response){
$('#reply_message').html(response);
})
});

Categories

Resources