Please see my code below. I want to auto refresh a div on a php page. I tried to refresh through javascript and html header, but it is slowly slowing down my computer.
page2.php
<?php
if($_GET['type']!='ajax'){
include 'header.php';
echo "<div id='main-content'>";
}
?>
Itm 1</br>
Itm 2
<img class="ajax-loader" src="ajax-loader.gif" alt="loading..." />
<?php
if($_GET['type']!='ajax'){
echo "</div>";
include 'footer.php';
}?>
app.js
$.cergis = $.cergis || {};
$.cergis.loadContent = function () {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
if (pageUrl != window.location) {
window.history.pushState({ path: pageUrl }, '', pageUrl);
}
}
$.cergis.backForwardButtons = function () {
$(window).on('popstate', function () {
$.ajax({
url: location.pathname + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
}
});
});
}
$("a").on('click', function (e) {
pageUrl = $(this).attr('href');
$.cergis.loadContent();
e.preventDefault();
});
$.cergis.backForwardButtons();
i have tried different variation but no luck. please help me.
thanks.
app.js changed...
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
}
setInterval(function(){myTimer()}, 1000);
Try setTimeout:
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
setTimeout(myTimer,1000);//so that the request ends setTimeout calls a new request.
},
error: function () {
setTimeout(myTimer,1000);//If there is an error in the request the "autoupdate" can continue.
}
});
}
myTimer();//fire
this way setTimeout() waiting to finish the request to invoke a new request.
setInterval() does not wait, which makes simuntaneos generate multiple events, which causes the slowness.
You can use setTimeout($.cergis.loadContent, 1000); to refresh once or setInterval($.cergis.loadContent, 1000); to refresh each seconds (1000 milliseconds = 1second).
See http://www.w3schools.com/js/js_timing.asp
Related
this is simple test for ajax and i want to send variable t in my index.php and get data(t) in my process.php and alert digit 15 when i click on button but my problem is not alerting anything
this is my index.php
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}
})
})
})
</script>
<button id="btn">Click!</button>
this is my process.php
<?php
$res = $_POST['t'] + 5;
return $res
?>
Change codes like below:-
1.jQuery:-
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'t':t},
success:function (response) { //remove (
alert(response);
}
});
});
});
2.Php:-
<?php
$res = $_POST['t'] + 5;
echo $res; //use echo rather than return
?>
Reason:-
return is used for returning a value from a function to another piece of PHP code.jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
Note:- After doing These changes, Please check the browser console while running the ajax and see any error happen there? If yes share with us
i) Change your code with following code
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}) //Close brace missing
})
})
});
2) Change return to echo
$(document).ready(function(){
$("#btn").click(function (){
var t = 10;
$.ajax({
type:'post',
url:'process.php',
data:{
t:t
},
success:(function (response) {
alert(response);
// you didnt close )
}) // close of success
})// close of ajax
})// close of click
}); // close of document
Process.php
<?php
$res = $_POST['t'] + 5;
echo $res;
?>
You should add jQuery like this
<script src="jquery-3.2.1.min.js"></script>
If you actually have downloaded and placed the file in the same directory.
You can include in from a CDN if you don't want to download it.
use this instead:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
And fix your JS code: (remove the extra '}' ...)
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'test.php',
data:{
't':t
},
success:(function (response) {
alert(response);
})
})
});
});
When I use this code then multiple time ajax call 4-5 time load same data in output. Please help me to solve this. Please see the flowing code.
<script>
$(document).ready(function () {
$(window).scroll(function () {
if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
sendData();
}
});
function sendData() {
var offset_val = $('#offset_val').val();
$.ajax({
url: '',
type: 'POST',
data: {offset_val: offset_val},
dataType: "json",
success: function (response) {
if (response.status) {
$('#load_data').append(response.all_data);
$('#offset_val').val(response.offsets);
setTimeout(function () {
//$('.animation_image').hide();
}, 600);
} else {
$('#no-data-found').html(response.all_data);
// $('.animation_image').hide();
}
}
});
}
});
</script>
That's not the ajax issue, check the following line:
$(window).scroll(function () {
if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
sendData();
}
});
The above code executes for each single scroll moment when condition return true. That's why it is initiating multiple request for a single scroll.
My question is i want to get total time of ajax request..
I means when i click on button then make a ajax request and start timer and store time in button caption,after ajax request success stop timer...
My problem is
when i click on button call ajax request and after ajax request successfully then timer start.
What i want
I want to start timer before ajax request and stop after ajax request success
My html code
<input class="btn green start_timer" value="Sync" name="btn" type="button">
My js code
$(document).ready(function () {
var setTimer = null;
$("body").on('click', '.start_timer', function () {
var obj = $(this);
var start = 1;
setTimer = setInterval(function () {
start++;
obj.val(start);
}, 1000);
$.ajax({
type: "POST",
url: base_url + "timerstart/start/1325",
async: false,
success: function (data) {
clearInterval(setTimer);
}
});
return false
});
});
You can use jQuery Global Ajax Event Handlers
Steps:
Use ajaxSend to trigger timer.
a. Display overlay.
b. Start the timer function. Use Interval to update timer on every second.
Use ajaxComplete to stop timer.
a. You can use ClearInterval to stop timer.
Calculate the difference incase you want that value to display after overlay is closed.
Notes:
Note that above mentioned global events will work as expected when there is only one ajax call at any moment of time.
You need to use Global variables to get the values from global events and calculate the difference.
Try this, its worked for me
$(document).ready(function () {
var setTimer = null;
$("body").on('click', '.start_timer', function () {
var element = $(this);
displayTimer(element);
});
function getData(element){
$.ajax({
type: "GET",
async:true,
url: "",
success: function (data) {
clearInterval(setTimer);
element.val("Sync");
},
error: function (data) {
clearInterval(setTimer);
element.val("Sync");
}
});
}
function displayTimer(element){
var start = 1;
setTimer = setInterval(function () {
start++;
element.val(start);
}, 1000);
setTimeout(function(){
getData(element);
},2000);
}
});
try this below updated:
<script>
$(document).ready(function () {
var setTimer = null;
$("body").on('click', '.start_timer', function () {
StartDispalyingTimer($(this));
});
RunAjax = function (ele){
$.ajax({
type: "POST",
async:true,
url: "index2.php",
success: function (data) {clearInterval(setTimer);},
error: function (data) {clearInterval(setTimer);}
});
}
StartDispalyingTimer = function (ele){var start = 1;
setTimer = setInterval(function () {start++;ele.val((start-1));}, 1000);
setTimeout(function(){RunAjax(ele);},1000);
}
});
</script>
You've got async=false in the options for your ajax request. This makes your request synchronous so the execution of the script "hangs" untill the request comes back with a response. You should never use async is false.
I have a jquery ajax function:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
And I want to stop the function when a user hovers over the div 'Posts' and resume when the user stops hovering over that div. Is there any way I could do that.
Thanks
Here you go :)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
timer = setTimeout(posts,2000);
}
});
}
posts();
$(document).ready(function(){
$('#posts').hover(function(){clearTimeout(timer);}, function(){setTimeout(posts,2000);});
});
</script>
<div id = 'posts'></div>
Basically I added a mouser-over and mouse-out event handlers to the #post div which will clear and reset the timeouts respectively..
you probably wnat to stop ajax function from running what you are looking for is called
var pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
more on hover event
$("idofyourdiv").hover(
function () {
pfunc.abort();
},
function () {
pfunc();
}
);
First, I'd structure your base code somewhat like this:
var timer = null;
var request = null;
function posts() {
request = $.ajax({
url: 'backend/posts.php',
success: function(data) {
$('#posts').html(data).fadeIn(2000);
timer = setTimeout(posts, 2000);
}
});
}
posts();
Next, to clear the timer, run clearTimeout() on the timer object. timer stores the id of your timeout function, which might not exist when you try to clear it, so safely clear it like this:
if (timer !== null) {
clearTimeout(timer);
}
Finally, you should abort the AJAX request, so just add that in as well:
if ((timer !== null) && (request !== null)) {
clearTimeout(timer);
request.abort();
}
This one will check if your div is being hovered. And if it is true, the ajax call will be cancelled.
Trying not to modify too much your code:
function posts()
{
pfunc = $.ajax({
url: 'backend/posts.php',
beforeSend: function(){
if($("#posts").is(":hover")){
return false;
}
},
success: function(data) {
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts,2000);
}
});
}
posts();
javascript is not multi threaded so you can not stop a piece of code from running. As stated in other answers you may call abort on your ajax request but that is not stopping any code, it just aborting a request. And I'm not even sure its smart to abort the request when your just going to make the request again when the user stops hovering. I would let the request go thru and check the hover state in the response. If the hover state does not match your condition buffer the response and wait till the user stops hovering then resume your execution. Something like the following...
var hovering = false;
var onResponse = null;
$('.Posts').mouseover(function() {
hovering = true;
});
$('.Posts').mouseout(function() {
hovering = false;
onResponse && onResponse();
});
function posts() {
pfunc = $.ajax({
url: 'backend/posts.php',
success: function(data) {
onResponse = function() {
if(hovering) return;
$('#posts').html(data);
$('#posts').fadeIn(2000);
setTimeout(posts, 2000);
onResponse = null;
};
onResponse();
}
});
}
posts();
I have this function working
<script type="text/javascript">
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
});
</script>
But I need to have the same stuff happening (on IOS Devices), but instead of it happening when the browser reaches the loadmoreajaxeloader div, I simply need it to happen on an onclick event on a link. Thanks heaps.
Tried to add code but didn't format so here it is http://pastebin.com/p2VUqZff
You need to separate the Ajax and the scroll event.
So create a function to load the content like so:
// Create the load content function
function loadContent(){
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html){
if(html){
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
}else{
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
Then bind the scroll event to the window:
// Set the onscroll event
$(window).scroll(function(){
if($(window).scrollTop()==$(document).height()-$(window).height()){
$('div#loadmoreajaxloader').show();
// IF YOU WANT TO LOAD MORE CONTENT WHEN SCROLLING THEN UNCOMMENT THE NEXT LINE
// loadContent();
}
});
Then set the onclick event of the Load More link:
// Bind the click event to the Load More link
$('#loadMore').click(function(e){
// This will prevent any default action
e.preventDefault();
// Load the content
loadContent();
});
UPDATE
I forgot to make sure the events are assigned once the page has loaded. Surround all of your javascript with this:
$(document).ready(function(){
// PUT ALL THE JAVASCRIPT HERE
});
If you're saying you want the code to execute both on scroll and when your link is clicked you can put the common code in a function that you call from all the places you need it:
function doStuff() {
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
}
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
doStuff();
}
});
$("#idOfYourLinkGoesHere").click(function() {
doStuff();
return false;
});
Noting that returning false from the click handler stops the default behaviour for a click on a link (i.e., prevents it navigating away from the current page or moving back to the top of the page).
I wasn't sure if the .show() was to occur from the link so I've left it within the scroll handler. If it applies to either case move it into the doStuff() function.
Try to replace the scroll parts with something like that:
$('a#moreLoader').click(function() {
$('div#loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
return false;
});
where a#moreLoader is a link with 'moreLoader' as id :
<a id="moreLoader" href="#">load more</a>
I think what you are asking is "how can I reuse this function when a link is clicked" - and if so, the answer is this:
<script type="text/javascript">
// Declare the AJAX action as a separate function
var loadMoreContent = function() {
$.ajax({
url: "loadmore.php?wall=<?php echo $wall; ?>&lastid=" + $(".postitem:last").attr("id"),
success: function(html) {
if (html) {
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center><font color="white">No more posts to show.</font></center>');
}
}
});
};
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('div#loadmoreajaxloader').show();
loadMoreContent(); // Just call the separate function here
}
});
// ...and attach the function as a click handler to the link:
$('#idOfMyLink').click(function() {
loadMoreContent(); // Just call the separate function here
return false; // Return false to prevent navigation away from the page
});
</script>