Loading external php page - php

The function below grabs a php page, then reloads it every 5 seconds. The only thing coming from that roomdata.php page is a string with a color name (blue, yellow, etc.). I wanted to be able to use that name in the function modifyLight(color), but it's not letting me. I don't know why, but no matter what I tried, it's not treating the variable data as a string, even if I clarify it as one.
Any help is appreciated, thanks!
$(function(){
function loadData()
{
var data = load('roomdata.php');
modifyLight(data);
setTimeout(loadData, 5000); // makes it reload every 5 sec
}
loadData(); // start the process...
});

You are using async ajad calls. You need to configure your request to be sync.
$.ajax(URL, {async : false});
In that way the execution of the next line will be done until the ajax request Is finished.
EDIT
Your function should be like this:
$(function(){
function loadData() {
$.post("roomdata.php", function(result) {
modifyLight(result);
setTiemout(function() { loadData(); }, 5000);
}
}
loadData(); // start the process...
});
The problem with the way you were doing it is that $.load(); only loads something with Ajax and put the content on $('#yourdiv'); It does not return anything. You need an ajax request with something in the "success" event. In the code I gave you, $.post makes an ajax request via post to roomdata.php and then, once the ajax is finnished, it executes the function function(result) { ... }

Related

jQuery Loop that slows your browser

I'm creating online chat, but I'm wondering while using jQuery .load() in my script, my browser seems to get slow. When i checked the inspect element "Net" section, it loads bunches of GET-data... etc.
I would like to know if there's a better script solution with this code to prevent chat being heavy in the background while the data keeps looping in the background to check who's keep coming online/offline.
setInterval('loadThis()', 5000);
function loadThis () {
$("#loads").load('includes/users.php', function(){
$(".chat-side-panel li").each(function(i){
i = i+1;
$(this).addClass("stats"+i);
var status = $(".stats"+i).find("span.bullet").data("status"),
flag = $(".stats"+i).find("span.mail").data("flag");
if(status == 1) {
$(".stats"+i).find("span.bullet").addClass("online");
}
if(flag == 1) {
$(".stats"+i).find("span.mail").addClass("active");
}
});
});
}
the Chat-Side-Panel will be the main panel, and LI will be the listings of users including their status (online/offline) and flag (message received). As for the standard, what can you suggest for the setInterval time loading (if 5sec. is enough) or should i increase it.
Thanks for your input for this.
PS. We're doing this with both PHP/MySQL also.
One issue I see is that you keep re-querying the DOM for the same elements. Get them once, re-use them thereafter:
var load_target = $('#loads');
function loadThis () {
load_target.load('includes/users.php', function () {
load_target.find('.chat-side-panel li').each(function (i) {
var stats_li = $(this),
bullet = stats_li.find('span.bullet'),
mail = stats_li.find('span.mail');
bullet.toggleClass('online', (bullet.data('status') == 1))
mail.toggleClass('active', (mail.data('flag') == 1));
});
});
}
I don't know all of your involved logic or what the rest of your system looks like, so this particular code may not work exactly. It should simply serve as a re-factor done in a vacuum to show what that function could look like if you stopped hitting the DOM so hard.
Also, use of setInterval is not generally recommended. If the load of the remote file takes a while, you could end up calling loadThis() again before a previous one was completed. This would compound your DOM issues if calls to loadThis() began stacking up. Recursive use of setTimeout is preferred in a situation like this. Here is the above code modified to run recursively, and some usage examples below that:
var load_target = $('#loads'),
loadThis = function (start_cycle) {
$.ajax({
url: 'includes/users.php',
dataType: 'html',
type: 'GET',
success: function (response) {
load_target
.html(response)
.find('.chat-side-panel li').each(function (i) {
var stats_li = $(this),
bullet = stats_li.find('span.bullet'),
mail = stats_li.find('span.mail');
bullet.toggleClass('online', (bullet.data('status') == 1))
mail.toggleClass('active', (mail.data('flag') == 1));
});
},
complete: function () {
if (typeof start_cycle !== 'boolean' || start_cycle) {
load_target.data('cycle_timer', setTimeout(loadThis, 5000));
}
}
});
};
//to run once without cycling, call:
loadThis(false);
//to run and start cycling every 5 seconds
loadThis(true);
// OR, since start_cycle is assumed true
loadThis();
//to stop cycling, you would clear the stored timer
clearTimeout(load_target.data('cycle_timer'));
Last years (around 2012) I developed a chat system for a social network, and saw that
Using setInterval issue is when the request is being sent regularly, without waiting or carry about the result of the first requests in the queue. Sometimes the script can not respond and Mozilla or IE asks the user whether he should block or wait for the non-responding script.
I finally decided to use setTimeout instead. Here is what I did (I use $.getJSON so please study the example and how can use load instead)
function loadThis () {
$.getJSON('url').done(function(results){
//--use the results here
//then send another request
setTimeOut(function(){
loadThis();
},5000);
}).fail(function(err){
//console.log(print(err))
setTimeOut(function(){
loadThis();
},1000);
});
}
loadThis();
PS.: I would like to mention that the time depends on our many items are to be retrieved in your users.php file. Maybe you should use the paging tip. Your users.php can then treat url params users.php?page=1&count=100 for the first request, users.php?page=2&count=100 for the second until the results rows number is 0.
EDITS: In addition, I suggest you consider not interacting with the DOM every time. It is important too.

Refresh PHP functions with JavaScript

i need a a script that will refresh the functions:
$ping, $ms
every 30 seconds, with a timer shown,
i basicly got this script:
window.onload=function(){
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds;
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();
}
but it refreshes the whole page, not the functions i want it to refresh, so, any help will be appriciated, thanks!
EDIT:
I forgot to mention that the script has to loop infinatly
This here reloads the whole page:
window.location.reload();
Now what you seem to want to do is reload portions of the page, those portions having been generated by php functions. Unfortunately php is server side so that means you cant get the client browser to run php. Your server runs the php to generate stuff that browsers can understand. In a web browser open a page you made using php and choose to view source and you'll see what I mean.
Here's what you'll need to do:
Make your two functions ping and ms accessable via ajax
Instead of window.location.reload() do a call to jQuery.ajax. on success write to your page
Here's what I think would be the ideal way of dealing with this... I haven't seen the php side of your problem but anyway:
make a file called ping.php and put all your ping function code in there. ditto for ms
in your original php file that called those functions, make a div at each point where you wanted a function call. Give them appropriate ids. Eg: "ping_contents" and "ms_contents"
You can populate these with some initial data if you want.
In your js put in something like this:
jQuery.ajax(
{
url : url_of_ping_function,
data : {anything you need},
type : 'POST', //or 'GET'
dataType: 'html',
success : function(data)
{
document.getElementById("ping_contents").innerHTML = data;
}
});
do another one for the other function
What you want is AJAX, Asynchronous JavaScript and XML
You can use jQuery for that.
I can put an example here, but there is a lot of information to be found on the internet. In the past I wrote my own AJAX code, but since I started using jQuery, it's all a lot easier. Look at the jQuery link I provided. There is some usefull information. This example code might be the easiest to explain.
$.ajax({
url: "test.php"
}).done(function() {
alert("done");
});
A some moment, for example on a click on a button, the file test.php is executed. When it's done, a alert box with the text "done" is shown. That's the basic.

Making two simultaneous AJAX calls to PHP

I have a form which submits an AJAX request to one of my controllers which uploads a file using PHP's curl. I want to show the user the status of that (PHP) upload, so I store the PHP upload progress in a session variable. Meanwhile, the submission of the form also starts a setInterval() which makes a different AJAX request to controller which checks the session variable. My problem is that the second AJAX call seems to only fire once (instead of throughout the upload process) and so instead of progressively updating the progress, it just returns 100 at the end. What am I doing wrong?
Here's my code:
(note: I'm using the jQuery form plugin to assist with the file upload. It also adds some additional callbacks)
<script>
var check_progress = function() {
$.ajax(
{
url : '/media/upload_progress',
success : function(data) {
console.log(data);
},
async : false
}
);
var options = {
beforeSend : function() {
$("#MediaSubmitForm").hide();
$("#MediaSubmitForm").after('<img class="hula-hippo" src="/img/hippo-hula.gif" />');
t = setInterval( check_progress, 500 );
},
success : function(data){
$(".hula-hippo").hide();
$("#MediaSubmitForm").after("<h3>Upload complete!</h3><p>Do <strong>you</strong> want to <a href='#'>create a project</a> of your own?</p>");
window.clearInterval(t);
console.log(data);
}
};
$("#MediaSubmitForm").ajaxForm(options);
</script>
Use setTimeout();. setInterval() executes the code after the time specified and setTimeout() executes the code every time it reaches the specific time.
These question explain well of their difference :)
setTimeout or setInterval?
'setInterval' vs 'setTimeout'
setInterval & setTimeout?
setInterval and setTimeout
JavaScript setInterval and setTimeout
And a search of this on SO will solve your problem :)
It sounds like this is a PHP locking issue. See the first comment in the answer to this question:
jQuery: Making simultaneous ajax requests, is it possible?

wait to leave page until ajax is done

Basically, I am sending a $.POST() when an element is clicked. this element brings the user to a different page, and the POST request is not going all the way through. If i step through it slowly the script gets ran, however.
How can i make the page wait until the script has run until it navigates away from the page? or is there a different issue here? Sort of new to AJAX
$('.ad-link').on('click', function() {
$.get('http://easyuniv.com/php/clickPP.php?id='+$(this).attr('id'));
});
and then clickPP.php is just a simple SQL query that i have verified to work.
Thanks
You can use a callback for this, like so:
$('.ad-link').on('click', function(e) {
e.preventDefault();
var url_to_redirect = $(this).attr('href');
$.get(
'http://easyuniv.com/php/clickPP.php?id='+$(this).attr('id'),
{},
function(return_data){ // callback function, wait till request is finished
// use the return_data if you need it
location.href = url_to_redirect; // redirect the user
}
);
});

setInterval not working properly

I have been searching all over the internet tonight, saw a lot of "solutions" but not working for me unfortunately. So I will try to get different answer of what I am seeing here on stack and elsewhere and hoping I will find one which will work...
My page has the following javascript bit:
logbook = setInterval(function () {
$.getJSON("php/log.php", function(data) {
$.each(data.posts, function(i,data) {
$('#logspan').replaceWith(data.logupdate);
});
});
}, 5000);
When I run the page, it works, but only ONE time and then it stops the interval completely (this is in Chrome and Firefox) and basically gives up.
This is weird, because there is yet another script which is running as follows and is doing its job perfectly:
var timer;
function startCount() {
timer = setInterval(count,1000);
}
function count() {
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML);
el.innerHTML = currentNumber+1;
}
I already tried to see if the first script works if I turned the second one off, but it is still no go. So, how can I ever make the first (JSON) script work? It is way past my bedtime thanks to this problem and I haven't gotten any step further!! pulls hair
Any suggestions / hints / tips are appreciated...
EDIT: Ok, I found something peculiar, when I replace the "replaceWith" and use "appendTo" it seems to update the #logspan just fine, but obviously I do not want to spam my own webpage. Maybe the problem lies somewhere else?
Agreed.
Use a different variable name than data in your $.each() function body, as you may be inadvertently referring to the data in the $.getJSON() function body
Since you're iterating over the posts returned in the JSON call, empty out the body of #logspan only once, then append the content of each post sequentially to #logspan.
var logbookTimer = setInterval(function () {
$.getJSON("php/log.php", function(data) {
// Empty out the body of the log
$('#logspan').empty();
// Add some content for each retrieved post
$.each(data.posts, function(i,d) {
$('<div>').html(d.logupdate).appendTo($('#logspan'));
});
});
},5000);
try this way
var logbook = function () {
$.getJSON("php/log.php", function(data) {
$.each(data.posts, function(i,data) {
$('#logspan').replaceWith(data.logupdate);
});
});
};
setInterval(logbook, 1000);

Categories