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.
Related
I have written this code but it didn't work. I have searched so much but those code are not properly work. what should I do? I want to fetch data without refreshing whole page.
I have looked at this other question.
$(document).ready(function() {
$("#pair_form").submit(function(e) {
e.preventDefault();
var devicename = $("#devicename").val();
var id = $("#id").val();
var latitude = $("#latitude").val();
var longitude = $("#longitude").val();
var ignition = $("#ignition").val();
var Arming = $("#Arming").val();
function showData() {
$.ajax({
url: 'http://example.com/ddd/cfg.php',
method: 'get',
dataType: 'text',
success: function(response) {
$('#result').html(response)
}
});
}
});
});
i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.
I have a simple toggle button that the user can use to either subscribe or unsubscribe from a group they belong to. I have 2 forms that get the post and depending on which page the form posts to, the user is subscribed or unsubscribed. Here's my code and I'm looking for a better way to do this. Currently, my user can click to subscribe or unsubscribe but he or she will have to reload the page to change their setting. In other words, it works fine but there's no toggle...users can't click back and forth between subscribe and unsubscribe, as they have to refresh the page and resubmit. I also would love to fix the toggle function. Thanks for any help.
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataString,
success: function(){
$("#subscribe").removeClass("notifications_subsc");
$("#subscribe").addClass("not_subscribed_group");
}
});
});
});
</script>
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#notsubscribed").click(function(){
$.ajax({
type: "POST",
url: "groupnotificationsoff.php",
data: dataString,
success: function(){
$("#notsubscribed").removeClass("not_subscribed_group");
$("#notsubscribed").addClass("notifications_subsc");
}
});
});
});
</script>
There's no need to rely on parsing out the query string when server-side scripting is available. Instead, when the page is initially served, arrange for PHP to write the group_id value into (eg.) a hidden input field, which then becomes available client-side to be read into javascript/jQuery. (Other techniques are available)
It's also a good idea to arrange for your "groupnotifications.php" script to receive a $_POST['action'] instruction to either subscribe or unsubscribe. That way the client-side half of the application exercises control.
With those changes in place, the code will be something like this:
$(function() {
$("#subscribe").click(function(){
var $s = $(this).attr('disabled',true);//disable button until ajax response received to prevent user clicking again
var clss = ['not_subscribed_group','notifications_subsc'];//The two classnames that are to be toggled.
var dataOj = {
owner : $s.closest(".groupContainer").find('.group_id').val(),//relating to element <input class="group_id" type="hidden" value="..." />
action : ($s.hasClass(clss[0])) ? 1 : 0;//Instruction to 1:subscribe or 0:unsubscribe
};
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataObj,
success: function(status) {//status = 1:subscribed or 0:unsubscribed
switch(Number(status)){
case 1:
$s.removeClass(clss[1]).addClass(clss[0]);
break;
case 0:
$s.removeClass(clss[0]).addClass(clss[1]);
break;
default:
//display error message to user
}
}
error: function(){
//display error message to user
}
complete: function(){
$s.attr('disabled',false);
}
});
});
});
untested
Note: The statement $s.closest(".groupContainer").find('.group_id').val() relies on the hidden input element having class="group_id" and allows for multiple groups, each with its own toggle action, on the same page. Just make sure each group is wrapped in an element (eg div or td) with class="groupContainer".
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>
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>