jQuery - Call ajax every 10 seconds
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/
At startup, run AJAX request every 10 seconds
You're not properly closing your functions, and to run the function every ten seconds, you could make it recursive, calling it again from the done()
callback, or you could use an interval
(function newjobs() {
var inputjob = $.ajax({
url: "create_new_job.php"
});
inputjob.done(function(data) {
alert('Job added!');
setTimeout(newjobs, 10000); // recursion
});
// ^^ missing closing
inputjob.fail(function() {
alert('Job not added....');
});
})();
How to start ajax request periodically use jquery every 10 second after click button?
You can set a empty variable and then assign a setInterval
function to it on the click event.
In this example, just replace the console.log('Run Every 10 Seconds');
with executeQuery();
This can then be cleared using clearInterval(timeoutFunction)
on another buttons click event.
For example:
$(function () {
var timeoutFunction;
$("#btnStart").click(function () {
timeoutFunction = setInterval(function(){
//executeQuery();
console.log('Run Every 10 Seconds');
}, 10000);
});
$("#btnStop").click(function () {
clearInterval(timeoutFunction);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnStart">Start</button>
<button id="btnStop">Stop</button>
calling ajax every 10 seconds using setinterval
It means an XHR Request every 10 seconds to the server, which is not a bad practice, since it is a core requirement. However, there can be a solution to it by applying the mechanism of Caching Data on Server Side, to reduce direct hits to the Database, and only perform hits in case there are any CRUD Operations applied on Database.
Execute an Ajax request every second
Something you might want to consider is Server Sent Events (SSE's)
This is an HTML5 technology whereby Javascript will "long-poll" a server endpoint (your PHP file) to see if any changes have occurred. Long-polling is basically where JS (I'm not sure if it uses Ajax or another technology) sends a request every second to the endpoint
You can try it like this:
#/your_js
var evtSource = new EventSource("increment.php");
evtSource.onmessage = function(e) {
$('#hidden').val(e.data);
}
To send the data, you can make an ajax call which will send the updated JSON object to the server, like you have:
$(document).on("click", ".your_object", function(data) {
$.ajax({
type: 'POST',
url: 'increment.php',
data: $(this).serialize(),
dataType: 'json'
});
});
This will only open an Ajax request when you perform an event, and your app will be "listening" for the response every second. As you are aware, Ajax long-polling is super resource-intensive, so it will be better to look at web-socket stuff if you want true "real-time" technology, but either way, this will be a much more efficient system than just using plain ajax for everything
A caveat here -- you'll have to change your increment.php
to handle the different response types
run a ajax call result on load and after 5 seconds
I am not sure what's stopping you from following the other page. You can just wrap anything that you wanna run after 5 seconds inside:
window.setTimeout(function () {
// Stuff to run after 5 seconds.
}, 5000 );
So your code will be:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// Instead of button click, change this.
setTimeout(function() {
jQuery.support.cors = true;
$.ajax({
crossDomain: true,
async: true,
type: "POST",
url: "http://san.gotdns.ch:8025/json",
success: function(result) {
$("#div1").html(result);
},
jsonpCallback: 'callbackFnc',
failure: function() {},
complete: function(data) {
$("#div2").html("Success : ");
if (data.readyState == '4' && data.status == '200') {
//document.write("Success : ");
//document.write(data);
} else {
document.writeln("Failed");
}
}
});
}, 5000);
});
</script>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
<div id="div2">
<h2>Complete</h2>
</div>
</body>
</html>
You had some extra unnecessary tags. I removed them. Please don't use document.write
function, as it is dangerous. Instead, use an element and update its contents. The following code:
if (data.readyState == '4' && data.status == '200') {
//document.write("Success : ");
//document.write(data);
} else {
document.writeln("Failed");
}
Should be replaced with:
if (data.readyState == '4' && data.status == '200') {
$("#div2").append(data);
} else {
$("#div2").append("An Error Occurred");
}
Related Topics
Access Controller Method from Another Controller in Laravel 5
Create Ini File, Write Values in PHP
How to Run a PHP Script Inside a HTML File
Use PHP to Set Cron Jobs in Windows
Why Is Register_Globals So Bad
How to Embed Youtube Videos in PHP
How to Use Sha1 Encryption Instead of Bcrypt in Laravel 4
Debugging PHP Mail() And/Or PHPmailer
How to Add Variation Stock Status to Woocommerce Product Variation Dropdown
How to Import a .SQL File in MySQL Database Using PHP
Jquery - Call Ajax Every 10 Seconds
Get in Woocommerce Cart the Product Id of a Cart Item
How to Get the Real Url After File_Get_Contents If Redirection Happens
Shortcomings of MySQL_Real_Escape_String