Auto update frontend AJAX script modification with jQuery - javascript

I have the script below that works great but want to modify it for a desired effect. Right now it only works on initial page load. But how can I edit it to make it auto-feed every 30 seconds or so?
$.ajax({
type: "GET",
url: "Administration/data/people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" class="mybutton" name="users" onclick="showUser(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
EDIT: 1/24/14 3:55 AM
I added the interval function, but now it is on an infinite loop and is not overwriting, but instead adding over and over again.
$(document).ready(function(){
setInterval(updateMe,1000);
function updateMe(){
$.ajax({
type: "GET",
url: "Administration/data/people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" class="mybutton" name="users" onclick="showUser(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
}
});

Use the setInterval function to call the function every 30000 miliseconds.

have a look at javascript setInterval ()
Plenty of examples on the web but the basic syntax is
var intervalID = window.setInterval(code, delay);

Related

Javascript functions keeps executing even after updating the DIV

I have certain content that gets updated using ajax on that Id, for example, let's suppose I have a complete main page and inside the body I have this code:
<div id="content">
<button onclick="update1()"></button>
<button onclick="update2()"></button>
</div>
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>
<script src="js/script.js"></script>
And the index.html of Page1 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page1"> .....</div>
And the index.html of Page2 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page2"> .....</div>
And the script.js contains some code like this:
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
});
What I want to do is when the button is pressed to call Ajax that gets the index.html from Page1 and puts it inside the id content, run a script.js this script only executes when the id page1 exists, I have found this trick from this answer, by using an if with jQuery for example if($('#page1').length ){my sj code} the javascript code runs only when that id exists, but unfortunately when I click the button to get the Page2 that has another id page2 that code keeps running, is there a way to stop this js code when that div is updated???
The function is not stopping because the interval will not stop firing unless you clear it, using clearInterval() function.
just put all your JS code in one file like this:
$(document).ready(function() {
var the_interval = setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
function stopTheInterval(){
clearInterval(the_interval);
}
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
stopTheInterval(); // we stop the first interval
}
});
}});
what I did here is saved the interval number in a variable, and created a new function to clear it.
next, all I did was put my new function in your update2() function, so once I get the data back I clear the interval and stop the repeating function.
script.js
dont use setInterval.
function some_function(){
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}
And call above function in update1.because you want it only when page1 updated
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
some_function() // call function here
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>
Try using update1().stop()
in starting of update2 function

jQuery is not getting applied

I am working on notification system and loading html notification body from database to views which populate as follows:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and applying jQuery function which I already defined on same page is like this:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
});
So when user click on button it's not work even not showing alert.
But things gets more interesting when I inject above jquery function from chrome console while view is loaded and button start working fine and shows alert too!
I am not getting the point which not letting things work!
It's because your acceptingRequest function is visible only inside anonymous jQuery(document).ready callback.
So when you click the button acceptingRequest is not visible.
Solutions keeping jQuery(document).ready(function() {})
To solve this bind the handler inside the callback using $('button.acceptinvite').on('click',acceptingRequest)
or use an anonymous callback (something like this):
$('button.acceptinvite').on('click',function(){
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
});
In both cases remove onclick="acceptingRequest();" since it's no longer needed.
Another option is to make acceptingRequest visible outside using a global variable (it's not a good practice anyway):
acceptingRequest = function () {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
Now acceptingRequest is visible outside jQuery().ready and you can do onclick="acceptingRequest();"
Solutions without jQuery(document).ready(function() {})
If you don't need the DOM to be completely loaded (like in this case) you can remove
jQuery(document).ready(function() {}) and just write your function from in head, so they are visible to the button.
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
</script>
Let me know if this was useful.
I think you are defining the function acceptingRequest() on document ready, but you are not really calling it. Try adding:
acceptingRequest();
just after the definition of the acceptingRequest() function. The result would be:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
acceptingRequest();
});
It is because this string
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
will be proceded by the browser earlier than the definition of your acceptingRequest function. 'acceptingRequest' in your code will be defined asynchronously when document ready fired. So browser can't assign it with the click listener. Try to put your script exactly before </body>(and after jQuery script) and without jQuery(document).ready
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
</script>
</body>
Function defined in ready state can be used in it's own scope.So you can use acceptingRequest() method in ready state.
in my view below code is bestpractice in event binding:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" id="acceptInviteButton" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and in ready state:
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
$("#acceptInviteButton").on("click",acceptingRequest);
});

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>

Getting variable from success function ajax

I have a variable in the success part of ajax and I want to reuse it in another function (which executed every 3 seconds), I tried to declare it global, but it does not work; Tdata is not known.
I know that $.ajax is an asynchronous function and I saw some posts similar to mine but it did not help me.
Help me please. Thank you.
This is a part of my code:
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
window.setInterval(function() {
$(window).load(function() {
$.each(Tdata, function(variable) {
/////////////
});
});
}, 3000);
</script>
Why not wait until the AJAX request has successfully returned data before starting your interval? Since any executions of the interval's function aren't going to do anything (due to no data) before that point waiting isn't going to change the way the page would function in any way.
$.ajax({
method: "GET",
url: "load-data.php",
dataType: "json"
success: function(data) {
var Tdata = data;
// do some more stuff with the response of the AJAX request
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
// do something with variable
});
}, 3000);
}
});
Note that I've removed the binding of the load event to the window every time the interval runs because doing so really doesn't seem to make any sense. I've also added a dataType property with a value of json to the options object passed to $.ajax() so you don't have to parse the response as JSON yourself.
try this,
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
$(window).load(function() {
window.setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
});
</script>
Function that uses the variable from AJAX call should be called from inside AJAX success, like this:
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
}
is callback tdataAjax function ajax success method run; #param parseJSON
var tdataAjax = function(callback) {
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
var Tdata=jQuery.parseJSON(data);
setInterval(function() {
callback(Tdata);
}, 3000);
}
});
};
is Callback function #param data in tdataAjax function
tdataAjax(function(data) {
$.each(data, function(variable) {
// code
});
});
tdataAjax ++ :)
tdataAjax(function(data) {
$.each(data, function(variable) {
// cla bla
});
});

Jquery method executed several time

I'm trying to implement simple Comet chat example and for this I implemented Long polling which calls itself recursively every 30 seconds.
When pressing on button I want another ajax request to send new data on Server using POST.
For now I just put alert to this function to trigger click event
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var polling = function poll(){
$("#postMessage").click(function () {
alert("request");
});
$.ajax({ dataType: 'json',url: "CometServlet", success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
}, complete: poll, timeout: 30000 });
}
$(document).ready(polling)
</script>
And my HTML is like this:
<div>
<input type="button" id="postMessage" value="post Message">
</div>
<div id ="message" name="message"></div>
When I click on button my alert is shown several times. Why? How can I solve it?
As Dave mentions, that's not what the timeout option is for. Try something using setTimeout instead. Also, you're mixing your polling logic and your click handler (I think). Here's how you would separate them:
function poll() {
$.ajax({
dataType: 'json',
url: "CometServlet",
success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
},
complete: function () {
setTimeout(poll, 30000);
}
});
}
$(document).ready(function () {
$("#postMessage").click(function () {
alert("request");
});
poll();
});
Example: http://jsfiddle.net/VyGTh/
In your code after every Ajax call you re-bind click event to #postMessage and that's why you had couple of alert messages. You need to bind click only once in page load. You can fix it by doing something like:
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
var polling = function poll(){
$.ajax({ dataType: 'json',url: "CometServlet",
success: function(data){
if (data !=null){
$('#message').append(data.sender+" : " + data.message+"<br />");
}
},
complete: poll,
timeout: 30000
});
}
$(document).ready(function(){
// Now Click only binds one time
$("#postMessage").click(function () {
alert("request");
});
polling();
});
</script>

Categories