ajax function auto reload - javascript

Hello i am getting data from a php file in json format,all works fine.I would however desire that this function reloads every say 3000millisecs thus updating the data.
How do I achieve this?
function loadFbill(hsid)
{
// Display a loading icon in our display element
$('.list-item-display').html('<span><img src="img/progress.gif" /></span>');
// Request the JSON and process it
$.ajax({
type:'GET',
url:""+xhr_path+"js_on.php",
data:"hid="+hsid+"&subscribers=paid",
success:function(feed) {
// Create an empty array to store images
var thumbs = [];
// Loop through the items
for(var i=0, l=feed.response.length; i < l && i < 6; ++i)
{
// Manipulate the image to get thumb and medium sizes
var payee = feed.response[i].result_paid;
var transaction_m = feed.response[i].result_payment_details;
var ptime = feed.response[i].result_time;
var plan = feed.response[i].result_plan;
var payee_num = feed.response[i].result_num;
var localhs = feed.response[i].result_hs;
var transaction_date = feed.response[i].result_payment_date;
var diff_date = feed.response[i].result_time_diff;
// Add the new element to the array
thumbs.push("<div class=list-item><div class=list-datetime><div class=time>"+ptime+"</div></div><div class=list-info><img src=img/pesa/ps_"+transaction_m+".jpg height=28 width=28 class=img-circle img-thumbnail/></div><div class=list-text><a href=# class=list-text-name> "+payee+" </a><p>"+payee_num+" <span class=icon-calendar></span> "+transaction_date+" <span class=icon-calendar-empty></span>"+diff_date+"<span class=icon-globe></span> "+localhs+" </p></div><div class=list-controls> "+plan+"</div></div>");
}
// Display the thumbnails on the page
$('.list-item-display').html(""+thumbs.join('')+"");
// A function to add a lightbox effect
addLB();
},
dataType:'json'
});
}

You can simply add setTimeout into ajax request callback function:
function loadFbill(hsid) {
// Display a loading icon in our display element
$('.list-item-display').html('<span><img src="img/progress.gif" /></span>');
// Request the JSON and process it
$.ajax({
type: 'GET',
url: "" + xhr_path + "js_on.php",
data: "hid=" + hsid + "&subscribers=paid",
success: function (feed) {
// ... all your code untouched
setTimeout(loadFbill, 3000); // <-- and reload again
},
dataType: 'json'
});
}

Related

JQUERY ajax post - multiple click, one reload - it is possible?

I have a problem and I don't know what is the solution. I would like to reload the specified divs only once after multiple click. Now when I add new item to the database from dropdown input, then after each click each time reload the specified div, and sometimes it is very disturbing. When you want to select a new item from the list, and then suddenly reset, and you need to select again). How can I do that if I click to add new item (sometimes I select 4-5 new items - not multiple select!) then not refresh the specified div after each click, just once with a specified delay.
Here is the current code of the javascript part (now it refresh after 100 milliseconds after a new item added). I hope that someone could help me, or give me an idea how can I resolve this. Many thanks!
<script type="text/javascript">
$('body').on('click',".addhplayer",function() {
var absidplayer = $('#abshidplayer').find(":selected").val();
var abstype = $('#abshtype').find(":selected").val();
var obj = $(this); // first store $(this) in obj
var absseasonid = $(this).attr('data-absseasonid');
var absidclub = $(this).attr('data-absidclub');
var absidmatch = $(this).attr('data-absidmatch');
//var dataString = 'abstype=' + abstype + '&addplayer=1&' + 'absidplayer=' + absidplayer + '&' + 'absidclub=' + absidclub + '&' + 'absidmatch=' + absidmatch + '&' + 'absseasonid=' + absseasonid;
$.ajax({
url: 'edit_absence.php',
type: 'POST',
timeout: 100,
data: {
addtype: abstype,
addhplayer: '1',
addidplayer: absidplayer,
addidclub: absidclub,
addidmatch: absidmatch,
addseasonid: absseasonid
},
success: function(response, textStatus, jqXHR){
$('.hpstatus').show();
$(".hpstatus").load(" .hpstatus");
$('#injur').show();
$("#injur").load(" #injur");
$("#homelineups").load(" #homelineups");
$("#awaylineups").load(" #awaylineups");
},
});
});
</script>
check out my old response to this question :
How do you send an ajax request every time that a form input field changes?
basically wrap your event code to a delayed function, on multiple call it will cancel the previous planned ajax call if the delay is not reach
edit > on your particular code :
var changeTimer = false;
function yourSpecificEventCode(){
var absidplayer = $('#abshidplayer').find(":selected").val();
var abstype = $('#abshtype').find(":selected").val();
var $o = $(this); // first store $(this) in obj
var absseasonid = $o.attr('data-absseasonid');
var absidclub = $o.attr('data-absidclub');
var absidmatch = $o.attr('data-absidmatch');
$.ajax({
url: 'edit_absence.php',
type: 'POST',
timeout: 100,
data: {
addtype: abstype,
addhplayer: '1',
addidplayer: absidplayer,
addidclub: absidclub,
addidmatch: absidmatch,
addseasonid: absseasonid
},
success: function(response, textStatus, jqXHR){
$('.hpstatus').show().load(" .hpstatus");
$('#injur').show().load(" #injur");
$("#homelineups").load(" #homelineups");
$("#awaylineups").load(" #awaylineups");
},
});
}
$('body').on('click',".addhplayer",function() {
if(changeTimer !== false) clearTimeout(changeTimer);
let t = this ;
changeTimer = setTimeout(function(){
yourSpecificEventCode.call( t ) ;
changeTimer = false;
},300);
});

yii2 hide model name from url in GET Method

I have a script that switches images in a certain amount of time. But on my page, the images are not displayed because they get method gets the wrong URL: GET http://schedule/monitor/img/math/22.03/22.03.JPG 404 (Not Found). The correct URL should be like this:
http://schedule/img/math/22.03/22.03.JPG. How to hide the model name from image src when I get this from js script?
slider.js
$(document).ready(function () {
$.ajax({
type: 'GET',
dataType: 'json',
url: '/monitor/insert_math',
data: 'json',
success: function (data) {
var i = 0; //START POINT
var unfiltered_images = data; //UNFILTERED IMAGES ARRAY
var time = 30000; //TIME BETWEEN SWITCH
var images = unfiltered_images.filter(file => file.endsWith('.JPG')); //FILE FILTER BY EXTENSION
console.log(images);
if (images.length != 0) {
function changeImg() {
document.getElementById('slide').src = images[i];
if (i < images.length - 1) { //CHECK IF INDEX IS UNDER MAX
i++; //ADD 1 TO INDEX
} else {
i = 0; //RESET BACK TO 0
}
setTimeout(changeImg, time); //RUN FUNCTION EVERY X SECONDS
}
window.onload = changeImg(); //RUN FUNCTION WHEN PAGE LOADS
}
}
});
});
1311.php
<div class="info_block">
<img id="slide" height="626px">
</div>
Path to PHP file:
document.getElementById('slide').src = "/"+images[i];
answer by Shringiraj Dewangan

Cannot read property 'row' of undefined

//anything inside 'pagebeforecreate' will execute just before this page is rendered to the user's screen
$(document).on("pagebeforecreate", function () {
printheader(); //print the header first before the user sees his page
});
$(document).ready(function () {
searchfriend();
function searchfriend() {
var url = serverURL() + "/getcategories.php";
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getCategoryResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getCategoryResult(arr) {
var t; //declare variable t
//loop for the number of results found by getcategories.php
for (var i = 0; i < arr.length; i++) {
//add a new row
t.row.add([ //error
"<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
]).draw(false);
//We drew a [View] button. now bind it to some actions
$("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) {
var data = event.data;
showcategory(data.id); //when the user clicks on the [View] button, execute showcategory()
});
}
$("#categoryresult").show(); //show the results in the table searchresult
}
function showcategory(categoryID) {
//alert(categoryID);
window.location = "showuser.html?userid=" + userid;
}
});
There is an error on line 33 which stated:
"Uncaught TypeError: Cannot read property 'row' of undefined"
However, it seems that I have no idea where the error is coming from.
Is there anyway I can solve this problem?
You look like you are using a third-party jQuery plugin, DataTables.
Follow the usage of DataTables.
var t; //declare variable t
should be
var t = $("#categoryresult").DataTable();
The variable t is not an object with a property called row.
Try with var t = { row: [] }
Edit: I apologize. I got confused add with push method.
So, you need an object with a method called add and assign that object to t

Display only most recent row of data in Google Sheet from api call

I'm trying to print the most recent row from a Google Sheet, which updates daily. I'm making an API call to it and returning it in Json and whilst I can grab the most recent value, I can only seem to print the whole column of data:
I apologise the code is a bit slap and dash, I'm new to this.
Javascript
var sheetsuUrl = "https://sheetsu.com/apis/v1.0/3e242af0";
$.ajax({
url: sheetsuUrl,
dataType: 'json',
type: 'GET',
// place for handling successful response
success: function(data) {
console.log(data[data.length-1]['moved'])
addCharacters(data);
},
// handling error response
error: function(data) {
console.log(data);
}
});
addCharacters = function(characters) {
var list = $('#ponies');
for(var i=0; i<characters.length; i+=1) {
char = characters[i];
function lastNoZero(myRange) {
lastRow = myRange.length;
for (; myRange[lastRow - 1] == "" || myRange[lastRow - 1] == 0 && lastRow > 0 ; lastRow--) {
/*nothing to do*/
}
return myRange[lastRow - 1];
}
myRange = char.moved;
if (char.moved == 'entered') {
html = "<img src='https://media.firebox.com/pic/p5294_column_grid_12.jpg'/>";
} else {
html = "<img src='http://41.media.tumblr.com/30b1b0d0a42bca3759610242a1ff0348/tumblr_nnjxy1GQAA1tpo3v2o1_540.jpg'/>";
};
list.append(html);
}
}
HTML
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<div id="ponies"></div>
CSS
html img{
width:100px;
height:100px;
}
You needed to reference the last item in the array returned by your GET request.
characters[characters.length - 1]; will get the last character in the characters array. Then, to ensure that the html is not added on each run of the loop, you needed to move list.append(html); outside the loop, ensuring that it only appends the content to the page once.
Run the code snippet below to see in action.
var sheetsuUrl = "https://sheetsu.com/apis/v1.0/3e242af0";
$.ajax({
url: sheetsuUrl,
dataType: 'json',
type: 'GET',
// place for handling successful response
success: function(data) {
addCharacters(data);
},
// handling error response
error: function(data) {
console.log(data);
}
});
addCharacters = function(characters) {
var list = $('#ponies');
for(var i=0; i<characters.length; i+=1) {
char = characters[characters.length - 1];
myRange = char.moved;
if (char.moved == 'entered') {
html = "<img src='https://media.firebox.com/pic/p5294_column_grid_12.jpg'/>";
} else {
html = "<img src='http://41.media.tumblr.com/30b1b0d0a42bca3759610242a1ff0348/tumblr_nnjxy1GQAA1tpo3v2o1_540.jpg'/>";
};
}
//for illustration purposes
list.append(characters[characters.length - 1].time)
//the code to attach the image
list.append(html);
}
<script src="https://code.jquery.com/jquery-3.0.0-alpha1.js"></script>
<div id="ponies"></div>

Using swipe.js with $.ajax() content

I am using Brad Birdsall's Swipe.js plugin as a touch friendly, library agnostic plugin for a slider in my current mobile project. When I populate the slider on page load, everything works great. However if I try and populate the slider with $.ajax() on click, the slider will receive all of the slides, but is not responsive to touch events, or any of the methods associated with the slider.
The general slider HTML structure looks like this:
<div id="slider" class="swipe">
<ul>
<li style='display:block;'>
<img src="/someImageUrl.jpg" />
</li>
<li style='display:none;'>
<img src="/someImageUrl.jpg" />
</li>
</ul>
</div><!-- .swipe -->
<nav>
PREV
NEXT
</nav>
I am using an $.ajax() response to populate the <li><img src="..." /></li> on a click event handler in my doc.
Here's my JS:
$.ajax({
url: "process.inc.php?vehicleId=" + vehicleId,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var swipeSlides = "";
for (i = 0 ; i < data.length; i++) {
var photoUrl = data[i].photoUrl;
var photoArray = photoUrl.split("|");
if (photoArray.length <= 1) {
list += "<img src="+photoArray[i]+" />"
} else {
for (i = 0; i < photoArray.length; i++) {
swipeSlides += "<li><img src='"+photoArray[i]+"' /></li>"
}
var prevNext = "<nav>PREVNEXT</nav>"
var sliderElement = $(self).parent().find("#data #slider ul");
sliderElement.find("li, nav").remove();
sliderElement.append(swipeSlides, prevNext);
$.getScript('../assets/js/swipe.js');
var slider = new Swipe(
document.getElementById('slider')
);
};
};
} // end success function
}); // end AJAX
This will sucessfully populate my page with all of the necessary content, but when I click one of the previous or next puttons, I get this error in my console:
Uncaught TypeError: Object #<HTMLCollection> has no method 'next'
Which tells me that my script is not being loaded into the page appropriately, or, my slider is not being instantiated at the proper time.
I have tried executing my code inside of the $.getScript() method like this:
$.getScript('../assets/js/swipe.js', function(data, textStatus, jqxhr) {
for (i = 0; i < photoArray.length; i++) {
swipeSlides += "<li><img src='"+photoArray[i]+"' /></li>"
}
var prevNext = "<nav>PREVNEXT</nav>"
var sliderElement = $(self).parent().find("#data #slider ul");
sliderElement.find("li, nav").remove();
sliderElement.append(swipeSlides, prevNext);
var slider = new Swipe(
document.getElementById('slider')
);
});
Or even just using a good old fashioned <script src="/assets/js/swipe.js"></script> before my jQuery script executes, and I keep getting the same exact error.
If anyone has any suggestions I will be forever grateful.
I figured out the problem.
In order to make the instantiation of the Swipe element recognized, I needed to use $.globalEval() inside of the $.getScript() function.
Heres my working code:
$.ajax({
url: "process.inc.php?vehicleId=" + vehicleId,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var list = "";
for (i = 0 ; i < data.length; i++) {
var photoUrl = data[i].photoUrl;
var photoArray = photoUrl.split("|");
if (photoArray.length === 1) {
list += "<img class='noPhoto' src="+photoArray[i]+" />";
var parent = $(self).parent().find("#data");
parent.find("table, .noPhoto").remove();
parent.append(list);
} else {
list += "<div id=\"slider\" class=\"swipe\"><ul>";
for (i = 0; i < photoArray.length; i++) {
list += "<li><img src='"+photoArray[i]+"' /></li>"
}
list += "</ul><nav>PREVNEXT</nav></div>";
var parent = $(self).parent().find("#data");
parent.find("table, div").remove();
parent.append(list);
$.getScript("../assets/js/swipe.js", function(data, textStatus, jqxhr) {
$.globalEval("var slider = new Swipe(document.getElementById('slider'));")
});
};
};
} // end success function
}); // end AJAX
Hopefully this helps someone else down the road.
Why use getScript in the first place? Append it to your other javascript files as (before your javascript file), then new Swipe() should work.
Also, if you want to call functions of your Swipe object later, you should declare the var outside your ajax function. Example:
var mySwipe;
document.ready(function(){
//...
});
function pullFromAjaxFunction() {
//... do some more stuff
mySwipe = new Swipe(...)
}

Categories

Resources