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

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

Related

Ajax is driving me nuts. Why is Jquery post method failing in this specific case?

Ok, so ajax seems to be misbehaving. In other words i'm doing something wrong. I have a simple angular js app. The html looks like this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="../scripts/form_controllers.js"></script>
</head>
<body ng-app="EditDocApp">
<div ng-controller="EventDetector">
<input ng-model="event">
<button ng-click = "SelectEvent()">Click</button>
</div>
</body>
</html>
form_controllers.js contains a call to the Jquery post method in the EventHandle angular service. This is invoked in the calling of EventHandle.ajaxRequest() in the $scope.SelectEvent method in the EventDetector controller. This is form_controllers.js:
var editDocApp = angular.module("EditDocApp", []);
editDocApp.controller("EventDetector", eventDetector)
.factory("HandleEvents", handleEvents);
function handleEvents() {
var pass_back = {
ajaxLastReturn: "one",
ajaxRequest: function() {
$.post("http://localhost/TrailGuide/Website/Interface/webDataModelBuild/Documentation/scripts/test1.php", {}, function(response) { alert(response); })
.fail(function() { alert("nah"); });
}
}
return pass_back;
}
function eventDetector($scope, HandleEvents) {
$scope.event = "";
$scope.SelectEvent = function() {
$scope.event = "select";
HandleEvents.ajaxRequest();
};
}
The $.post method is failing every time i execute it by calling $scope.SelectEvent() from the button in the view (an alert box with "nah" pops up). I've tested the address passed to $.post by copying and pasting to the browser address box and it runs fine. I've tried the $.post method with and without data, no dice. I've tried jquery.ajax, still no dice. The php file, test1.php, is as follows:
<?php
echo "I am here!";
?>
Can somebody please point out what i am missing here? Is there some setting in php.ini that could be effecting this? Btw, this is my very first post on stack overflow so go easy on me! I'll get the hang of it. Thanks a bunch!

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.

Global variable inside Ajax function

I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
$.ajax({
url: 'loaddata.php',
success: function(data){
var arr = data.split('|');
for(var i=0; i<arr.length; i++){
var miniArr = arr[i].split(',');
db.push(miniArr);
}
printTest(); //work here
}
});
printTest(); //not working and collapse here
});
function printTest(){
document.getElementById('test').innerHTML += db;
}
</script>
</head>
<body>
<div id="test" />
</body>
</html> `
My php file should be fine,
<?php
$database = file('database');
foreach($database as $item){
if ($item===end($database))
echo $item;
else
echo $item.'|';
}
?>
Thanks in advance.
Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.
If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.
You can't call your second printTest() here.
And for the record, try to use JSON to retrieve your datas, it's way much easier.

how to run java script file after invoke with ajax and append to the output

My problem with the javascript file run through the AJAX call is
for example :
index.php
$(function(){
$(".btn-ajax").click(function(){
$.getJSON('ajax.php',function(data){
jsInc(data['js'][0]['src']);
$("#response").html(data['html']);
});
});
function jsInc($src){
var head = document.getElementsByTagName("head")[0];
var script=document.createElement("script");
script.type='text/javascript';
script.src = $src;
head.appendChild(script);
}
ajax.php
$arr['js'][] = array('src'=>'js.js');
$arr['html'] = '<input type="button" class="btn" value="show message"/>';
echo json_encode($arr);
js.js
$(function(){
$(".btn").on('click',function(){
alert("test !");
});
});
but when execute ajax request and append input button to the index.php file this button click event not worked!
please help me
Thanks
You want to get script via AJAX right? You can use $.getScript:
$.getScript("script.js");
Load a JavaScript file from the server using a GET HTTP request, then execute it.
I think what's happeneing is your first loading the JS which binds the click listener and then loading the Button. SO the listener doesnt get bound
Try reversing the order like:
$("#response").html(data['html']);
jsInc(data['js'][0]['src']);
Try rebinding the click function after the Ajax call (success):
$.ajax({...
success: function(data) {
$(".btn").click(clickFunction);
}
});
$(".btn").on('click', clickFunction);
function clickFunction() {
alert("test !");
}
You need to change your function in js.js to be a delegate function.
$(function(){
$('body').on('click','.btn',function(){
alert("test !");
});
});
When you do it this way. The .btn element doesn't even need to be present before the script is run. It attaches the event to the body tag prior to checking if the .btn element exists.

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

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

Categories