Implementing Charts.js in Laravel 5.1 - laravel

Hi I've been wondering around the net getting answers can't find one. I'm trying to display Chart using Charts.js..
In my route:
Route::get('surveys/chart', 'AboutController#projectChartData');
In my AboutController: I used json_encode() to pass data to my view
public function projectChartData()
{
$devlist = json_encode(DB::table('surveys')
->select(DB::raw('MONTHNAME(updated_at) as month'), DB::raw("DATE_FORMAT(updated_at,'%Y-%m') as monthNum"),
DB::raw('count(*) as projects'))
->groupBy('monthNum')
->get());
return view('pages.chart',compact('devlist'));
}
In my view:
<canvas id="projects-graph" width="1000" height="400"></canvas>
<script type="text/javascript">
$(function(){
$.getJSON("surveys/chart", function (result) {
alert('');
var labels = [],data=[];
for (var i = 0; i < result.length; i++) {
labels.push(result[i].batch);
data.push(result[i].created_at);
}
var buyerData = {
labels : labels,
datasets : [
{
fillColor : "rgba(240, 127, 110, 0.3)",
strokeColor : "#f56954",
pointColor : "#A62121",
pointStrokeColor : "#741F1F",
data : data
}
]
};
var buyers = document.getElementById('projects-graph').getContext('2d');
new Chart(buyers).Line(buyerData, {
bezierCurve : true
});
});
});
</script>
The problem It doesn't Display the Graph. But if I just return the data not using json_encode it gives me array() but charts.js needs json.
I'm really having difficulty implementing charts (morris,lavacharts,highcharts,charts.js) in laravel 5 since, not much of a proper turorial out of google. And if anyone can give me nice package I could use. big thanks..

You will pass your data to view and in your view you will just json_encode like this {!! json_encode($devlist) !!}

Related

Shopify: How can I render the recommended products?

I am trying to use Shopify Ajax API to get recommended products inside the cart. I am able to get the recommended product's json but not the section rendering.
The script (note section_id):
jQuery.getJSON('/cart.js', function(cart) {
// first recommendation
jQuery.getJSON("/recommendations/products.json?product_id=" + cart.items[0].product_id + "&limit=6&section_id=recommended_first", function(
response
) {
var recommendedProducts = response.products;
}
});
})
The HTML:
<div id="recommended_first" class="upsell_product">
</div>
I get some messages in the console:
Error: ShopifyAnalytics.meta.page.pageType is empty: undefined
Fallback logic initiated
What am I missing? I didn't find any examples in the Shopify doc.
Thanks a lot!
Your code will not work because you have an extra } on line 7. Assuming the cart request returns valid data, the following code should work (also a good idea to check if the cart request returns any items before using the cart.items variable):
jQuery.getJSON('/cart.js', function(cart) {
jQuery.getJSON("/recommendations/products.json?product_id=" + cart?.items?[0]?.product_id + "&limit=6&section_id=recommended_first", function(response) {
var recommendedProducts = response.products;
var recommendedProductsHTML = "";
for (i = 0; i < recommendedProducts.length; i++) {
recommendedProductsHTML += `<div>${recommendedProducts[i].title}</div>`;
}
$("#recommended_first").html(recommendedProductsHTML);
});
});

Multiple invisible recaptchas always send empty g-recaptcha-response

I'm using the new invisible recaptcha on my website, and in the homepage I have two forms with recaptcha validation.
Because I'm using more than one recaptcha in the same page, I had to use the method and set it to explicit.
Anyway, I lost an entire day of searching to understand that I need to use grecaptcha.execute() to make it work, but it didn't work even with it, I'm probably doing something wrong, but I don't know what exactly is it, here's some code:
<script type="text/javascript" charset="utf-8">
var onloadCallback = function() {
var recaptchas = document.querySelectorAll('div[class=g-recaptcha]');
for( i = 0; i < recaptchas.length; i++) {
grecaptcha.render( recaptchas[i].id, {
'sitekey' : '',
'badge' : 'inline',
'size' : 'invisible'
});
grecaptcha.execute(i);
}
}
</script>
In the forms I'm using it like this:
<div class="g-recaptcha" id="rc1"></div>
And in the end of the page:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
I really don't know why it isn't working now, I've set grecaptcha.execute to "i" because I've read that it's a 0 based index, so it should work, but it doesn't
For those wondering how to do it, I got it to work by loading both explicitly, and it worked, like this:
<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
<script>
var recaptcha1;
var recaptcha2;
var myCallBack = function() {
//Render recaptcha1 on element with ID "recaptcha1"
recaptcha1 = grecaptcha.render('recaptcha1', {
'sitekey' : 'your-site-key',
'theme' : 'light'
});
//Render recaptcha2 on element with ID "recaptcha2"
recaptcha2 = grecaptcha.render('recaptcha2', {
'sitekey' : 'your-site-key',
'theme' : 'light'
});
};
</script>

Does anyone know why this Ajax wont work?

I have some code, some to change the class of a div, the rest to load content into the ajax div.
The ajax div however, does not load content. Why might this be?
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var otherClasses = favorites.className;
if (otherClasses.contains("Active")) {
everyone.className = 'statusOptionActive';
favorites.className = 'statusOption';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var otherClasses = everyone.className;
if (otherClasses.contains("Active")) {
favorites.className = 'statusOptionActive';
everyone.className = 'statusOption';
}
}
function loadXMLDoc(event) {
$.ajax({
url: "../home/" + event.data + ".php",
type: "GET",
success: function (result) {
$("#centreCont").html(result);
}
});
}
}
</script>
These divs start the ajax code (or should do at least)
<div id="everyone" class="statusOptionActive" onclick="loadXMLDoc('indexEveryone')">Everyone, everywhere</div>
<div id="favorites" class="statusOption" onclick="loadXMLDoc('indexFav')">Favourites Only</div>
Why won't it work :(
DEMO
Delete your div onclick event,since already you are manipulating your click event in the script.
Edited div
<div id="everyone" class="statusOptionActive">Everyone, everywhere</div>
<div id="favorites" class="statusOption">Favourites Only</div>
And I don know what argument you are passing in to loadXMLDoc('indexFav'); and loadXMLDoc('indexEveryone'); apart from that your javascript code is correct.
Hope this helps
Thank you
One obvious problem I can see is that you pass a string to loadXMLDoc, then you try to access .data on that string.

one dropdown appears on the selection of other dropdown using codeigniter

I am trying to create dynamic dropdown of category and on selection of this category sub-category dropdown should appear. I have done this using OOP PHP but really having tought time with codeigniter.
Firstly I have created this category dropdown
<?php
$js =' onChange="callAjaxFunction(this.value)"';
echo form_dropdown('category', $categories, null, $js); ?>
Javascript to show sub-category
<script>
// JavaScript Document
var enableCache = false;
var jsCache = new Array();
var AjaxObjects = new Array(new sack(),new sack());
function ShowContent(divId,ajaxIndex,url)
{
document.getElementById(divId).innerHTML = AjaxObjects[ajaxIndex].response;
if(enableCache){
jsCache[url] = AjaxObjects[ajaxIndex].response;
}
AjaxObjects[ajaxIndex] = false;
document.getElementById("ajax_container").innerHTML = '';
}
function ShiftChanger(divId,url,id) {
//to show the div
document.getElementById(divId).innerHTML="";
if(enableCache && jsCache[url]){
document.getElementById(divId).innerHTML = jsCache[url];
return;
}
var ajaxIndex = AjaxObjects.length;
AjaxObjects[ajaxIndex] = new sack();
AjaxObjects[ajaxIndex].requestFile = url+"?id="+id;
document.getElementById("ajax_container").innerHTML = '<img src=ajax_loader.gif hspace=10 vspace=10 />'; AjaxObjects[ajaxIndex].onCompletion = function(){ ShowContent(divId,ajaxIndex,url+"?id="+id);};
AjaxObjects[ajaxIndex].runAJAX();
}
function callAjaxFunction(value)
{
ShiftChanger('shiftcontainer','ajax_category.php',value);
}
</script>
But this is not working. As you can see ajax_category.php is not being able to pass. I think it should be done with controller, I had tried that also but nothing seems as working. I am really stuck with this. Please anyone with little help. Really getting depressed with it :(.

AJAX separating the data returned into specific DIVs

AJAX code:
<script type="text/javascript">
function doCalc(){
var roomX = $('#room_str').val();
var heightX = $('#height_str').val();
var widthX = $('#width_str').val();
var prodid = $('#prodid').val();
var qtyX = $('#qty_str').val();
$.post('db_query.php',
{qtyX:qtyX, roomX:roomX, heightX:heightX, widthX:widthX, prodid:prodid},
function(data) {
data = $.parseJSON(data);
$('#width-placeholder').html(data.width);
$('#height-placeholder').html(data.height);
// ...
});
return false;
};
</script>
PHP Code:
<?php
include('db_pbconnection.php');
$query = mysql_query(" SELECT * FROM price_dimensions WHERE prodid = '".$_POST['prodid']."' AND height >= '".$_POST['heightX']."' AND width >= '".$_POST['widthX']."' ORDER BY height ASC, width ASC LIMIT 1 ");
$results = array();
$row = mysql_fetch_array($query);
$results = array(
'width' => $row['width'],
'height' => $row['height'],
'price' => $row['price']
);
$json = json_encode($results);
echo $json;
?>
EDIT: Updated code works successfully thanks to Alex. This uses json_encode to send the data back with ability to assign each SQL row to an identified for placeholders. This is just in case you need to move your data around individually in a layout.
If I'm not mistaken, what you try to do is apply selectors to HTML data coming from AJAX request. Yes? I don't think jQuery would help you here.
An option might be to have this div structure already on page as some template with placeholders. And your AJAX calls should return data in JavaScript native, parsable format - JSON. PHP has a function which will make JSON for you - json_encode. After you get JSON from your server, you can do this:
function(data) {
data = $.parseJSON(data);
$('#width-placeholder').html(data.width);
$('#height-placeholder').html(data.height);
// ...
});
return false;
};

Resources