Codeigniter: calling model from view - DB content seems frozen - javascript

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.

Related

Reload div each time meta value of current page is updated in wordpress

For now, I have this :
<?php
$result = get_metadata('post', 3241, 'progression_aujourdhui', true);
?>
<div class="ligne_barre ligne_barre_aujourdhui">
<div id="progress_bar-aujourdhui" class="progress_bar_salle_presse">
<h2 class="progress-title"><?= wp_get_attachment_image(3278, 'full'); ?></h2>
<div class="blocs-barre-progression">
<div class="skill-item">
<div class="progression">
<div class="progress_bar" data-progress-value="<?= $result; ?>" data-progress-equipe="equipe1">
<div class="progress-value"><?= $result . "%" ?></div>
</div>
</div>
</div>
</div>
</div>
</div>
The code is inserted in a page called "Salle de Presse" using a shortcode.
This page called "Salle de Presse" has a metakey named 'progression_aujourdhui'.
On reloading that "Salle de Presse" page, if the value of the metakey "progression_aujourdhui" has been updated, the "data-progress-value" updates well in the div with class "progress_bar".
Now, what I would like is to make the div with class "ligne_barre" to reload each time the value of the meta key "progression_aujourdhui" is updated, without having to refresh the whole page myself.
I know that AJAX is needed, but I'm not sure how to use it in wordpress, and furthermore the "detect when a meta value is updated" part leaves me with no success in my research on the internet.
This will not be an easy task to establish on a wordpress. There are 2 general solutions to this problem.
Use "long pooling", basically call your wordpress api from the frontpage each n seconds and update data if changed. This may prove costly as each client will bombard your backend.
Use web-sockets and subscription method, usually you will need a custom vps (server) for this with nignx proxy, enable tcp connection, and get a "subcription" whenever database changes, but still the logic "to who and where to send this database change info" will be on your side. Wordpress and websocets should be enough to get you going
Good luck
It sounds like you are trying to retrieve data from a database and update the data on the front end without a page reload.
I use Ajax calls quite a lot in wordpress for this and I find them pretty easy to do.
You make an Ajax call from your front end JavaScript.
The Ajax call triggers a PHP function in your function.php file. The function sends a response containing the requested data back to the front end.
The font end JavaScript then processes the response received and updates the page values, etc without reloading the webpage.
Use Ajax. What you'll want is to use a single ajax session to get updates with an infinite timeout. you'll need javascript for this (i dont bother with jquery), and some php hooks.
For javascript you can dynamically generate it such as using admin_url(); to output the path of admin but the normal static path is /wp-admin/admin-ajax.php
Give your elements an id thats related. for instance i use a button to fetch data so use an onclick trigger to a function that sends the ajax.
var t0 = performance.now();
var request=document.getElementById('status');
var table=document.getElementById('contents');//div that will contain the updated html
var t1;
xhr = new XMLHttpRequest();
xhr.open('POST', '../wp-admin/admin-ajax.php',true);//../ forces root url but just / works
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
t1 = performance.now();
request.innerHTML='Status:Successful Time:'+ (t1-t0) + 'ms';
table.innerHTML=xhr.responseText;
//polymorphism here, recall the ajax function
}
else if (xhr.status !== 200) {
t1 = performance.now();
request.innerHTML='Status:Failed Time:'+ (t1-t0) + 'ms -'+xhr.status;
//polymorphism here, recall the ajax function
}
xhr.send("action=me_action&mevar1="+me_value+"&..."+status);
On the php side you'll need this:
add_action("wp_ajax_me_action", "me_function");
function me_function(){
$response='your response here';
$mevar=$_Request['mevar1'];.....
echo $response;
}
To improve performance, set output_buffering=On or 1 (dont use a set limit as a smaller output will cause delays) in your php.ini as large requests can be more efficiently packaged across the network and with compression.
To continuously update or recheck just use
setTimeout(my-ajax-function,0);
but if the server has a timeout for this then use setInterval(my-ajax-function,less-then-server-timeout-in-milliseconds);
many wordpress setups are already heavy, it takes a lot of resources on servers to run the php that while a static web page can be delivered in 50ms, your wordpress response will tend to be delivered in 500ms-1s for most installs unless you actually know how to optimise it (a service i do offer from the ground up, server to wordpress). I did not use jquery because if you barely need it for a page, please avoid using it to save on resources. Same for your ajax calls, do it with as few requests as possible and try to get everything in 1 request. This applies to other wordpress related work like using the wordpress REST API as each request adds a significant delay that can end up stacking from seconds into minutes. A page of 100 listed items with 100 requests can take 50 seconds, and a lot of CPU, so do it all in 1 or as few requests as possible.

Ajax Call to refresh web page

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

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.

How to properly handle "chat updating" in a chat page?

So I'm trying to make a chat program in JavaScript using AJAX, and PHP. I am currently updating the chat like this, and I'm sure it's very hard on my server:
<div id="messages">[no messages]</div>
This is whats in the file called ajax-load-messages.php
<?php
$sql_posts_result = mysql_query("SELECT Post FROM Posts ORDER BY Date ASC LIMIT 50", $db) or die("Can't load post"."<br/>".mysql_error());
if(!empty($sql_posts_result)){
while($row = mysql_fetch_row($sql_posts_result)){
echo '<div class="message-post">'.$row[0].'</div>';
}
}
?>
and that's called by this javascript:
setInterval(function(){
$('#messages').load('/ajax-load-messages.php');
}, 3000);
So every 3 seconds I load the last 50 messages to the #messages div.
I know there's a way to handle this that isn't even like 10% as resource intensive, but I don't know where to start. How can I handle this better?
Give the table an int autoincrement id. Keep track of the highest id received (in the session maybe), and on next poll only look for ids higher than that (i.e. only records created since last poll).
These would be my suggestions to handle your chat system better:
1) I would suggest to use a chained-setTimeout instead of setInterval
Why? Suppose the load takes longer than 3 seconds. Then setInterval will beat that and cause more than 1 XML HTTP Request to happen, causing a strain in the browser.
This is how a chained setTimeout would look like in your example:
setTimeout(function loadMessages() {
$("#messages").load('/ajax-load-messages.php', function onLoadMessagesComplete(responseText, textStatus, xmlHttpRequest) {
setTimeout(loadMessages, 3000);
});
}
2) Instead of writing HTML in ajax-load-messages.php, you could respond back with a JSON object json_encode(). Then if you keep track of each chat instance's messages in an array that are currently displayed, then you can figure out if there is a new message or not (developerwjk's answer is a good suggestion). This way, you don't have to reload the DOM every 3 seconds (regardless if there was a new message or not). Of course, you would need to keep aware of the memory usage in the browser though.
===
Usually chat systems (like the Facebook, Google+) use pushing systems rather than polling. The server pushes to the client if there is a new message. This reduces the number of requests to the server, but it could be more difficult to implement.

How to update/modify webpage content with Javascript before page load completed?

I'm trying to display a progress bar during mass mailing process. I use classic ASP, disabled content compression too. I simply update the size of an element which one mimics as progress bar and a text element as percent value.
However during the page load it seems Javascript ignored. I only see the hourglass for a long time then the progress bar with %100. If I make alerts between updates Chrome & IE9 refresh the modified values as what I expect.
Is there any other Javascript command to replace alert() to help updating the actual values? alert() command magically lets browser render the content immediately.
Thanks!
... Loop for ASP mail send code
If percent <> current Then
current = percent
%>
<script type="text/javascript">
//alert(<%=percent%>);
document.getElementById('remain').innerText='%<%=percent%>';
document.getElementById('progress').style.width='<%=percent%>%';
document.getElementById('success').innerText='<%=success%>';
</script>
<%
End If
... Loop end
These are the screenshots if I use alert() in the code: As you see it works but the user should click OK many times.
First step is writing the current progress into a Session variable when it changes:
Session("percent") = percent
Second step is building a simple mechanism that will output that value to browser when requested:
If Request("getpercent")="1" Then
Response.Clear()
Response.Write(Session("percent"))
Response.End()
End If
And finally you need to read the percentage with JavaScript using timer. This is best done with jQuery as pure JavaScript AJAX is a big headache. After you add reference to the jQuery library, have such code:
var timer = window.setTimeout(CheckPercentage, 100);
function CheckPercentage() {
$.get("?getpercent=1", function(data) {
timer = window.setTimeout(CheckPercentage, 100);
var percentage = parseInt(data, 10);
if (isNaN(percentage)) {
$("#remain").text("Invalid response: " + data);
}
else {
$("#remain").text(percentage + "%");
if (percentage >= 100) {
//done!
window.clearTimeout(timer);
}
}
});
}
Holding respond untill your complete processing is done is not a viable option, just imagine 30 people accessing the same page, you will have 30 persistent connections to the server for a long time, especially with IIS, i am sure its not a viable option, it might work well in your development environment but when you move production and more people start accessing page your server might go down.
i wish you look into the following
Do the processing on the background on the server and do not hold the response for a long time
Try to write a windows service which resides on the server and takes care of your mass mailing
if you still insist you do it on the web, try sending one email at a time using ajax, for every ajax request send an email/two
and in your above example without response.flush the browser will also not get the % information.
Well, you don't.
Except for simple effects like printing dots or a sequence of images it won't work safely, and even then buffering could interfere.
My approach would be to have an area which you update using an ajax request every second to a script which reads a log file or emails sent count file or such an entry in the database which is created by the mass mailing process. The mass mailing process would be initiated by ajax as well.
ASP will not write anything to the page until it's fully done processing (unless you do a flush)
Response.Buffer=true
write something
response.flush
write something else
etc
(see example here: http://www.w3schools.com/asp/met_flush.asp)
A better way to do this is to use ajax.
Example here:
http://jquery-howto.blogspot.com/2009/04/display-loading-gif-image-while-loading.html
I didn't like ajax at first, but I love it now.

Categories