Getting AJAX to .append(data) with a delay or queue - php

So due to a lack of sleep or pure misunderstanding I am having troubles getting a piece of jQuery code to work.
So please community your my only hope :P
I have a jQuery function which executes upon an element onClick="" attribute
<div id="next" onClick="choice('next', '<? echo $page; ?>')"></div>
Basically what I am trying to achieve is thus: to have an element fade out then call a PHP script via AJAX grab the relevant data and that data to the previously hidden element discussed earlier and then fade said element back into focus.
The problem I am having is that no matter what I do (using .queue or setTimeout) or just using the standard 'fx' queue in jQuery the AJAX data always loads ASAP and any attempt to delay does not work.
Below is the code, thank you in advance for any help.
function choice(value, page) {
var timer;
$.get("http://<? echo ROOT; ?>includes/forms.php", { choice: value, page: page }, function(data) {
clearTimeout(timer);
$("#slideOut-inner").fadeOut(2000).empty();
timer = setTimeout(show, 2200);
function show() {
$("#slideOut-inner").append(data).fadeIn(2000);
}
});
}

Set the delay outside of $.get's success callback, otherwise it will only happen once client receives the response from the server:
$("#slideOut-inner").fadeOut(2000, function() {
$(this).empty();
$.get("http://<? echo ROOT; ?>includes/forms.php", {
choice: value,
page: page
}, function(data) {
$("#slideOut-inner").append(data).fadeIn(2000);
});
});

Try putting the append() in the callback of the fadeOut():
$.get("http://<? echo ROOT; ?>includes/forms.php", { choice: value, page: page }, function(data) {
$("#slideOut-inner").fadeOut(2000, function() {
$(this).empty()
.append(data).fadeIn(2000);
}).empty();
});

Related

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

jquery AJAX function issue

I'm trying to run a function that executes a spinner while a PHP script is loading and also refreshes a PHP file that counts the number of rows inserted to show the script's progress.
This is what I have so far:
<script type="text/javascript" language="javascript">
// start spinner on button click
$(document).ajaxSend(function(spinner) {
$("#spinner").show();
});
// refresh progress script and output to #content div
function updateProgress(){
$('#content').load('progress.php');
}
myTimer = setInterval( "updateProgress()", 2000 );
// Execute the primary function
$(document).ready(function() {
$("#driver").click(function(event){
$('#stage').load('execute.php');
});
});
// hide spinner and content div when finished
$(document).ajaxStop(function(spinner) {
clearInterval(myTimer);
$("#spinner").fadeOut("fast");
$("#content").fadeOut("fast");
});
</script>
Right now the updateProgress() function starts after the first interval is over even if the button hasn't been pushed, so I'm assuming I have to tie it in with the spinner function but I'm just not entirely sure how to make that work.
EDIT: Here's the HTML that displays the button and the div's:
<div id="stage">
Click to Import New Data into AssetData Table
<p>
<div id="spinner"><img src="/images/spinner.gif" alt="Loading..."></div>
<div id="content"></div>
<p>
<input type="button" id="driver" value="Load Data" onClick="this.disabled=true;"></div>
You need:
Load page with button. When you push button file execute.php should upload.
After user push button, spinner appearing and browser starts make ajax request to progress.php.
When execute.php uploaded, spinner disappears, progress results disappears.
jQuery code below doing this:
var myTimer;
$(document).ready(function () {
// Execute the primary function
$("#driver").click(function (event) {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139',
success: function (data) {
//$("#someField").html(data); // you put result of executting `execute.php` into #someField field by uncommenting this string
$("#spinner").toggle();
$("#content").fadeOut("fast");
clearInterval(myTimer);
},
error: function (bob) {
// show error
console.log('get error');
clearInterval(myTimer);
},
beforeSend: function () {
myTimer = setInterval(function () {
/* // uncomment this when you will use it with real files and server
$.ajax({
url: 'progress.php',
success: function (data) {
$("#content").html(data);
}
});
*/
$("#content").append("progress data<br>");
console.log('progress executed');
}, 1); // change delay, when you work with real files and server
$("#spinner").toggle();
console.log('ajaxSend handler executed');
}
});
console.log('main function executed');
});
});
Look this example (this example for code above), please.
Now, this code do all what you need. Right?
Don't forget to uncomment some lines (ajax requests), change intervals, remove debug outputs (line 29, for example) etc.
Notice (and change it, when you will use my code) url field of execute.php ajax-requst. I had used weather api (just for example, you musth change it to progress.php because download this data takes some time, so you can see results. Remove weather url and put url to progress.php.
Also, you can check this example. Code is tided up and this version allows to load file and after that load another. And after that load another. + now myTimer+setInterval+function progress synergizes better, I suppose.
Hope, this will help you.

refresh div with new data as if it was a page refresh

Is it possible using jQuery to literally refresh a div?
Nothing like submitting a form or anything like that.
I have a data stream which is updated else where and all I want to do is refresh the div and all its contents as if it were a page refresh. I can't link to that page to make a return that populates as the only output is just raw data.
The div itself contains all the data display processing. Nothing needs to be fetched as the data is already there.
you have to use setinterval with ajax function,
$(document).ready(function(){
setInterval(function(){ refreshDiv(); }, someInterval);
});
function refreshDiv(){
$.ajax({
url: "http://yourrequestpath",
.....
});
}
<div id="data"></div>
<script>
$('#div').load("loaddata.php", function() {
window.setInterval("loadData", 60000);
});
function loadData()
{
$('#div').load("loaddata.php");
}
</script>

How can I use jQuery effects on Ajax loaded content?

Hi and thanks for taking some time to look at my question. I have a part of the page where content is dynamicly loaded into from another file. Reason for this is it needs to be live updated. Now I want to be able to apply jquery effects that are usually used for show/hiding content (slide, fade etc) to animate the difference between the current data and the new data. This is the code used to get the content and load it into the div:
function k() {
$.post("../includes/ajaxAgenda.php", {
limit : value
}, function(data) {
$('#tab-agenda').html(data);
});
};
$(document).ready(function() {
k();
$('#tab-agenda').scroll(function() {
loadMore();
});
});
var refreshId = setInterval(function() {
k();
}, 1000);
So I guess my question is how do I animate what gets loaded in so it doesn't just "pop" from one content to another?
edit: I tried using the .live instead of .scroll but it doesn't seem to work:
$(document).ready(function() {
$('#tab-agenda').live("scroll",function() {
alert("hi");
loadMore();
});
});
You need to use live function of jquery to bind the dynamically added elements.
Ref: http://api.jquery.com/live/
Try this :
$('#tab-agenda').live("scroll",function() {
loadMore();
});
I suggest you to add the ajax loader image with proper css over the content/ div as like below.
function loadmore(){
$("#loader").css('display','block');
//your
//code
//here
$("#loader").css('display','none');
}
html
<img id="loader" src="ajax-loader.gif" style="display:none" />
<div id="content">
your cont to display
</div>

how to stop setInterval after php script is done executing through ajax

I have searched for the answer to this and the reason I'm not finding it could just be that I'm completely botching my script from the getgo, so please anyone who can help I greatly appreciate it.
I have a javascript function which fires onClick of a form submit and runs an ajax call to script1.php, then starts a timer with setInterval. setInterval is calling another javascript function to poll an output file from script1.php so we can get new data added to the screen. This part works fine.
However, I'd like to stop the timer when script1.php is done processing. How do I do this? I've tried putting in a clearInterval(myTimer) in script1.php as the last statement it runs, and it seems to be showing up in the browser, but it's not stopping the timer.
<script type="text/javascript">
var myTimer;
var file1 = "script1.php";
var file2 = "script2.php";
function startTimer(myTimer) {
myTimer = window.setInterval(loadData, 2000);
}
function stopTimer() {
clearInterval(myTimer);
}
function startData()
{
ajaxRequest(file1,data);
startTimer(myTimer);
}
function loadData()
{
ajaxRequest(file2)
}
</script>
<form action="index.php" method="post">
<div style="text-align:left;width:300px;">
<textarea style="width:300px;height:200px;"> </textarea><BR>
<button type="button" onclick="startData()">get data</button>
</div>
</form>
<div id="myDiv" style="text-align:left;width:500px;border:solid 1px #ccc;padding:50px;">
please enter data above
</div>
Yes, you botched it. You should just have PHP return the data directly to the script that does the AJAX call.
On AJAX success, any text outputted by the PHP script will be available to the success callback.
If you were using JQuery, it would be as simple as:
$.ajax({
url: 'someurl',
success: function(response) {
// do whatever with response
}
});
You're passing myTimer as a parameter to startTimer. This makes myTimer a local variable to startTimer. Therefore it's not updating the global myTimer.
It should be:
function startTimer() {
myTimer = setInterval(loadData, 2000);
}
function stopTimer() {
clearInterval(myTimer);
}
Then you just need to call startTimer() and stopTimer().
when you starting your interval assign it to any PUblically accessible variable say "INTERVAL_ITEM"
and when your response achieved clearInterval(INTERVAL_ITEM);

Categories