Is there a shorter way to refresh div - javascript

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

Related

How to invoke a method from ajax success function?

I've a jQuery with ajax using to fetch some data from a servlet
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: function(response){
//some data fetched from ServiceToFetchDocType
//Need to invoke another method here
}
});
</script>
Is it possible to invoke another method inside the success function and get some value?
I've very new to jQuery and ajax, any kind of help is appreciated.
$(document).ready(function() {
$.ajax({
url: 'ServiceToFetchDocType',
type: 'post',
cache: false,
success: function(response) {
/* invoke your function*/
yourFunction();
}
});
});
you can do something like this
var invokeAfterSuccess = function() {
}
var successFunction = function(response) {
/* do something here */
invokeAfterSuccess()
}
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: successFunction
})
/*--------------- OR -------------*/
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false
}).done(successFunction)
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: function(response){
Myfunction(); //this is how you can call function
}
});
Myfunction(){
alert("hiii")
}
}
</script>
// thats how it will work
[success: function (data) {
TypeOfReportDropdown.closest("form").find("div\[id$='MonitoringChemicalData'\]")\[0\].innerHTML = data;
var hours = $("#UptimeHourYear").val();
var emissions = round(parseFloat(($("#AverageMassLoadOut").val() * hours) / 1000), 1);
$("#Emissions").val(emissions);
$("#TotalEmissions").val(emissions);
$(this).delay(3000).queue(function () {
var emissieTotal = 0;
var totalHAP = 0;
$('\[data-emissie\]').each(function () {
emissieTotal += Number($(this).data('emissie'));
var hap = $(this).data('hap');
if (hap == "True") {
totalHAP += Number($(this).data('emissie'));
}
});
var emissieFinalTotal = round(emissieTotal, 3);
$('#TotalEmissionForOnlineInstruments').html(emissieFinalTotal);
var totalHAPFinal = round(totalHAP, 3);
$('#TotalHAPForOnlineInstruments').html(totalHAPFinal);
});
}][1]

jQuery clearinterval / stopinterval doesn't work

I have an autorefresh function that gets called if a checkbox is checked and a button clicked. I want to stop the autorefresh when the checkbox is unclicked:
var refreshId = null;
$("#disINFRAlive").click(function(infralivefun) {
event.preventDefault(infralivefun);
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
if ($('#autorefcheck').is(':checked')) {
var refreshId = setInterval(function() {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
}, 5000);
}
});
The autorefresh works if the checkbox #autorefcheck is checked and the button #disINFRAlive is clicked. However, I can't make it stop by unchecking the checkbox:
function stopinterval(){
clearInterval(refreshId);
return false;
}
$('#autorefcheck').click(function() {
stopinterval();
});
I tried to use clearInterval in various ways and none worked so far.
Remove the var keyword from the initialization of refreshId.
if ($('#autorefcheck').is(':checked')) {
refreshId = setInterval(function() {
The way you have it, you are redeclaring the variable in a different scope. That way, you cannot access it from stopInterval().

Set the function itself to the url in AJAX?

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

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/

Can we have two or more function call in jquery-ajax success

I have request to webservice and getback xml result as output , In sucess function can i have a two or more function call
function searchLocationNear() {
// Get the radius using jQuery
var radius = $("#radiusSelect").val();
// Make Ajax call using jQuery
$.ajax({
type: "POST",
data: "keyword1=&streetname=&lat=&lng=&radius=" + radius,
url: "WebService1.asmx/GetList",
success: function (response) {
var xml = GXml.parse(response.xml);
....
.....
var marker=createmarker(...........);
var sidebar cretesidebar(.........);
},
error: function (response) {
alert(response);
}
});
}
function createmarker(..........)
{}
function createsidebar(....)
{
}
Yes you can. Don't forget the assignment symbol var sidebar = cretesidebar(...);

Categories

Resources