Ajax Call to refresh web page - javascript

Update: I am using an apache server on the back-end and vanilla JS and jquery on the front-end.
Currently i have a web page that is displaying a variety of data that i am pulling from my back-end server.
How it works: I have a php script that is scraping directory names and displaying them in a dropdown. I have a refresh function set in my html for the web page that refreshes the page every 30 seconds.
The problem: I don't like the constant refresh, especially if there is nothing to update.
Is there a way to use ajax to pool my back-end server and check if new data has been entered in the directory and then update my dropdown?
Many thanks!

Use .data
window.setInterval(function() {
$.getJSON('/foo', { }, function(result) {
//Get the old data stored in the body using jquery data
var old_data = $('body').data('my_data');
//If objects are not the same, update cell
if ( ! equal_objects(result, old_data) )
update_cell();
//Store the new data
$('body').data('my_data',result);
});
}, 30000);
OBS: equal_objects is a function you should implement to compare 2 objects since JavaScript doesn't provide this functionality. See this post for details: Object comparison in JavaScript

Related

Ajax call to update values in HTML

I am trying to implement a JS that updates an otherwise static HTML table in a set interval without any sort of websockets etc. just using ajax calls. The page is regularly updated with new data on the source server and I want the HTML, once open in the users browser, to load the new values and replace them dynamically.
My solution is matching the user HTML's id-tags with it's updated pairs in the new version on the server and inserting them using the ajax load function.
function updateVals () {
for (var i = 0; i < (idList.length); i++) {
$('#' + idList[i]).load('SamebutUpdated.html #' + idList[i])
}
}
Now, my problem is that when I try to update the source HTML's values on a simulated live server (VSC) while the user's HTML is open, the user's HTML jumps back to it's original data values before reloading the new ones and I'd like for it not to do that but instead keep the previously loaded ones and then replace them yet again.
Hope this is clear and cohesive enough.
Cheers in advance!

How to submit value to database with jquery?

so basically i want to make a webpage to detect how many times user clicked on it and send that value to database. I know i should use ajax but just can't figure out how to use it.
var count = 0;
$("body").click(function() {
$("#track").text("you clicked " + count + " times");
count++;
});
$.ajax({
url: "index.html",
cache: false,
success: function(html){
$("#results").append(count);
}
});
Assuming the following things. You:
have AMP Stack installed with PHP & MySQL.
have a working DataBase in MySQL (most commonly used with PHP).
are running the web server and looking at HTTP version and not file version in Chrome.
I would go by this method:
On load, I'll get the current count from DataBase using a PHP backend.
In the PHP backend, I'll write a code to query MySQL and get the current value.
Use a single file, say count.php as a file to get and set the counts.
Using GET method, the file responds with the count.
Use an AJAX code and get the count data.
Using jQuery with the AJAX's response, update the DOM with the current count.
Once you load the page and update the value, set the event listener on click.
Update the current count in the UI by adding one more.
Use the same code as you have to update the UI to increment the count.
Fire a POST request using AJAX to the count.php and send the new value.
In the count.php, write an UPDATE query to update the count.
Send a success message.
When you reload the page or look at the database, the count will be preserved.

Get data from mysql database on date selection using ajax

I'm trying to fetch data from a MySQL database relevant to the selected date_time.
I have extracted the date_time from the database and displayed it on a page and now the thing I want to do is that "When I select a date the data on that date should be display without refreshing the page".
you have to create an other .php page containing calling your date_time and call it in ajax after ward.
your ajax request should looks like :
$("#Button_get_date").onclick ( function () {
$("#div_to_display").load("/date.php", {"date= (#optiondate#.val));
})
the other page php should contain
$data = $ddb ->query("select * from tableinfodate where date = ".$_POST["date"].");
after i think you know what to do but remember to make your display in your in the loaded page.
have a look at the function load :http://www.w3schools.com/jquery/jquery_ajax_load.asp and also at GET and POST method in php. More over i think it is better to try hard on js before trying to do loaded function as this one.
I hope it helps a bit.

Codeigniter: calling model from view - DB content seems frozen

I am trying to use javascript in my CI view to update (without refresh) a data model every 2 seconds, for my use case where the database contents can be changed by other users.
<script type="text/javascript">
var refreshFunc = setInterval(function() {
<?php
$this -> load -> model('m_cube', '', TRUE);
$stamp = $this -> $m_cube -> stamp();
?>
var stamp = "<?php echo $stamp; ?>";
console.log(stamp);
}, 2000);
refreshFunc;
</script>
I am using JS setInterval to create the 2 second loop, and calling the CI model to retrieve data from the Postgresql database. In the simplified code sample, it's just asking the DB for a timestamp. The problem is that the timestamp written to console doesn't update - something is stuck.
2013-10-21 14:35:54.168-04
2013-10-21 14:35:54.168-04
2013-10-21 14:35:54.168-04
...
Same behavior when querying a table of real data - it doesn't return up-to-date values.
Why does the model access a "frozen" version of the DB?
It's not stuck or "frozen", it's that you had a bit of confusion on what comes before and what after.
I don't see you using AJAX, so by the time your php has been processed (i.e, the data fetched from the db and assigned to $stamp) the page - html, css and javascript too - are yet to be generated and served by the server, nor outputted by the browser.
This means that inside your setInterval you always have the same value, which has been already generated, and thus you keep reprinting the same string.
If you want a continue update, you need to keep requesting the data to the server, and that's where AJAX (Asynchronous JavaScript and XML) can be handy since it runs as a separate request from the main one, so you can work on two different "levels" and fetch content while the rest of the page remains static (already served and outputted).
If you're using jQUery you can look into $.ajax(), which makes this kind of things pretty easy.
When this script runs at the server it fetches the model data and replace the <?php ?> tags with the results. So when it comes to client browser, it doesn't contact server every 2 seconds, but logs the stamp value every 2 seconds. If you want it to be updated you should consider using Ajax technology.

How to re-render the page after a database add call without refreshing?

Hi I am using a form which takes input of some data and when I press submit an Ajax Post request goes to the server which then saves the data in the database and then data only gets updated on the ejs Page when I press refresh.
I want to know is there any way I can make any call through either Jquery or JavaScript that on the success of AJAX POST re renders the ejs page and page is again functional without refreshing?
I tried to use the below code to re load the page what it does is; it works, reloads the data but that data is not accessible or its values are not usable until I refresh
The code I used
$('body').load('views/test.ejs', function () {
$(this).fadeIn(5000);
});
My rendering function looks like this;
function renderList(res, list) {
res.render('admin', {
jsonList: list, // JSON of data generated from DB
listId: req.session.user.listID, //global session
access: req.session.user.Access, //global session
products: req.session.user.Products, //global session
user: req.session.user.FirstName || req.session.LastName
});
}
I have a tabbable menu of bootstrap in which I am passing the IDs of the data from Databases and using those tabbable menu to display corresponding data of that item. So I am not getting IDs when I just use the Load function. only location.reload() works for me but its not a good way to do it.
jQuery .ajax() and .post() have success callback functions that you can use to update the page with your new data. Try looking at this answer of mine for an example.

Categories