Execute an Ajax request every second
ajax, jquery
Solution
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
Problem
I have an ajax call being made to a php file. I am receiving results. Now I am investigating if it is possible to have the ajax request automatically perform every 1 second. I am posting the results into input field called `hidden`. How can I execute the ajax call every three seconds without having to call the function? ``` $.ajax({ type: 'POST', url: 'increment.php', data: $(this).serialize(), dataType: 'json', success: function (data) { $('#hidden').val(data);// first set the value } }); ```