I have a page displaying a catalogue of items on auction. Each has a button to place bids that has a timeout of 2 seconds to check if a new bid has been placed. There is also another script that checks if the minimum amount for this item has been reached. This one has a timeout of 3 seconds.
I had a timer on the page counting down until the auction closes that fired every second but this ended up blocking up the resources of the browser and everything lagged. What I ended up doing was calling this timer externally with javascript doing the actual countdown. This freed up the browser resources perfectly.
The problem I am facing is that if people are actively bidding in the last minute, it needs to recognise there is a bid-war taking place and add two minutes to the timer. I have the PHP code for this and it worked fine when the timers were on the page firing every second but now the ajax calls the timer once so the two minutes won't get added. Below is the code for the one second ajax, and secondly what I have now.
The question is, how can I get the second option to refresh the php page independantly from the main page? I realise I probably need it to run like before but that loads the browser again.
//ORIGINAL OPTION
$(document).ready(function() {
$(function worker(){
// don't cache ajax or content won't be fresh
$.ajaxSetup ({
cache: false,
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 1000);
}
});
// load() functions
var loadUrl = "/lot-timer.php?lot_id=<?php echo $rsprod['lot_id']; ?>&auction_id=<?php echo $row['auction_id']; ?>&eye=<?php echo $i; ?>";
$("#lot-timer<?php echo $rsprod['lot_id']; ?>").load(loadUrl);
// end
});
});
//SECOND OPTION
$(document).ready(function() {
$.ajax({
type: 'POST',
data:$(this).serialize(),
dataType: 'html',
url: "/lot-timer.php?lot_id=<?php echo $rsprod['lot_id']; ?>&auction_id=<?php echo $row['auction_id']; ?>&eye=<?php echo $i; ?>",
success: function (d) {//begin success
//add the pending message to a div on the page
$("#lot-timer<?php echo $rsprod['lot_id']; ?>").html(d);
}//end success
});
});
Related
I have a website, and in the navigation header, I have a player count, for the people who are currently online (On an external server). The count is outputted as a raw number generated by PlayersOnline.php, and I just include that.
How would I have this page update the player count every X seconds without refreshing the page?
You can use Javascript and jQuery to solve this:
$(function() {
updateCounter();
});
function updateCounter() {
$.ajax({
url: 'yourScript.php',
success: function(output) {
$('#yourCounterElementID').text(output);
},
complete: function() {
setTimeout(updateCounter(), 5000);//run again in 5 seconds
}
});
}
I am stuck again with a problem, let me explain it to you.
Inside the div I have fetched data with HTML SIMPLE DOM from other site. Like
<div id="data">.....</div>
It will refresh each and every time user will refresh the page. But I want something extra. What I wanna do is, refresh the div (inside which external data is fetched and added) periodically after 5 seconds.
Both the PHP SIMPLE HTML DOM script and this div is on same page.
Now I only need, any jquery or javascript code to refresh the div with data id after each 5 seconds with new data fron other site and all this without refreshing the whole page.
UPDATE:
I have used this code
$(document).ready( function() {
function getTheTime(){
$.get('http://your-domain/file.php',function(data,status){
$('#data').html(data);
});
}
var refresh = setInterval(
"getTheTime()",
5000
);
});
But the problem is very very strange, why it is not refreshing the div? Infact I have set alert for the interval but it also didn't worked. What the real problem is? Why it is not getting data from file.php and why actually it is not refreshing the div??
I am using latest jquery CDN. http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js
$(function() {
setInterval(function(){
$('#data').load('site.php');
}, 5000);
});
Definitely a job for AJAX...
Since you say you're already using jQuery, I'll walk you through the steps quickly to get an AJAX function set up and run it on an interval.
Step 1: Create a PHP file which gets the data you want to put in the DIV...
Just make a PHP file and put the code in to get the data:
<?php echo "The time is " . date('Y-m-d H:i:s');
Step 2: Set up an AJAX function to get the data from that file...
function getTheTime(){
$.get('http://yourdomain.com/ajax/getthetime.php',function(data,status){
$('#data').text(data);
});
}
(It would be possible to use the .load function instead, but it's far less flexible if you want to do anything with the data before putting it in the DIV).
Step 3: Call that function on an interval...
Next, we need to set up an interval to call the new function every 5 seconds.
$(function(){
var refresh = setInterval(
getTheTime(),
5000
);
});
Instead of using setInterval to call the function every 5 seconds, you can use simple long polling technique to refresh your div every 5 seconds. The problem with setInterval is that if the ajax request doesn't complete in specified time (5 secs here) there will be the chain of ajax requests.
function getTheTime(){
$.ajax({
type: "POST",
url: "http://your-domain/file.php",
success: function(response) {
$('#data').html(response); //update your div
},
complete: function(){
setTimeout(
getTheTime, /* Refresh time */
5000 /* ..after 5 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//display you error message
},
timeout: 5000 //Timeout is necessary to prevent chaining of unsuccessful ajax request
});
}
I use a page with Jquery tabs and if i submit one of the forms in the tabs only that tab is submitted and refreshed with this jquery code:
$(document).on("submit", "#plaatsen_stap3", function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type:"GET",
url:"../plaatsen_advertentie/plaatsen_advertentie_stap3.php",
cache: false,
data: $("#plaatsen_stap3").serialize(),
success:function(data){
$("#tab2").html(data);
}
});
});
But in the case that there has to be payed i want to reload the page with the payment page. I want to do that AFTER the div is reloaded with the data, because i need to put a payment row in the DB with the data from the GET. Is location an option? If i use that now only the div (tab2) is loaded with the payment page....
So:
1.push submit
2.submit the form and load page/script in div by Ajax
3.check in php script (within the div) if payment is needed
4.if yes,add row with payment data in database and reload entire page with payment page (with some Get data in the url (last inserted id)
success:function(data){
$("#tab2").html(data);
location.href = "/yourpage.php";
}
Since you wanna do once the HTML is generated, give some time like about 5 seconds?
success:function(data){
$("#tab2").html(data);
setTimeout(function(){location.href = "/yourpage.php";}, 5000);
}
This would work for your use case. This cannot be done from server side.
I think load() is what you are looking for. http://api.jquery.com/load/
The code below is intended as a guideline, and I'm not even sure it's working (I have not tested it). But I hope it will be of some help.
I would do something like this:
//Step 1
$(document).on("submit", "#plaatsen_stap3", function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type:"GET",
url:"../plaatsen_advertentie/plaatsen_advertentie_stap3.php",
cache: false,
data: $("#plaatsen_stap3").serialize(),
success:function(data){
//Step 2 - submit the form and load page/script in div by Ajax
//Make sure array[] is an actual array that is sent to the test.php-script.
$("#tab2").load("test.php", { 'array[]' , function() {
//Step 3 - check in php script (within the div) if payment is needed (Do this from test.php - don't check the actual div but check values from array[])
//Step 4 - if yes,add row with payment data in database and reload entire page with payment page (with some Get data in the url (last inserted id)
//Do this from test.php and use header-redirect to reload entire page
$("tab2").html(data); //Do this when test.php is loaded
}
} );
}
});
});
I have created a page "index.php" with a lot of divs and I need to refresh only one of the divs when the form is submitted.
This div loads the content from chat_window.php which is as follows:
<div id="chatbox">
<?php echo $res; ?>
</div>
<!-- Chat user input form-->
<?php echo $formchat; ?>
chat_window.php uses dynamic content - $res and $formchat from chat.php.
Everytime I post the form the content of $res and $formchat is modified and I need to reflect the same in my page which loads chat_window.php.
I used AJAX and jQuery to do the same as follows:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("input#chat").val();
var dataString = "chat="+ name;
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
}
});
$("#chatwrapper").load(chat_window.php);
return false;
});
});
The index.php has a div to show the chat_window as follows:
<!-- Chat window-->
<div id="chatwrapper">
<?php include ("chat_window.php"); ?>
</div>
As per my analysis, when I post the form, $res and $formchat are getting updated in the php. But when I load the chat_window.php, it doesnot loads the modified values. It rather loads the initial static values.
(Please dont suggest setInterval() as I dont want to refresh the page automatically).
Javascript is non-blocking, so it means that the interpreter does not wait for jobs to complete before processing the next one.
In your code, $("#chatwrapper").load('chat_window.php'); is being called pretty much before the ajax request above it completes. You will need to use the ajax success event to call the reload.
Try:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load('chat_window.php');
}
});
Try moving the .load() statement into the ajax success handler:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load("chat_window.php");
}
});
The $.ajax() call is asynchronous, which means that execution does not pause waiting for the response, rather, it moves on directly to the .load() call. (Which is also asynchronous, so really you've no guarantee about the order the response from each call will come in unless you don't make the second call until the first one finishes.)
I got my work done. Though I used another way of doing it.
What I have understood after few days of R&D is that, when we submit the form to a php, the request is sent with input params. When your php file processes this request, it might be updating some global variables. It completes processing the request and returns the control back to the calling index.php page.
The important thing to notice is:
The variable updates made while processing the form submit request do not persist after the control is returned. The global php variables will only get updated when the page gets refreshed.
So, if there is a strict requirement to avoid page refresh, collect the processed data from the php in some output string and pass it back to index.php like this:
$responseString = $res . "|" . $formchat;
echo $responseString;
The success parameter of .ajax will receive this output and accordingly you can update your chat window or any other form.
I have some problems with redirecting/reloading after a successful ajax call.
Here is the situation:
I have item for deletion saved in an array. When I click on a button it calls for PHP file via ajax, and after success I need to reload the page. But I have some problem doing this.
I searched the internet and couldn't find a working solution.
I have PHP file which goes through the array deleting item by item from the database.
foreach($arrayVals as $key=>$val)
{
//bla bla
}
Also, I have jQuery part:
$("#button").live("click",function(){
$.ajax({
url, data, type... not important
success: function(html){
location.reload();
}
});
});
I mean, the code works, but not good. It does delete items, but not all of them and then it reloads the page.
Like, if I have 10 items to delete, it deletes like 6-7, and 3-4 items stay undeleted.
It acts like it reloads the page too soon, like PHP file does not have enough time to process everything :D
BrixenDK is right.
.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
use this Reload page
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
Using the ajaxSuccess to reload the page after ajax success.
$(document).ajaxSuccess(function(){
window.location.reload();
});