Uncaught SyntaxError: Unexpected token < in CodeIgniter - javascript

I am currently working on CodeIgniter charts, but am getting an error like:
Uncaught SyntaxError: Unexpected token <
And charts are not loading showing blank.
var data_course_stats = google.visualization.arrayToDataTable([
['Course', 'Time spent',{ role: 'style' }],
<?php
$i=0;
foreach ($timespent_stats as $course) { $course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
$color_val = $colors[$i++];
?>
['<?php echo $course->title;?>', <?php echo $course->spent_seconds/60;?>,'<?php echo $color_val; ?>'],
<?php } ?>
]);
var options_course_stats = {
title: 'Course Wise Spent Time in Minutes',
curveType: 'function',
height: 400,
bar: {groupWidth: "50%"},
legend: { position: "none" },
};

For longer blocks, to keep PHP open - you're getting in trouble because you're mixing and matching open and closed. Change this:
<?php
$i=0;
foreach ($timespent_stats as $course) { $course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
$color_val = $colors[$i++];
?>
['<?php echo $course->title;?>', <?php echo $course->spent_seconds/60;?>,'<?php echo $color_val; ?>'],
<?php } ?>
to this:
<?php
$i=0;
foreach ($timespent_stats as $course) {
$course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats))) {
$color_val = $colors[$i++];
echo "['" . $course->title . "','" .
$course->spent_seconds/60 . "','" .
$color_val . "']";
}
}
?>

although you have accepted the answer, i want to add the another technique which is little simpler than the previous one. You can perform echo with <?= like <?php echo something; ?> so you can simply do this <?= something ?>
<?php
$i=0;
foreach ($timespent_stats as $course) {
$course = (object)$course;
$color_val = 'green';
if(count($i<count($timespent_stats)))
{
$color_val = $colors[$i++];
?>
[<?= $course->title ?>, <?= $course->spent_seconds/60 ?>, <?= $color_val ?>]
<?php
}
}
?>

If anyone get this problem again, check if your base_url is correct in config/config.php

Related

Alert() javascript function not working in php

I know this is frequently asked question however I have tried using :
script language='javascript'
placed header in else after alert
script type='text/javascript'
Still I don't get alert box, while else parts executes perfectly.
Here's my code:
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data=mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
}
else{
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
?>
What am I missing here.
Thanks
You have your js files mixed up.
Include jquery and then your script, inside separate tags:
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>';
echo '<script type="text/javascript">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
By the way, you do NOT need jquery for a simple alert, as it is plain javascript. Try to avoid including external library if not needed, you will end up with a bloated code.
And printing js with php it's a bit of a hack. Why not just print it into your html or js file?
Javascript inside a script tag that has an src attribute does not get executed, you have to create a second script tag after the jquery one.
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data = mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo '</script>';
echo "<script>alert('PF No. Does not exist. Please Contact Admin!!!');</script>";
} else {
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
}
?>

Form values are not inserting into my database

My form values are printing on this page but they are not inserting into my
database. I don't know what is wrong? If all the values are printing
that means values are reaching on this particular page but not going into
database.Even the columns in the database are sorted, but it still doesn't
work.
<?php
include("connection.php");
if(isset($_POST['continue']))
{
echo $eta_type = $_POST['eta_type'];
echo $firstname = $_POST['firstname'];
echo $lastname = $_POST['lastname'];
echo $title1=$_POST['title1'];
echo $dob=$_POST['dob'];
echo $gender=$_POST['gender'];
echo $nationality=$_POST['nationality'];
echo $cob=$_POST['cob'];
echo $passportnumber=$_POST['passportnumber'];
echo $pid=$_POST['pid'];
echo $ped=$_POST['ped'];
echo $residence=$_POST['residence'];
echo $possesseta=$_POST['possesseta'];
echo $multipleentry=$_POST['multipleentry'];
echo $arrivaldate=$_POST['arrivaldate'];
echo $purpose=$_POST['purpose'];
echo $final_dest=$_POST['final_dest'];
echo $stay_days=$_POST['stay_days'];
echo $add1=$_POST['add1'];
echo $add2=$_POST['add2'];
echo $city=$_POST['city'];
echo $state=$_POST['state'];
echo $pscode=$_POST['pscode'];
echo $country=$_POST['country'];
echo $addlanka=$_POST['addlanka'];
echo $email=$_POST['email'];
echo $alternate_email=$_POST['alternate_email'];
echo $phone=$_POST['phone'];
echo $mobile=$_POST['mobile'];
echo $fax=$_POST['fax'];
$date1 = date('Y-m-d', strtotime($dob));
$date2 = date('Y-m-d', strtotime($pid));
$date3 = date('Y-m-d', strtotime($ped));
$date4 = date('Y-m-d', strtotime($arrivaldate));
$address=$add1.$add2;
$sql= "INSERT INTO
user(applicationtype,
surname,givenname,
title,dob,gender,nationality,
cob,passportnumber,pid,ped,
residenceinsrilanka,processeta,
multipleentryofsrilanka,intentedarrivaldate,
purposeofvisit,finaldestination,staydays,address,
city,state,postalcode,country,addinsrilanka,email,
alternateemail,telephonenos,mobilenos,faxnos)
VALUES('$eta_type','$lastname','$firstname','$title1',
'$date1','$gender','$nationality','$cob',
'$passportnumber','$date2','$date3','$residence',
'$possesseta','$multipleentry','$date4','$purpose',
'$final_dest','$stay_days','$address','$city',
'$state','$pscode','$country','$addlanka','$email',
'$alternate_email','$phone','$mobile','$fax')";
$query = mysqli_query($conn, $sql);
if($query)
{
header("Location: continue-to-pay.php?pno=$passportnumber");
}
else
{
echo "<h4 style='color:red'>Failed.</h4>";
}
}
?>
Incredibly dangerous code...
Read some about query injection....
Any value passed this way can break your query.
You need to escape your values with mysqi_escape_string()
http://php.net/manual/fr/mysqli.real-escape-string.php

Chart Js clickable bar

I want to make my chart js bar clickable. I want to add click features such as links. No idea how to proceed. Have read documentation times 10...
<script> var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Now', '-1h', '-2h', '-3h', '-4h', '-5h', '-6h', '-7h', '-8h', '-9h', '-10h', '-11h', '-12h', '-13h', '-14h', '-15h', '-16h', '-17h', '-18h', '-19h', '-20h', '-21h', '-22h', '-23h'],
datasets: [{
label: 'Litraa',
data: [<?php echo "$chart_readings[0]";?>, <?php echo "$chart_readings[1]";?>, <?php echo "$chart_readings[2]";?>, <?php echo "$chart_readings[3]";?>, <?php echo "$chart_readings[4]";?>, <?php echo "$chart_readings3[5]";?>, <?php echo "$chart_readings3[6]";?>, <?php echo "$chart_readings[7]";?>, <?php echo "$chart_readings[8]";?>, <?php echo "$chart_readings[9]";?>, <?php echo "$chart_readings[10]";?>, <?php echo "$chart_readings[11]";?>, <?php echo "$chart_readings[12]";?>, <?php echo "$chart_readings[13]";?>, <?php echo "$chart_readings[14]";?>, <?php echo "$chart_readings[15]";?>, <?php echo "$chart_readings[16]";?>, <?php echo "$chart_readings[17]";?>, <?php echo "$chart_readings[18]";?>, <?php echo "$chart_readings[19]";?>, <?php echo "$chart_readings[20]";?>, <?php echo "$chart_readings[21]";?>, <?php echo "$chart_readings[22]";?>, <?php echo "$chart_readings[23]";?>],
backgroundColor: "rgb(255, 255, 255)"
}]
},
options: {
tooltips: {
mode: 'label'
}
}
});
/*Global settings*/
Chart.defaults.global.defaultFontColor = '#fff';
</script>
If you are using chart.js version 2.4+ (maybe earlier), there is a onclick event that is very useful. I'm using it on a stacked bar chart, so it should work for you too. You can find it under common chart configuration in the documentation. (See: https://www.chartjs.org/docs/latest/charts/bar.html#stacked-bar-chart)
options:{
onClick: graphClickEvent
}
function graphClickEvent(event, array){
if(array[0]){
foo.bar;
}
}
Hope this helps.

Undefined but existing

Here's my code:
js
var priorities = {
banner: '300',
avatar: '301'
};
var editableDiv = $('*[data-edit]');
editableDiv.append('<div class="overlay-edit"></div>');
editableDiv.each(function(index, value) {
var actualPriorities = value.getAttribute("data-edit");
console.log(actualPriorities);
console.log(priorities[actualPriorities]);
});
html/php
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "=" . $value . "&nbsp";
}
}
?>
>
$this->htmlOptions contains
array('data-edit' => 'avatar')
The output :
banner
300
avatarĀ 
undefined
I do not understand why my last result is undefined. When I'm trying
priorities['avatar']; // ouput is 301
The output is good.
The problem is the no breaking space character, and you can improve the code wrapping in quotes:
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "='" . $value . "' ";
}
}
?>
Note that I change the with the ' (with a real space to separate the attributes)

Only can load one Zingchart

i have a problem that i can only load 1 zingchart in my web even though i have codes for 2 charts.
The code will just generate the latest chart, in this case, the pie chart and ignore the bar chart.
Below are my codes
<?php
//getDBConnect function
require 'dbconnect.php';
//Get ID from form
$id = $_GET['staffid'];
//connect to database
$con = getDBConnect();
if(!mysqli_connect_errno($con)){
$sqlQueryStr =
"SELECT a.ai_Name, r.duration " .
"FROM report AS r, academicinstitution AS a " .
"WHERE r.ai_Id = a.ai_Id ";
$result = mysqli_query($con,$sqlQueryStr);
mysqli_close($con);
} else {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get data into array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
//Group array by ai_Name
$grouparray = array();
foreach($emparray as $item)
{
if(!isset($grouparray[$item["ai_Name"]]))
$grouparray[$item["ai_Name"]] = 0;
$grouparray[$item["ai_Name"]] += $item["duration"];
}
?>
<script>
var dataBar=[
<?php
foreach($grouparray as $keys => $value){
echo $value. ",";
}
?>];
window.onload=function(){
zingchart.render({
id:'chartBar',
height:400,
width:600,
data:{
"graphset":[
{
"type":"bar",
"title":{"text":"BarChart"},
"series":[
{
"values":dataBar
}
]
}
]
}
});
};
</script>
<script>
var dataPie=[
<?php
foreach($grouparray as $keys => $value){
echo '{';
echo '"text":"'.$keys.'","values":['.$value.']';
echo '},';
}
?>];
window.onload=function(){
zingchart.render({
id:'chartPie',
height:400,
width:600,
data:{
"graphset":[
{
"type":"pie",
"title":{"text":"PieChart"},
"series":dataPie
}
]
}
});
};
</script>
<div id="chartBar"></div>
<div id="chartPie"></div>
What should i do?
The issue here is that you've assigned two functions to the window.onload event. JavaScript only allows one function to be called when that event fires. If you assign multiple functions to it, the latest assignment will overwrite any previous ones. That's why your pie chart is rendering but not your bar chart.
The solution is to put both render calls inside the window.onload callback.
Here's what that looks like:
<script>
var dataBar=[
<?php
foreach($grouparray as $keys => $value){
echo $value. ",";
}
?>];
var dataPie=[
<?php
foreach($grouparray as $keys => $value){
echo '{';
echo '"text":"'.$keys.'","values":['.$value.']';
echo '},';
}
?>];
window.onload=function(){
zingchart.render({
id:'chartBar',
height:400,
width:600,
data:{
"graphset":[
{
"type":"bar",
"title":{"text":"BarChart"},
"series":[
{
"values":dataBar
}
]
}
]
}
});
zingchart.render({
id:'chartPie',
height:400,
width:600,
data:{
"graphset":[
{
"type":"pie",
"title":{"text":"PieChart"},
"series":dataPie
}
]
}
});
}
</script>
I'm on the ZingChart team. Holler if you have any more questions.

Categories

Resources