jQuery - Async Ajax requests? - javascript

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()});

Related

PHP+AJAX refresh div not correctly working [duplicate]

I have a mysql feedback database constructed like this:
name | location | feedback
Ryan | England | great support
Obviously there's more entries than that. I am trying to build a feedback div, where it displays a new feedback item every 10 seconds via ajax.
So I have constructed this:
$(document).ready(function(){
new get_fb();
});
function get_fb(){
var feedback = $.ajax({//Ajax
type: "POST",
url: "feedback.php",
async: false
}).responseText;//end of ajax
$('div.feedback-box').html(feedback).delay(10000).queue(function() {
new get_fb();
});
}
And here's my PHP file:
$result = mysql_query("SELECT * FROM feedback ORDER BY RAND() LIMIT 0,1");
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
$location = $row['location'];
$feedback = $row['feedback'];
echo "
<p>Name: $name, Location: $location, Feedback: $feedback.</p>
";
}
However, this only shows two. It doesn't keep showing new ones, it purely shows the first then the second and stops.
What am I doing wrong? Thanks :)
Are you going to want to do a setInterval()?
setInterval(function(){get_fb();}, 10000);
Or:
setInterval(get_fb, 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 get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Or use .ajax().complete() if you want it to run regardless of result:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).complete(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
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/
setInterval(function()
{
$.ajax({
type:"post",
url:"myurl.html",
datatype:"html",
success:function(data)
{
//do something with response data
}
});
}, 10000);//time in milliseconds
You could try setInterval() instead:
var i = setInterval(function(){
//Call ajax here
},10000)
This worked for me
setInterval(ajax_query, 10000);
function ajax_query(){
//Call ajax here
}

Updating input field of html form every 5 seconds automatically [duplicate]

I have a mysql feedback database constructed like this:
name | location | feedback
Ryan | England | great support
Obviously there's more entries than that. I am trying to build a feedback div, where it displays a new feedback item every 10 seconds via ajax.
So I have constructed this:
$(document).ready(function(){
new get_fb();
});
function get_fb(){
var feedback = $.ajax({//Ajax
type: "POST",
url: "feedback.php",
async: false
}).responseText;//end of ajax
$('div.feedback-box').html(feedback).delay(10000).queue(function() {
new get_fb();
});
}
And here's my PHP file:
$result = mysql_query("SELECT * FROM feedback ORDER BY RAND() LIMIT 0,1");
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
$location = $row['location'];
$feedback = $row['feedback'];
echo "
<p>Name: $name, Location: $location, Feedback: $feedback.</p>
";
}
However, this only shows two. It doesn't keep showing new ones, it purely shows the first then the second and stops.
What am I doing wrong? Thanks :)
Are you going to want to do a setInterval()?
setInterval(function(){get_fb();}, 10000);
Or:
setInterval(get_fb, 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 get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Or use .ajax().complete() if you want it to run regardless of result:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).complete(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
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/
setInterval(function()
{
$.ajax({
type:"post",
url:"myurl.html",
datatype:"html",
success:function(data)
{
//do something with response data
}
});
}, 10000);//time in milliseconds
You could try setInterval() instead:
var i = setInterval(function(){
//Call ajax here
},10000)
This worked for me
setInterval(ajax_query, 10000);
function ajax_query(){
//Call ajax here
}

jQuery Ajax - sometimes I get a response, sometimes no response?

this is my Ajax function (for polling), wrapped in $(document).ready. Every second, a request should be sent to update.php.
(Note that getParameterByName and arrayIndexExists are my own functions)
(function poll() {
setTimeout(function() {
$.ajax({
url: "../update.php",
method: "POST",
data: {"game": getParameterByName("game")},
dataType: "json",
complete: poll,
success: function(data) {
console.log("Updating");
console.log(data);
}
});
}, 1000);
})();
This is what I have here in update.php:
header('Content-type: application/json');
$game = $_POST["game"];
$returnArray = array();
// do stuff with the data......
echo json_encode($returnArray);
When it works (say 60% of the time), something like this appears in the console every second or so:
But when it doesn't work, nothing appears in the console at all.
Apparently, the request is still being sent, just that there is no response:
I had spent the whole morning yesterday trying to figure out the problem but I don't know what I'm doing wrong and how to get it working 100% of the time. Thanks.

Reload variables every 10 seconds

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");

How to use PHP to send javascript

I posted a more specific question on this yesterday, but I think my problem is more basic than what I initially asked.
I am trying to use PHP to set a setTimeout() with a wait variable from a database, but any script I echo doesn't work, even if it involves no PHP manipulation. Take a look below.
Here is the ajax call
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
And here is the PHP it receives.
echo '<h1>Upload content to start the show</h1>';
echo '<script>
setTimeout(loadContent, 4000);
</script>';
The is showing, so I believe the ajax and the PHP is working properly. The script works properly when I place it inside the javascript file, but the script won't run when it's echoed to the page.
My problem is the javascript I echo doesn't run. How can I use PHP to send javascript to the user? Why is what I wrote not functioning?
UPDATE: I realized that when I echo script, it echoed to the middle of the body and technically is above where the script file is loaded on the bottom of the body. Can I echo to the bottom of the body?
Here is a workaround:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
var myArray = html.split("|");
var message = myArray[0];
var counter = parseInt(myArray[1]); //Minor fix
$("#contentWindow").html(message);
startCounter(counter);
}
});
}
function startCounter(counter){
//counter as the value of 1000 milliseconds are equal to 1 second
setTimeout(loadContent, counter);
}
PHP File
$refreshTimer = 1000; //This is a test
echo "Upload content to start the show|".$refreshTimer; //The message and the counter
If you return just the script portion in your php file you can set the dataType in the .ajax call to 'script' and it will execute the returned javascript (http://api.jquery.com/jquery.ajax/)
So:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
dataType: 'script',
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
Then in your PHP:
echo 'setTimeout(loadContent, 4000);';

Categories