I have a question, I'm using uploadify, and every time when a file finishes to upload, the script runs a code which is located in the onComplete statement, and the code from the onComplete statement it's an ajax call to a page, let's call it X , how can I know when the script access the page X for the first time?
Although I'm not familiar with uploadify, if you set a variable in the global scope (outside the onComplete), I'll call it var hasBeenCalled, set it to false at the page load.
When onComplete is called, do:
if (hasBeenCalled)
{
// not the first time
}
else
{
//first time
hasBeenCalled = true;
}
Hope it helps
try with this:
var myFirstEvent = false;
var myFunOnComplete = function()
{
if (!myFirstEvent)
{
// code for fist instance
}
// set finish the first instance
myFirstEvent = true;
// code for ajax call
callAjax();
}
jQuery('#fInput').uploadify({
...
'onComplete': myFunOnComplete,
...
});
Related
I have an AJAX call on a loop, set to 1000 miliseconds.
The PHP script is simple, it just puts some information (a number) into a session variable. Yesterday I've recived an email from my hosting provider (HostGator), which states that I've been using 75%+ of CPU on shared hosting. After looking the logs, I've found that the problem is in that AJAX call. Here is the code:
PHP (ajax.session.php):
<?php
session_start();
$movieID_e = $_POST['id'];
$state = trim(strtolower($_POST['status']));
if ($state == 'playing') {
if (empty($_SESSION[$movieID_e])) {
$_SESSION[$movieID_e] = 1;
}
else {
$_SESSION[$movieID_e]++;
}
}
echo $_SESSION[$movieID_e];
?>
Javascript:
function interval(func,wait,times){
var interv = function(w, t){
return function(){
if(typeof t === "undefined" || t-- > 0){
setTimeout(interv, w);
try{
func.call(null);
}
catch(e){
t = 0;
throw e.toString();
}
}
};
}(wait,times);
setTimeout(interv, wait);
};
var watched = (function() {
var executed = false;
return function () {
$.post('ajax.session.php',{id:'<?php echo encrypt($id); ?>',status:'none'},function(result) {
if (result == 1000) {
if (!executed) {
executed = true;
var highlightad = introJs();
highlightad.setOptions({
steps: [
{
element: '#advertisment1',
intro: 'test',
position: 'bottom'
},
{
element: '#advertisment2',
intro: 'test2',
position: 'left'
}
]
});
highlightad.start();
}
}
else {
executed = false;
return false;
}
});
};
})();
interval(function(){watched()},1000,3000);
Explanation of JS:
function interval() -> Alternative to setInterval(), taken from thecodeship.com
function watched() -> AJAX request to file ajax.session.php shown above. If the result is 1000 then it highlights a part of a website using Intro.JS.
interval(function(){watched()},1000,3000); -> repeat watched() every 1000ms, max. number of repetitions is 3000 times.
Note that PHP script (ajax.session.php) is also called by AJAX from another script, also with function interval() every 1000ms.
I am using the interval() every second to count the number of seconds that past in a video player.
Do you have any suggestions on how to prevent CPU overload with the following script?
What server stats do you have? I think the problem is, that you have too much traffic for a weak server. Also of course 1second intervals for ajax calls are tooo often. Check your console, you will see that most of them will get timedout.
Sessions will be server side, so it will use servers resources. If you would convert your script to cookies, then the data will be stored in users browser. Also you could use $.cookie jQuery plugin to easily read the cookies via JS, so no need to ajax call.
Also, I would not recommend to use sessions at all, unless making some highly secure login system. I would recommend to use memcache to store temporary data.
Also, I'm pretty sure your JS could use optimization, because on first look I didn't see that you would check if one ajax call is active already. So it wouldn't ajax call before the last call was finished. Otherwise you can imagine the pointless ajax calls going to the server, where 50% of them get timedout.
I am making a function and i have added if statement at the top of it. I want to change variable value when user scroll. If the user scroll if statement check variable value and run the function inside if statement
var usrscrolled = 'notscroll';
function scrolled() {
//do by scroll start
usrscrolled = 'scroll';
}
$(window).on('scroll', scrolled);
if (usrscrolled = 'notscroll') {
}
this code works but onscroll variable dont change and if statement runs on scroll
= is used to assign value, to compare you need to use ==, so change
if (usrscrolled = 'notscroll') {
to
if (usrscrolled == 'notscroll') {
I think you're missing that the if statement is not running after there's been a scroll:
// Unnecessary if; usrscrolled will always be 'notscroll' here
// This does _not_ run on scroll
if (usrscrolled === 'notscroll') {
}
If you want that, you need to wrap it in the on handler, i.e. like this:
function scrolled() {
if (usrscrolled === 'notscroll') {
// Do something before the variable is set to 'scroll'
// I.e. first time user scrolls
}
usrscrolled = 'scroll';
}
$(window).on('scroll', scrolled);
i have added this code
var delay = 1000;
var timeout = null;
$(window).bind('scroll', function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
usrscrolled = 'notscroll';
}, delay);
});
It changes variable value after 1 second when user stops scrolling. And it works for me
I'm starting my adventure with js and jQuery and I can't understand why my function pokaz_czas() is not executed when I reload the page.
I use a script in a php file (wpis.php), which I'm including in another php file (index.php?page=wpis). I want my function to execute when I reload the page (index.php?...)
Javascript Code:
function zero(element)
{ //1
if (element < 10) return element = "0" + element;
return element;
}
function pokaz_czas()
{
var czas = new Date();
var data = czas.getFullYear()+"-"+zero((czas.getMonth()+1))+"-"+zero(czas.getDate());
var time = zero(czas.getHours())+":"+zero(czas.getMinutes());
$('#data').val(data);
$('#time').val(time);
}
$(document).ready(pokaz_czas());
$(document).ready
(
function()
{
$('#data').change
(
function()
{
alert($(this).val());
}
);
}
);
By the way, if I do...
...
var time = zero(czas.getHours())+":"+zero(czas.getMinutes());
$('#data').val(data);
$('#time').val(time);
setTimeout("pokaz_czas()",1000)
}
...then the function is executing (but it does so every second, and I want to execute it only once).
Sorry for my English, it' s my first post here ;)
Thank you in advance.
Yes , definitely try this way:
$(document).ready(pokaz_czas);
It means you don't want to fire pokaz_czas immediately , only when your DOM is ready
While developing a web app where I'm making great use of javascript php and ajax.
I want to call
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
to build my terminal and call feed_terminal() which has its own setTimeout() recursion call
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
a php file that does nothing more that
exec("sudo /usr/bin/./init-raid-drives-web.sh");
and this is where I fail. This next line is not executed until after the exec() in the php file returns to the php file and the php file returns to the javascript. Not that it matters, but I am pretty sure it did not used to be this way, as originally the bash script would execute over a time period of 2 minutes and the javascript would successfully be updating the html with feed_terminal. this is not the case anymore.
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart.You must re-login to FDAS-Web.');
Below is a bunch of code for your questions
Ultimately my question is, how can I run javascript DURING the ajax call?
Or maybe my question should be, how can I have edit_initRaid return an xmldoc, without waiting for the exec() to return, or how can i have the exec() return even without the script completing?
function initRaidArray(){
if (document.getElementById('initRaid_doubleCheck')){
if (document.getElementById('initRaidHideButtonSpot'))
document.getElementById('initRaidHideButtonSpot').innerHTML = '';
var spot=document.getElementById('initRaid_doubleCheck');
spot.innerHTML='';
spot.innerHTML='This may take a few moments. Please wait.';
}
display_terminal('feedback_viewer','logs/init-raid-log.txt','Init-Raid');
var url='../edit_initRaid.php';
status_text('Initializing raid-array. Please wait a moment...');
var xmldoc=ajaxPHP2(url,2);
alert("javascript has returned from ajax call");
if (xmldoc) {
status_text('Raid-array initialized successfully. System will now restart. You must re-login to FDAS-Web.');
}
}
where display_terminal() does two things, builds a table and appends it to the page, and calls feed_terminal(logfile,bigDiv,0)
function feed_terminal(logFile,bigD,lap){
// AJAX
bigD.innerHTML = '';
var url='../view_xml_text.php';
/*
* lap(0)=clear file , lap(1)=do not clear file
*/
url+='?logFile='+logFile+'&lap='+lap;
var XMLdoc=ajaxPHP2(url,2);
var xmlrows = XMLdoc.getElementsByTagName("line");
alert("xmlrows.length=="+xmlrows.length);
// empty file
if (xmlrows.length==0){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML='...';
d.appendChild(s);
bigD.appendChild(d);
} else {
// Parse XML
for (var i=0;i<xmlrows.length;i++){
if (xmlrows[i].childNodes[0]){
if (xmlrows[i].childNodes[0].nodeValue){
var d = document.createElement('div');
var s = document.createElement('span');
s.innerHTML=xmlrows[i].childNodes[0].nodeValue;
d.appendChild(s);
bigD.appendChild(d);
}
}
}
}
setTimeout(function(){feed_terminal(logFile,bigD,1)},2000);
}
where the most important item is the setTimeout() call to continue reaching out to the php file which returns xml of the lines in the file, simply.
function ajaxPHP2(url,key)
{
if (window.XMLHttpRequest) {
xml_HTTP=new XMLHttpRequest();
if (xml_HTTP.overrideMimeType) {xml_HTTP.overrideMimeType('text/xml');}
} else { xml_HTTP=new ActiveXObject("Microsoft.xml_HTTP"); }
xml_HTTP.open("GET",url,false);
xml_HTTP.send(null);
if (key){return xml_HTTP.responseXML;}
}
You need to tell Javascript to do your XHR call asynchronously.
Change
xml_HTTP.open("GET",url,false);
to
xml_HTTP.open("GET",url,true);
But first, you'll need to tell it to do something when the request completes (a callback):
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
One recommendation: XHR is a pain. It would be a lot easier to use something like jQuery's $.ajax()
You need to set your ajax call to be asynchronous. In the ajaxPHP2 function, the line xml_HTTP.open("GET", url, false); is what is causing the page to pause. The false parameter is telling the ajax call to make everything else wait for it. Change the false to true so it looks like this:
xml_HTTP.open("GET", url, true);
You may also need to attach a function to the onreadystatechange property so that when the ajax call returns it knows what to do. See these links for more information.
How can we call Php functions with in the JavaScript If-else condition.
For Example,
if (top == self) {
// not in any kind of frame
} else {
// in a frame
// calling php function
}
</script>
Here, PHP exit() function calling for both if and else conditions. I need to call that function for only in else part.
Please advise me.
Thanks.
Prabhu
Technically not possible. However you can make an AJAX call to a PHP page and get the values returned by it.
PHP (test.php):
<?php
$x = 10;
$y = 20;
$val = $y / $x;
echo $val;
?>
Javascript (jQuery):
$(document).ready(function() {
$.ajax({url: 'test.php',
type: 'POST',
success: function(data){
//takes the value returned by test.php and
//puts it directly into the element with
//id = someElement
$('#someElement').html(data);
}
});
As far as calling exit(); and making the page that holds the JavaScript stop processing, you just can't unless you control the logic on that same page in PHP and call exit(); from there.
Do not try to mix javascript with php.
If you want to stop the page from loading you could also redirect the page to an other (php) page where you simply put exit();
If this javascript is in a function just use : return; or return false;