Reload variables every 10 seconds - javascript

Okay here's the problem.
I want to have 6 realtime variables in php (now they are like Divs). The method I use works fine but it's awful (I know). I need better solution.
Now I load 6 diffrent files like this:
<script>
function loadText() {
$.ajax({
url: ("variable1.php"),
cache: false,
success: function(data) {
$("#variable1").html(data);
}
});
} setInterval(loadText, 60000);
</script>
<div id="variable1"></div>
What should I do? Thanks.

Are you going to want to do a setInterval()?
setInterval(function(){loadText();}, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:
function loadText(){
var text = $.ajax({
type: "POST",
url: "variable1.php",
async: false
}).success(function(){
setTimeout(function(){loadText();}, 10000);
}).responseText;
$('#variable1').html(text);
}
Or use .ajax().complete() if you want it to run regardless of result:
function loadText(){
var text = $.ajax({
type: "POST",
url: "variable1.php",
async: false
}).complete(function(){
setTimeout(function(){loadText();}, 10000);
}).responseText;
$('#variable1').html(text);
}
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
http://jsfiddle.net/YXMPn/

You can always have a function you set to run however often you want that has this... It's a much shorter way... If this is what you mean...
$("#variable1").load("variable1.php");

Related

run php script every 10 seconds

I'm trying to use setInterval to execute the php script update.php every 10 seconds and refresh div id = verification. For some reason setInterval is preventing the script from functioning. Any suggestions on where to place\change setInterval would be appreciate as I'm stumped (sorry entry level javascript user here). For clarity I omitted all the non-relevant details, such as vars.
<div id="verification"></div>
<script id="verification" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
var foobar = data[2]; //foobar
$('#verification').html("(<b>" + foobar + "</b>)"); //output to html
}
});
});
setInterval(10000); //every 5 secs
</script>
Suggestions/Steps/Bugs:
Create a separate function to perform ajax request
Call this function on page load to run it when page is loaded
Use setInterval() to call the function every n seconds
id should always be unique. You're now using verification as if for <div> and <script>
You can remove id and language attributes of <script>. Those are not required.
Code:
function update() {
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function (data) {
//on receive of reply
var foobar = data[2]; //foobar
$('#verification').html("(<b>" + foobar + "</b>)"); //output to html
}
});
}
$(document).ready(update); // Call on page load
// ^^^^^^
setInterval(update, 10000); //every 10 secs
// ^^^^^^
setInterval() takes a function (that it should execute) as it's first argument.
Try this:
setInterval(function(){
$.ajax({
url: 'update.php', //php
data: "", //the data "caller=name1&&callee=name2"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
var foobar = data[2]; //foobar
$('#verification').html("(<b>"+foobar+"</b>)"); //output to html
}
});
}, 10000);
you are using setInterval in a wrong way - you can read about it here:
http://www.w3schools.com/js/js_timing.asp
Also please notice that AJAX calls are asynchronous - when program is going forward it doesn't mean that previous AJAX call has ended. You can "wait" for AJAX completition using some jQuery mechanisms like binding ajaxComplete or using when
You are missing the function block:
setInterval(function() {
// to do
}, 5000);
My suggestion is to go for setTimeout as you are running ajax it is not certain that it would complete within 5 seconds. In case if you wana go for it:
var dispatchUpdates = function() {
setTimeout(pullUpdates, 5000);
};
var pullUpdates = function() {
$.ajax({
url: 'update.php',
data: "",
dataType: 'json',
success: function(data) {
var foobar = data[2];
$('#verification').html("(<b>" + foobar + "</b>)");
dispatchUpdates(); // next updates
},
error: function() {
dispatchUpdates(); // retry
}
});
};
$(dispatchUpdates); //page load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Using Two jQuery Ajax Methods in Script

Can you please let me know how I can use two Ajax call in one script and avoid conflicts? For example, I have a script like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'POST',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
</script>
Can you please let me know how I can use both methods in the script? Thanks.
Just close DOM ready with }); at the bottom of your script block and you're all set:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'GET',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
});// <------ YOU'RE MISSING THIS
The requests should work fine. And since you're not posting any data to the URLs I might suggest that you use type:'GET'.
Maybe you want to use the $.when method http://api.jquery.com/jquery.when/
jQuery.when understanding
possibly put one in the callback of the other, I don't understand the problem off the top my head. But if div2 is inside div 1 or something you can control the order in that fashion

jQuery - Async Ajax requests?

I tried to use ajax requests and response async, but it seems not to work.
I'm sending every second ajax request.
The console should print out "DON'T WAIT" every second and "WAIT5" every 5 Seconds (sleep in php).
But what happens is, that "DON'T WAIT" get logged, then the whole site/script waits 5 Seconds and both messages are logged 5 times.
How can I make this async, so "DON'T WAIT" comes really every second and doesn't wait for the other script ?
//Edit:
This is an example.
The idea is later to Execute a code ( not setInterval ) which need 10 seconds to get the done-status. In this time the other setInterval should work as normal and not waiting !
The sleep as sleep(rand(5,10));
Javascript:
function getProductionStatus() {
jQuery.ajax({
url: "report.sessioncall.php",
dataType: "json",
async: true
})
.done(function(data) {
console.log(data);
});
}
function getProductionStatusLong() {
jQuery.ajax({
url: "report.sessioncall1.php",
dataType: "json",
async: true
})
.done(function(data) {
console.log(data);
});
}
window.setInterval(getProductionStatus, 1000);
window.setInterval(getProductionStatusLong, 1000);
PHP:
<?php
session_start();
sleep(5);
$_SESSION["jobs"] = "WAIT5";
$sessionstatus = json_encode($_SESSION["jobs"]);
echo $sessionstatus ;
?>
AND
<?php
session_start();
$_SESSION["jobs"] = "DONT WAIT";
$sessionstatus = json_encode($_SESSION["jobs"]);
echo $sessionstatus ;
?>
The rule
Ajax requests are asynchronous by default. If you don't change this by using $.ajaxSetup({async:false}), there is no need to write async: true in your ajax request.
The reason for this is, that in the most cases, it's bad practice to make synchronous ajax request, because you can worsen your user experience by preventing your browser to react on user input.
Your specific solution
Just change
window.setInterval(getProductionStatusLong, 1000);
to
window.setInterval(getProductionStatusLong, 5000);
I would not trust this to work.
Instead try something like this - it will not run exactly on the second, nothing will, but it may be closer to what you want
var cnt = 0
function getProductionStatus() {
$.ajax({
url: "report.sessioncall.php",
dataType: "json"
})
.done(function(data) {
console.log(data);
cnt++
if (cnt==5) {
getProductionStatusLong()
cnt=0;
}
else {
setTimeout(getProductionStatus, 1000);
}
});
}
function getProductionStatusLong() {
$.ajax({
url: "report.sessioncall1.php",
dataType: "json"
})
.done(function(data) {
console.log(data);
getProductionStatus();
});
}
$(function() {getProductionStatus()});

Reading a file into a string in jQuery/JS

The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.

Run a ajax function to check a json response every 3 seconds

I want to check if my user is updated from another system using javascript.
I need help writing a function which checks a json response. If it is true or false.
The url /user/updatecheck/ has a json response like this: {"updated": "true"} or {"updated": "false"}
<script type="text/javascript">
$(document).ready(function() {
var updated='2013-01-02T10:30:00.000123+02:00'; //user variable from the system, will be empty if the user is not updated
if (!updated){
$('#not-updated').modal('show');
var updatedCheck = window.setInterval(
$.ajax({
url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"}
data: dataString,
dataType: "json",
success: function(data){
if (json.updated == 'true') { //not sure if this is the correct method
window.clearInterval(updatedCheck);
//The user is updated - the page needs a reload
}
} //success
})
, 3000); //Hoping this is the function to check the url every 3 seconds until it returns true
}
});
$(document).ajaxStop(function(){
window.location.reload();
});
</script>
It does not seem to work. Not sure if my ajax function is correct, I only get the modal window if the user is not updated at first, and the page does not reload if the url /user/updatecheck/ returns true.
The way you call jQuery ajax function as part of the setInterval is not proper. Please try placing it within a function,
var updatedCheck = window.setInterval(
function(){$.ajax({
url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"}
data: dataString,
dataType: "json",
success: function(data){
if (json.updated == 'true') { //not sure if this is the correct method
window.clearInterval(updatedCheck);
//The user is updated - the page needs a reload
}
} //success
})}
, 3000);
The data that you will receive from the ajax request is returned via the data parameter of you success callback function, so you can use that. Try to print the data result to the console (i.e. console.log(data);)or alert it (i.e. alert(data);). For instance you may need to call data.updated. I'm not sure if the json variable you are using in the if condition is initialised.

Categories