Execute function from another script in a script - php

I have two scripts running in the body of my page. When "a" is pressed on the keyboard, another script runs. How can I add some delay and then trigger the first script again? I have tried with the code below, it does not work. Prefferably, I would like to cancel the first timeout in the beginning of the second script as well.
<script id="source" language="javascript" type="text/javascript">
$(function (){
function reloading(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( vname +":" ).fadeIn("slow");
setTimeout(function(){
reloading();
}, 60000);
}
});
}
reloading();
});
</script>
<script>
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Message</i><br> <br>" +_val2 +" additional." ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
});
setTimeout("reloading()",1000);
</script>

You have to put reloaded() in global scope to access it from another script. Right now it is inside an anonymous function (a bit of a hack to mitigate global scope pollution), but for your case if it isn't feasible to merge the two scripts into one, you are going to have to pollute global scope.
If it is a one-off function, give it a unique prefix or something:
myApp_reloaded();
If you have a bunch of functions that need to be in the global scope, create a wrapper object. There are a bunch of different patterns you can use, I prefer this...
function MyApp() {
}
MyApp.prototype.reloaded = function () {
// reload func body here
}
var myApp = new MyApp();
now you can access the methods globally:
myApp.reloaded();

Quick hack until someone comes with a more elegant one that does not pollute the global scope
<script id="source" language="javascript" type="text/javascript">
var tId;
function reloading(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data) {
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( vname +":" ).fadeIn("slow");
clearTimeout(tId);
tId=setTimeout(function(){ reloading();}, 60000);
}
});
}
$(function (){
reloading();
});
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Message</i><br> <br>" +_val2 +" additional." ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(tId);
tId = setTimeout(function() { reloading()},1000);
});
</script>

Related

How to use jQuery variable in SQL statement?

myscript.js
$(".tablestyleorchideeaanbod").on("click", function() {
var value = $(this).find('tr:first td:first').html();
lastClickedValue = value;
console.log( value );
var test = lastClickedValue
});
So when got clicked on my table with class tablestyleorchideeaanbod, var test will get a value. Let's say for example: hi;
So, var test = hi
Now I need to use this variable in my homepage, index.php.
In index.php I want to use the variable; var test, to use in a MYSQL Query.
For example:
SELECT * FROM thisismytable WHERE rowname = var test
How to achieve this?
$(".tablestyleorchideeaanbod").on("click", function() {
var value = $(this).find('tr:first td:first').html();
lastClickedValue = value;
console.log( value );
var test = lastClickedValue
});
Then you most use ajax to send the data to de server
$(".tablestyleorchideeaanbod").on("click", function() {
var value = $(this).find('tr:first td:first').html();
lastClickedValue = value;
console.log( value );
var test = lastClickedValue;
$.ajax({
url: 'data.php',
type: "POST",
/*contentType: "application/json; charset=utf-8",*/
data: {val : test },
dataType: 'json',
success: function (data) {
console.log(data);
}
});
});
php script data.php
<?php
$val = $_POST['val'];
// do whatever you want here .....
//insert sql or select
?>

Auto Refresh JS Array if content changes?

I have this javascript function which serves an AJAX request to an external PHP Script, I want this to auto update a HTML <div> if the new check is different from the old check.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
This currently sucessfully returns and updates the div with the content from the array, the problem is, since adding the window.setInterval(function() line, it will server the connection every 5 seconds and update the <div> with duplicate data.. when all I want, it for it to echo the new data (if there is a ny)
Here is my other PHP script:
$STD = new mysqli ("localhost", "root", "hidden", "ajaxrequests");
$array = array();
$Query = $STD->prepare ("SELECT * FROM ajaxdata");
$Query->execute();
$Query->bind_result($ID, $Name, $Password);
while ($Query->fetch())
{
$array[] = array ( $ID, $Name, $Password);
}
echo json_encode($array);
Just add a call to empty() before your loop.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
Of course if your data size is large, this would not be very optimal. I would actually suggest having the PHP server send a timestamp value with it's response. You could then pass this back in subsequent AJAX requests and have the server determine if there are actually updates to deliver since that last timestamp. You could then have the server only send those updated records, which you could append/update similar to how you are already doing it.

Two looping JS functions conflicting with each other

so I've got these two sets of JavaScript functions that continuously pole my server and, if the database has been updated, the functions do something. Both sets of functions have nothing to do with each other; they're only relationship is that they happen at the same time. Yet for some reason one function is conflicting with the other. Here's what my code looks like:
<!DOCTYPE html>
<html>
<head>
<title>Stage</title>
<link href="stage.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
///////////////////// FUNCTION SET 1
function loadThumbnail(){
$.ajax({
url: 'process_stage_show.php',
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data){
var idCurrent = data[0];
var idVideo = data[1];
var idSession = data[2];
var state = data[4];
if (state == 1) {
$('#tv').html('<img src="http://i.ytimg.com/vi/'+ idVideo +'/hqdefault.jpg" width ="800" height="533"/>');
setTimeout(function(){timedCount2(idCurrent);},1000);
}
else {
setTimeout(function(){timedCount2(idCurrent);},1000);
}
}
});
}
function timedCount2(idCurrent){
$.ajax({
url: 'process_stage_show.php',
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data) {
var idNew = data[0];
var idVideo = data[1];
var idSession = data[2];
var state = data[4];
if (!(idCurrent == idNew)) {
window.location.reload();
}
else{
setTimeout(function(){timedCount2(idCurrent);},1000);
}
}
});
}
///////////////////// FUNCTION SET 2
function loadStage(){
$.ajax({
url: 'process_stage_play.php',
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data){
var idVideo = data[0];
var idCurrent = data[1];
var idSession = data[2];
var state = data[4];
if (state == 2) {
//alert("State equal to 2. Do nothing.");
setTimeout(function(){timedCount(idCurrent);},1000);
}
else if (state == 1) {
//alert("State equal to 1. Open window.");
popupwindow = window.open ("http://www.youtube.com/watch_popup?v="+ idVideo);
setTimeout(function(){timedCount(idCurrent);},1000);
}
else if (state == 0) {
//alert("State equal to 0. Close window.");
popupwindow.close();
setTimeout(function(){timedCount(idCurrent);},1000);
}
}
});
}
function timedCount(idCurrent){
$.ajax({
url: 'process_stage_play.php'
data: 'value=<?php echo $_GET["session"]; ?>',
dataType: 'json',
success: function(data) {
var idVideo = data[0];
var idNew = data[1];
var idSession = data[2];
var state = data[4];
if (idCurrent == idNew) {
setTimeout(function(){timedCount(idCurrent);},1000);
}
else{
//alert("ID has changed. Re-load stage.");
loadStage();
}
}
});
}
</script>
</head>
<body onload="loadStage(); loadThumbnail();">
<div id="tv"></div>
</body>
</html>
I'm don't want to go into too much detail about what these sets of functions do (unless requested) as I don't want this post to be REALLY long. But the problem is both these sets of functions work fine by themselves but for some reason if you run them at the same time, the second function set keeps saying popupwindow is not defined when state is equal to 0.
Which makes no sense! Why would the first function set cause that to happen? :(
Well one of the things that the first function sometimes does is reload the window. As soon as that happens, the global variable "popupwindow" will vanish.
It might work to have code in the popped-up window check its "opener" window periodically to see whether it should close itself.
Do I understand correctly that these functions both open a popup window?
If so, some browsers do only open one popup per webpage and if another popup is opened, the old one will be refreshed with the new url.
Thus, one of these functions could lose "its" popup window which would explain your problem.

First load issue, setInterval

Using setInterval to reload a script - it does not reload before the first amount of time has passed (i.e: waits 120000 msec before actually displaying content). Is there a better way to do this?
<script id="source" language="javascript" type="text/javascript">
setInterval( "reloading();", 120000 );
$(function () {
reloading = function(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) + 1;
_val2 = val2;
$('#output').hide().html(timestamp +message ).fadeIn("slow");
$('#username').hide().html( vname ).fadeIn("slow");
}
});
}});
</script>
1 you are declaring reloading as a global variable and accessing it without knowing if your function is ready, that's not a good idea. If by any chance your site takes more than 2 minutes to load that will never work.
If you want to queue up your re-loads to process once every 2 minutes and run the first time without waiting, you can do it like this:
$(function(){
function reloading(){
//whatever you want to process goes here
(...)
setTimeout(function(){
reloading();
}, 120000);
}
reloading();
});
this will load your code once and then wait 12 seconds to run it again, and so on...

execute php file in jquery after a time delay in sequence

i have one jquery function which i need to work in following way
1. call a php file
2. log the values return by php file
3. have time delay
again repeat the above process for number of time
for this purpose i write bellow jquery and php file
<script type="text/javascript">
$(document).ready(function() {
listsValues="1,10,20";
n=0;
msgids = listsValues.split(',');
$.each(msgids, function() {
html="TEST MESSAGE";
n++;
setTimeout(function() {
$.ajax({
type: "POST",
url: "test1.php",
cache:false,
data:"id="+ msgids[n],
dataType:'json',
success: function(json)
{
var foo = json.foo;
uemail = foo.split(',');
console.log(uemail)
}
});
}, 1000);
});
});
</script>
and here is test1.php
<?php
$id=$_POST['id'];
$val="";
for($i=1;$i<=$id;$i++) {
$val.=$i;
}
$return["foo"] =$val;
print stripslashes(json_encode($return));
?>
but this is not working as a way i want, when i execute this script
i can see in firebug test1.php file executes (called) for 3times and after that values are written in console
as i said waht i want was
1. execute test1.php file
2. write value in console
3. give delay
then repeat
Thanks
I think you are searching something like this:
<script type="text/javascript">
function request(n) {
$.ajax({
type: "POST",
url: "test1.php",
cache:false,
data:"id="+ msgids[n],
dataType:'json',
success: function(json)
{
var foo = json.foo;
var uemail = foo.split(',');
console.log(uemail);
setTimeout(
function() {
request(n);
}
, 1000
);
}
});
}
$(document).ready(function() {
var listsValues="1,10,20";
var n=0;
var msgids = listsValues.split(',');
$.each(msgids, function() {
var html="TEST MESSAGE";
n++;
request(n);
});
});
</script>

Categories