Repeat the function for every 1 min? - javascript

i am calling a function with parameters from onclick method what i want to do is i want this function to repeat every 1 min here is html code:
I am calling a function on everyclick with some parameter as id
The id fetches the the lat longs,and it is plotted in map ,i have done everything working except that i get the data keep recieving from the back end so what i want to do is , as i have clicked the href i want that particular id to be sent and keep recieve the data of that particular id only and when i click the second the first should be stopped and start the another .
<html>
</head>
<body>
</body>
</html>
javascript:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}

Try this...
Use setInterval to call function every 1 minute and "trigger" function to click automatically when call function "test"
<html>
</head>
<body>
sdsd
sdsd
</body>
</html>
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
function test() {
$(".todo").trigger("click");
}
var refreshId = setInterval(test, 60000);

You can simply call a setInterval inside your todo function and it will fire with different calls, change your function like this:
function todo(id) {
setInterval(function() {
/*$.ajax({
type: "GET",
url: "example?value=" + id,
dataType: "text",
success: function(data) {
//parsing;
});*/
console.log(id);
}, 1000);
}
link1
link2
I used only 1000 milliseconds for test here, you only have to change it to 60000 to fit your needs, you can see the results in the console..
Note:
Keep in mind that for each click you will fire a new setInterval() so you have to disable click events after the first setInterval() to avoid this problem.

It is not clear as to what constraints you may require from your question and comments, but perhaps something like this?
Repeat will be stopped if there is an ajax error.
Clicking a button will cancel the current repeat and immediately start the new repeat (1-4). Requests in progress are not cancelled and there is no checking included to ignore processing them upon complete.
A stop button is included, this will stop the repeat but not the request in progress.
The requests are async and no effort has been made to make sure that they are processed in order of request.
This is a very basic example that starts you moving in the right direction.
var pre = document.getElementById('out'),
interval = 5,
running = false,
fetching = false,
timerId;
function stop() {
clearInterval(timerId);
running = false;
}
function todo(id) {
fetching = true;
$.ajax({
type: 'GET',
url: 'http://jsonplaceholder.typicode.com/albums?id=' + id,
dataType: 'jsonp',
error: function (qXHR, textStatus, errorThrown) {
pre.textContent += id + ': ' + textStatus + '\n';
stop();
},
success: function (data) {
pre.textContent += id + ': ' + data[0].title + '\n';
},
complete: function () {
fetching = false;
}
});
}
function start(id) {
if (running) {
stop();
}
running = true;
if (!fetching) {
todo(id);
}
timerId = setInterval(function () {
if (!fetching) {
todo(id);
}
}, interval * 1000);
}
document.body.addEventListener('click', function (evt) {
var target = evt.target;
if (target.classList.contains('album')) {
start(target.value);
}
}, false);
document.getElementById('stop').addEventListener('click', function () {
stop();
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="album" value="1">1</button>
<button class="album" value="2">2</button>
<button class="album" value="3">3</button>
<button class="album" value="4">4</button>
<button id="stop">stop</button>
<pre id="out"></pre>

You can use setTimeout of javascript.
It will repeat given function in specified time interval.
Javascript setTimeout function repeat
OR
setInterval( function(){ todo(id);}, 60000);

Make use of setTimeout to call the function again:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
setTimeout(function(){todo(id)}, 60000);
}
And if you also want to clear timeout on some condition:
var timer;
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
timer = setTimeout(function(){todo(id)}, 60000);
if(//Your condition){
window.clearTimeout(timer);
}
}

Related

How to use script to get searched value in php

I am trying to make search button:
<input type="text" name="searchme" id="searchme" onkeydown="searchme()" />
<input type="button" value="SearchMe" />
I want to get all data from table if textbox is empty else myFunction() will be execute and search.
<script>
function searchme() {
var searchvalue;
searchvalue = document.getElementById('search_id').value;
alert(searchvalue);
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: value }
})
}
</script>
is there any problem with script? What should I add?
Your code is looks fine to me. You just need to add success for fetching results.
HTML
<input type="text" name="searchme" id="searchme" onkeyup="searchme()" />
Change onkeydown to onkeyup. because on key the you are not able to get the value.
include jQuery in <head> of your html
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
now JS
function searchme() {
var searchvalue;
searchvalue = $('#searchme').val();
alert(searchvalue);
var table = "table_name";
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: searchvalue, revanue: table},
success: function (result)
{
$(".resultDiv").html(result);
}
})
}
Where .resultDiv is the div where you want to show the result. and remove ' from searchvalue and revanue.
I would do it like this. Since you're using jquery. Might as well use it everywhere.
<input type="text" name="searchme" id="searchme" />
Then your JS
$('#searchme').keyup(function(){
var search = $(this).val();
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: search},
success: function (data)
{
$(".results").html(data);
}
})
});
But also...you probably dont want your script firing on every keystroke. Instead you should wait a fraction of a second between strokes, to only fire the request when the user is actually done typing.
So like this...
// The delay function
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#searchme').keyup(function() {
var search = $(this).val();
delay(function(){
$.ajax({
type: "GET",
url: "get_projectList.php",
data: {searchvalue: search},
success: function (data)
{
$(".results").html(data);
}
})
}, 800 );
});
EXAMPLE HERE

Is there a shorter way to refresh div

I have some elements in my page and I need to refresh their contents every 5 seconds. The code that I'm going to show you works well but it looks so long and repeating itself. When I use only setInterval function, page doesn't loaded regularly before the interval comes. Can you suggest a better way to do this? Thanks in advance. Here is my code:
var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
var refreshSongDetails=setInterval(function() {
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
}, 5000);
Create your ajax call into a function and call it :
var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");
function ajaxCall() {
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
}
ajaxCall();
var refreshSongDetails = setInterval(ajaxCall, 5000);

Javascript status loop

Ok, simple thing in javascript that I could not solve even searching on the web. I guess I even found the right thing but could not put on the right place.
This code tells me if a stream is online or offline. But how do I do to the status and keep updating every 5 seconds?
$(function () {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else {
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
});
Example :
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
var ResInterval = window.setInterval(myAjaxCall, 60000); // 60 seconds
To Stop:
window.clearInterval(ResInterval);
use set time out function
setTimeout(function(){
//your function
foo();
},1000);
Try this out:
function checkStatus() {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else{
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
}
$(function() {
setInterval(checkStatus, 5000);
});
This calls the function checkStatus every 5000 milliseconds (5 seconds).

JS/AJAX Auto submit form: Disabling enter key to prevent page refresh

I am using a function that will submit with ajax and without the help of a button click. But I am currently undergoing two issues which with trial and error haven't found plausible solutions:
First is there any way I can disable the enter button click(this causes the whole page to refresh)?
JSFIDDLE basic example in how the JS function works
Second, It feels like I am going the roundabout way to display what has been posted. How can I change this part of the function $('#special').html('<p>' + $('#resultval', result).html() + '</p>'); to have it POST just inside a div called #special without the need of span or <p> #resultval?
Everytime i echo through php I have to do set it like this to display a result: <div id="special"><span id="resultval">This is the result.</span></div>
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});
</script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(event){// the function call on click or on submit onclick=submitForm(event);
event.preventDefault(); //to prevent enter key
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').text(result); //you can use text() or html() only
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});

Pausing for loop after every execution

i have a page, wherein i am using a ajax for inserting records... now in javascript i am using a for each loop to loop the html table and insert the rows in database. but happens is as foreach loop executes fast, it sometime, does not insert some records.. so i want to make the loop sleep for sometime once it has executed first and thereafter...
is there any way to pause the for loop.. i used setTImeout.. but it just delay it first time and not consecutive times...
here's my code.
function AddTopStories() {
$("#tBodySecond tr").each(function (index) {
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", this).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
window.setTimeout(showSuccessToast(data.d), 3000);
},
error: function (data) {
window.setTimeout(showSuccessToast("Error:" + data.reponseText), 3000);
}
});
});
}
Please help me to resolve this issue... its utmost important.
*************************************UPDATED CODE AS PER THE CHANGES BY jfriend00*********
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex > stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
alert($("td:nth-child(1)", item).text());
addNext();
}
}
This just does not do anything... does not alert...
I'd recommend you break it into a function that does one story and then you initiate the next story from the success handler of the first like this:
function AddTopStories() {
var stories = $("#tBodySecond tr");
var storyIndex = 0;
function addNext() {
if (storyIndex >= stories.length) return; // done, no more to get
var item = stories.get(storyIndex++);
$.ajax({
type: "POST",
url: "AjaxMethods.aspx/AddTopStoriesPosition",
data: "{'articleID':'" + $("td:nth-child(1)", item).text() + "','siteID':1}",
dataType: "json",
contentType: "application/json",
success: function (data) {
addNext(); // upon success, do the next story
showSuccessToast(data.d);
},
error: function (data) {
showSuccessToast("Error:" + data.reponseText);
}
});
}
addNext();
}
Ugly, but you can fake a javascript 'sleep' using one of the methods on this website:
http://www.devcheater.com/

Categories

Resources