charts.js from session var, flicker effect - php

My charts loaded via ajax call looks just fine. Currently, whenever user refresh the page, data are loaded from DB server. As those graphs are quite massive, I thought about using SESSION var to store the charts and speed up loading time (all charts are loaded at the same time). Finally, I achieved the goal however I encountered small issue.
Whenever HTML + JS code is served from $_SESSION var, the chart is presented but with no animation effect. In addition flicker effect is visible (scaling). I solved that by setting responsive to false, but this caused issue with labels, being too small to be accepted.
I tried .destroy() option but with no luck (the same flicker effect) :
var myChart = new Chart(ctw, {
type: 'bar',
data: chart_data,
options: chart_options
});
myChart.destroy();
var myChart = new Chart(ctw, {
type: 'bar',
data: chart_data,
options: chart_options
});
Is there any way I can force animation to kick in (regardless if the chart comes from $_SESSION or not) and do not loss responsiveness?
Thank you.

If myChart.destroy() not working. Try myChart.update().
Try update like this:
var myChartData = myChart.data; // need to store in variable first
myChartData = chart_data; // chart_data from $_SESSION var
myChart.data = myChartData;
myChart.update();
Good luck.

Related

jquery ajax progress with custom calculation

I need advice on my ajax progress bar while executing a long PHP script treating pictures.
I know there are plenty of questions on stackoverflow already like
Show progress for long running PHP script
or JQuery ajax progress via xhr
or update progress bar using ajax request seconds)
Most of the examples I see are using the file size to calculate the progress.
But in my case I would like to calculate percentage based on images_treated / total_images.
So I still can't make this work as I want.
In JS bellow I commented the not working progress function I took from another question and dataType: 'json' for tests but I would prefer if I can still use a JSON return.
Questions
The console.log() will only log once - when the full script is done. Am I doing it wrong?
What should I write to replace the comment?
in some answers, the PHP headers are set to header('Content-Type: application/octet-stream'); is it mandatory or just nicer?
Javascript:
$.ajax(
{
type: 'GET',
// dataType: 'json',
url: formAction,
data: 'addImagesToArticle',
cache: false,
xhr: function()
{
var xhr = new window.XMLHttpRequest();
// Download progress.
xhr.addEventListener("progress", function(e)
{
console.log(e);
// I saw this piece of code from another question it is supposed to work... Maybe my PHP?
/*var lines = e.currentTarget.response.split("\n");
var progress = lines.length ? lines[lines.length-1] : 0;
$('#progress').text(progress);*/
}, false);
return xhr;
}
});
My PHP is quite big so I just explain quickly: in the loop on pics I have variables $images_treated and $total_images. After the loop, a summary is returned to JS via JSON in an object like {error: bool, message: string, ...} so if there is a way to make the progress work without echoing but setting a JSON variable that would be perfect!
Thank you for your help!
[EDIT] to add context details.
I want to use this in an admin side, in an article edition with a WYSIWYG, I have dropzone taking care of my multiple images uploads.
then I see the preview of images while each image is put in temp folder on server. I can then remove some images if needed and once all images are definitive, i click a button that will process them for resizing 2 sizes and inject figure tags with img in the article WYSIWYG editor.
Waw I found a solution!
I am happy to discover that new thing I did not know about PHP and share with people who also don't know (in step 3 bellow)!
#riccardo was right talking about socket - which I don't know so well - but I did not need to go that far.
So I had multiple things to solve in my case before being able to get closer of my goal.
not using xhr.addEventListener("progress"... but a second ajax call in a timer: it will also be lighter-weight in resource consumption.
rather than using a timer like setInterval or setTimeout - as requests are async it may come in unwanted order - use a recursive call in callback of first call like:
function trackProgress()
{
$.getJSON('create-a-new-page.html', 'ajaxTrackProgress=1', function(response)
{
var progress = response.progress;
$('#progress').text(progress);
if (progress < 100) trackProgress();
});
}
then realize that my second script call is delayed by first script still running? yes. So the key here is session_write_close()!
I could dig in this way thanks to this good post:
https://stackoverflow.com/a/1430921/2012407
and I posted a very simple example here to reply to another question: https://stackoverflow.com/a/38334673/2012407
Thank you for all your help in comments guys, it led me to this solution. ;)

Dynamic jquery pages

I didn't really know what to call this so I couldn't find anything by searching. Pretty much I have the following:
$(document).on('click', 'a[data-ajax]', function(e) {
var box = $('#ajaxdata');
e.preventDefault();
var r = $(this).attr('href');
$.ajax({
type: 'post',
url: '/betasite/' + r,
success: function(data) {
box.html(data);
}
});
});
Pretty much it loads the contents of a file (being some html) into a div so the page doesn't need to reload data as often. The problem is having is that I want to have some php inside that loaded file so I can access server side MySQL data and display it. Whenever I try to do this however, it comments the php out like <--php (stuff) -->. Does anyone know how I can work around that (like having the php generate the page before its loaded)?
Your php code will be rendered by server(WAMP/MAMP) automatically if you are on a local environment. If you are not running a server(WAMP/MAMP) you will have to select one depending on the O/S you use.
a good practice is to test the operation of the service in this case "php", before trying the operation in the front-end (jquery). If you have an Apache server up should see the result of their service by accessing the service route.

Mobile browsers doesn't support session variables?

I have a browser version of my web app and I have some values stored in cookies. Now I am making a mobile version and it seems that my cookies are not working.
Is it possible to use cookies on mobile devices?
I am trying to perform this code and my php is giving me an empty value:
$(document).ready(function() {
var session_lang= '<?php if(isset($_SESSION['SESS_LANGUAGE']))
echo $_SESSION['SESS_LANGUAGE'];?>';
if (session_lang!='')
{
check_and_change(session_lang);
}
});
Is there any other way to store data in internal memory so it can work as cookie?
Does mobile devices support session variables? I am looking on the firebug and I can see that I can create session variable but when I want to read it it is null.
What could be a problem and how to solve this?
EDIT:
I will put you almost entire code so you can see what am I doing...btw. this code is working normally on PC browser.
Javascript file:
$(document).ready(function() {
function languageChange()
{
var lang = $('#websites1 option:selected').val();
return lang;
}
$('#websites1').change(function(e) {
var lang = languageChange();
var dataString = 'lang=' + lang;
$.ajax({
type: "POST",
url: "pass_value.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(response) {
check_and_change(response.message);
}
});
return false;
});
} );
function check_and_change(lang)
{
switch (lang)
{ //do something
}
}
Then this first part that I have put above is on the actual php site that I am looking and which is opening:
And the last thing is pass_value.php:
<?php
session_start();
$_SESSION['SESS_LANGUAGE'] = $_POST['lang'];
print json_encode(array('message' => $_SESSION['SESS_LANGUAGE']));
die();
?>
I really don't know why this code doesn't work on the mobile phones.
Cookies definitely work on mobile browsers. You say "I am looking on the firebug" which makes me think you aren't really looking at it on a phone.
Have you started the session, and turned on error reporting?
I had a similar situation and discovered that, before my tablet called the script I specified in the URL parameter of the .ajax( ) call, it was actually calling the index.php script again.
Same with my phone. Since I had initialized my session variables in index.php, they kept getting re-set to their initial values (making it look like they were not being correctly stored between pages).
I never figured out why index.php was getting re-called, but I added if !isset( ) checks around the initialization statements and that cleared it up.
On Android, turning on "Data Saver" effectively destroyed my session. I have a login script which will redirect to the previous page when login succeeds. Worked until I turned on Data Saver. Turning it off made it work again. Google does state that Data Saver may affect secure pages which I guess includes my script, which is not on a HTTPS website.

Running a PHP script via Ajax, through a link?

I'm making a fairly simple rating system, and I've got a small problem. When you +1 rate something, I'm trying to run a PHP script which will connect to the database, download the value from it, +1 to that value, and UPDATE the value in the database again.
I don't think reloading the page for a continious rating system would be a very good idea :S
I'm wondering how I can toggle a PHP script with Ajax, so that when you Click an image of a + sign, it runs the PHP add 1 script, and the + button turns in to a tick. I'm crap at ajax, and I'd go for trying jQuery + $.ajax({}); but I've failed 73 attempts. haha.
Anyone willing to give me a hand writing an Ajax script? :DDD
Thanks! :)
If you want someone to click a link which will access your page, let's assume you have this marup:
<a class = 'plusOne' id = 'someIDForYourSQLTable'>+1</a>
The ID is what you are going to pass to your server script so you can update the appropriate row, generally speaking this should be a primary identifier (i.e. Key) for the record that you want to +1.
Here is the jQuery that will send the ajax request to the file: plusOne.php in the same directory as the current page:
$(function() {
$(".plusOne").bind("click", function() {
$.ajax({
type: "GET",
data: "v="+$(this).attr("id"),
url: "plusOne.php",
success: function(data) {
// Whatever you want to do after the PHP Script returns.
}
});
});
});
The request will send the a URL parameter 'v' which you can access in your PHP script from the $_GET super global array.
html
<img src="plusone.png" rel="some_unique_id" class="rate" />
javscript
$(".rate").click(function() {
var elem = $(this);
$.get('/rate.php?id=' + elem.attr('rel'), function() {
elem.attr('src', 'checked.png').unbind('click');
});
});
and in php
mysql_connect('localhost','db_user','pssword');
mysql_query('UPDATE database_name.table_name SET rating=rating+1 where id=' . mysql_real_escape_string($_GET['id']));
Have a look at xAjax, a library to expose PHP functions/method to client-side JavaScript. xAjax makes things very simple.
For example, you are able to perform several changes in the browser in parallel:
$objResponse = new xajaxResponse();
$objResponse->assign("myInput1","value",$DataFromDatabase);
$objResponse->assign("myInput1","style.color","red");
$objResponse->append("myDiv1","innerHTML",$DataFromDatabase2);
$objResponse->prepend("myDiv2","innerHTML",$DataFromDatabase3);
$objResponse->replace("myDiv3","innerHTML","xajax","<strong>xajax</strong>");
$objResponse->script("var x = prompt("Enter Your Name");");
return $objResponse;

Google Visualization API working locally, but not on external server?

I'm building a dynamic pie chart to show election results using the Google Visualization API and jQuery, and I had it (sort of) working on my local machine, and wanted to get some feedback, so uploaded it to an external server, now everything I try to load gives me a "No Data" error.
I've got two files, one which gets data from a database and converts it to JSON, and one which displays the visualization, depending on what areas are checked. You can see it here:
http://www2.lichfielddc.gov.uk/sandbox/pie.php?electionid=14
Any ideas where I'm going wrong?
Cheers
Think I may be on to something.
I downloaded it and tested it locally and as you said it works fine. However, in the datasource i was using (data.php) if I put a delay (sleep(1)) it stopped working. I think it was because you were drawing the chart out of the ajax success callback.
Try this:
function drawVisualization() {
$('.poll').click(function() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Party');
data.addColumn('number', 'Votes');
var polls = [];
$('.poll:checked').each(function(){
polls.push(this.value);
});
polls.join(",");
url = "http://www2.lichfielddc.gov.uk/sandbox/piedata.php?pollid=" + polls;
$.getJSON(url, function(d) {
data.addRows(d.length);
var items = [];
var num = 0;
$.each(d, function(i, o) {
console.log(o);
data.setValue(num, 0, o['party']);
data.setValue(num, 1, o['votes']);
num++;
});
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data);
});
});
Stepping through the code: By the time you call the draw() method, the object 'data' has no data in it. This is likely because the modifications to the data object are not in the same scope.
I agree with Tribal that it's a timing issue, because the live version does work sometimes. There's a couple of other lurking bugs, that aren't behind the presenting issue, but ...
polls.join(",");
url = "http://www2.lichfielddc.gov.uk/sandbox/piedata.php?pollid=" + polls;
polls.join() returns a string, it doesn't do the join in-situ. And url isn't being declared as a local variable

Categories