jquery AJAX function issue - php

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.

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

How to load php instantly from ajax?

I am trying to directly load a page using ajax. Here are the details:
HTML:
<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>
script.js:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
do.php:
<?php
//Do whatever...
echo "Done!";
?>
What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?
As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.
I can suggest 2 things:
You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.
Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.
You could start loading immediately and then add the data when everything has completed.
var _data = null;
var _ready = false;
$.ajax({
url: 'do.php',
success: function(data){
_data = data;
tryAddData();
}
});
$(document).ready(function() {
_ready = true;
tryAddData();
});
function tryAddData(){
if(_ready && _data !== null){
$('#feedback').html(_data);
}
}

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>

ajax inject html into a div but keep the html elements including their ids

I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};

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