Google charts from MYSQL database - asp.net-web-api

This is set up with a form that input either female or male varchar into a MySQL table with only one Colom that is called Gender I need this to look at that data using google charts to make a pie chat with the number of females compared to the number of males. their are lot of tutorial but they all seem to use a different type of connection them me I have the PDO connection so please help
I'm like 90% sure the error is in my drawchart function
PS: please have mercy on me I am new to coding :) (no hate)
this code is being hosted at http://webapi.mycscihw.com/
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>web api HW</title>
<?php
// db connection
$db = new PDO ('mysql:host=50.62.209.160:3306;dbname=jmthom1353_chat;', 'jmthom1353', 'dog123');
$final = $db->query("SELECT GENDER, count(*) as number FROM MORF GROUP BY GENDER");
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
<?php
while($row = $final->fetch(PDO::FETCH_ASSOC))
{
echo "['".$row["gender"]."', ".$row ["number"]."],";
}
?>
]);
       
        // Set chart options
        var options = {
title: 'Percentage of Male and Female ',
//is3D:true,
pieHole: 0.4
};
        // Instantiate and draw our chart, passing in some options.
       var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
      }
    </script>
</head>
<!DOCTYPE html>
<body>
select gender:
<form action="" method="post">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
<?php
if (isset($_POST['gender'])){
$gender = $_POST['gender'] ;
$success= $db->prepare("INSERT INTO `MORF` (`GENDER`) VALUES ('$gender')" );
$success->execute();
echo 'a '.$gender.' was added';
}
else
{
echo "<font color='red'>no gender selected</font>";
}
?>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</div>
</body>
</html>

Related

PHPExcel attempting to read Excel file using ajax() call is failing

I am attempting to read an Excel File using PHPExcel Lib through an ajax call. However, the read attempt is causing an error of PHPExcel_Reader_Exception: Could not open for reading! File does not exist.
My index.php is as follows:-
<?php
ob_start();
ini_set("xdebug.var_display_max_children", -1);
ini_set("xdebug.var_display_max_data", -1);
ini_set("xdebug.var_display_max_depth", -1);
session_start();
if ( isset($_POST['label']) ) {
var_dump($_POST['label']);
}
?>
<!doctype html>
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script>
var label;
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls");
var fileExt = sender;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
} else return true;
}
$(function() {
$(document).on('change', ':file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {
if(checkfile(label)== true){
var input = $(this).parents('.input-group').find(':text'),
log = label;
if(input.length) {
input.val(log);
} else {
// if(log) alert(log);
}
}
$.ajax({
//url:"../uploadxlsx/readxlsx.php",
url:"uploadxlsx/readxlsx.php",
method:"POST",
data:{label:label },
success:function(data){
$('#sheetnames').html(data);
}
});
});
});
});
</script>
</head>
<body>
<br>
<br>
<br>
<div class="container">
<table>
<thead>
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary">
Browse <input type="file" id="uploadfile" name="uploadfile" style="display: none;" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
</thead>
</table>
</div>
<div class="input-group" name='sheetnames' id='sheetnames'>
</div>
</body>
</html>
The ajax called php file readxlxs.php is as follows:-
<?php
ini_set("xdebug.var_display_max_children", -1);
ini_set("xdebug.var_display_max_data", -1);
ini_set("xdebug.var_display_max_depth", -1);
ob_start();
include_once $_SERVER['DOCUMENT_ROOT'] . '/CommandWks/phpAssets/Classes/PHPExcel.php';
$exceldata = array();
//$inputfilename = $_POST['label'];
$inputfilename = basename($_FILES['fileName']);
var_dump($inputfilename);
$inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($inputfilename);
$excelReader = PHPExcel_IOFactory::createReaderForFile($inputfiletype);
$excelObj = $excelReader->load($inputfiletype);
$worksheet = $excelObj->getSheet(0);
$lastRow = $worksheet->getHighestRow();
var_dump($lastRow);
ob_end_flush();
?>
A screenshot of the error displayed is this
Where is the error? Or is it that PHPExcel cannot be used with ajax?
general advice
you could use browser debug console (F12 if chrome) to see if file actually got upload
you could var_dump($_FILES) to see actually what server got
this has nothing to do with begin ajax vs PHPExcel, I think you got it wrong at the basic level of how to handle form data in PHP
and on your question, since your file input is like this
<input type="file" id="uploadfile" name="uploadfile"
variable name must be
$_FILES["uploadfile"]
and "name" is just name, for actual file you'll have to use
$_FILES["uploadfile"]["tmp_name"]
read this for more info on $_FILES array structure
Array
(
[file1] => Array
(
[name] => MyFile.txt (comes from the browser, so treat as tainted)
[type] => text/plain (not sure where it gets this from - assume the browser, so treat as tainted)
[tmp_name] => /tmp/php/php1h4j1o (could be anywhere on your system, depending on your config settings, but the user has no control, so this isn't tainted)
[error] => UPLOAD_ERR_OK (= 0)
[size] => 123 (the size in bytes)
)
)

Select2 The Result Cannot Be Load in CodeIgniter

When I type in my select box the result always show "The result cannot be load". I am using CodeIgniter for my framework and select2 in my select box and am a newbie in CodeIgniter and Select2. I have already search it through all articles that can be related to my problem but it still can't work. I think I messed my ajax but I don't know how and where I should fix it.
Here is my controller
<?php
class Admin extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('admin_model');
}
function search_book(){
$booksClue = $this->input->get('booksClue');
$data_book = $this->admin_model->get_book($booksClue, 'id_book');
echo json_encode($data_book);
}
}
?>
Here is my model
<?php
class Admin_model extends CI_Model{
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->like('id_book', $booksClue);
$data = $this->db->from('book')->get();
return $data->result_array();
}
}
?>
And here is my view
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('.searchingBook').select2({
placeholder: 'Masukkan ID Buku',
minimumInputLength: 1,
allowClear: true,
ajax:{
url: "<?php echo base_url(); ?>/admin/searchbook",
dataType: "json",
delay: 250,
data: function(params){
return{
booksClue: params.term
};
},
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.id_book,
text: item.id_book
});
});
return{
results: results
};
}
}
});
});
</script>
<table>
<tr>
<td><b>ID Buku</b></td>
<td> : </td>
<td>
<select class="searchingBook" style="width: 500px">
<option></option>
</select>
</td>
</tr>
</table>
<br><br>
</body>
</html>
Big thanks for your help!
Update your model function like below:
function get_book($booksClue, $column){
$this->db->select($column);
$this->db->from('book');
$this->db->like('id_book', $booksClue);
return $this->db->get()->result_array();
}

Am trying to upload image using ajax php and jquery what am i doing wrong here

$(document).ready(function(){
$("#log").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var img = $("#img").val();
$.ajax({
url:"ajax.php",
type:"POST",
async:false,
data:{
"postD" :1,
"nameD" : name,
"emailD" : email,
"imgD" : img
},
success:function(data){
$("#name").val('');
$("#email").val('');
$("#img").val('');
}
});
});
});
function displaydata(){
$.ajax({
url:"ajax.php",
type:"POST",
async:false,
data:{
"displayP":1
},
success:function(data){
$("#datafromDb").html(data);
}
});
}
<?php
include("db.php");
$sql = "
CREATE TABLE IF NOT EXISTS temptable (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(20) NOT NULL,
PRIMARY KEY(id)
);
";
mysqli_query($connect, $sql);
if (isset($_POST['postD'])){
if(!empty($_POST['nameD']) && !empty($_POST['emailD'])&& !empty($_FILES['imgD'])) {
$emailP = $_POST['emailD'];
$nameP = $_POST['nameD'];
$imgP = $_FILES['imgD']['name'];
$tmpname = $_FILES['imgD']['tmp_name'];
$folder = "upload/";
move_uploaded_file($tmpname, $folder.$imgP);
$insert = "INSERT INTO `inserteddata` (`name`, `email`,`img`)
VALUES('{$nameP}','{$emailP}','{$imgP}')";
$qry = mysqli_query($connect, $insert);
if($qry) {
echo "inserted";
}
}else {
echo "make sure all fields are filled";
}
}
if(isset($_POST['displayP'])){
$sel = "SELECT * FROM `inserteddata`";
$res = mysqli_query($connect, $sel);
while($row=mysqli_fetch_array($res)) {
echo "Name = ".$row['name']."<br><br><br>";
}
}
?>
<?php
$connect = mysqli_connect("localhost", "root", "", "ajaxinsert");
if(!$connect) {
echo "database connection error".mysqli_error();
}else {
echo "connected successfuly<br><br><br>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ajax insert</title>
<script type="text/javascript" src="jquery-3.2.1.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<div id="datafromDb">
<script type="text/javascript">
document.write(displaydata());
</script>
</div>
<br>
<br>
<form enctype="multipart/form-data" action="" method="post">
<input type="text" id="name"><br><br>
<input type="email" id="email"><br><br>
<input type="file" id="img" name="img"><br><br>
<input type="submit" value="Login" >
<a href="" id="log" >add</a>
</body>
</html>
Am trying to upload image using ajax php and jquery what am i doing wrong here. the image should be uploaded without refreshing the page. i have tried the above code. if your see any prolem, help!!
The thing is i want to move the uploaded file to the upload folder and insert the image name to the database as a BLOB.
You can use FormData objects but you need to write the code in plain Javascript because I think JQuery doesn't support it yet. Please read this for more information https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Typeahead js Autocompletion Laravel

I try to make an autocompletion search to my laravel application , but i get an error when i inspect my browser i get " b.toLowerCase is not a function "
Here my controller for Autocomplete :
public function autocomplete(Request $request){
$data = Licencies::select("lb_nom")->where("lb_nom","LIKE","%{$request->input('query')}%")->get();
return response()->json($data);
}
Here my view Input :
#section('content')
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.1/bootstrap3-typeahead.min.js"></script>
<input class="typeahead form-control" style="margin:0px auto;width:300px;" type="text">
Here my script :
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get(path, { query: query }, function (data) {
return process(data);
});
}
});
</script>
Someone knows why i get
b.toLowerCase is not a function
Many thanks in advance
Try this:
$data = Licencies::select("lb_nom as name")

Laravel 5.2 ajax code doesn't work

I developed a simple ajax code.According to this image when click+ qty increase and when click - qty decrease
Code in online _help.blade.php
<head>
<title>Ajax Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script>
$(document).ready(function(){
$('.cart_quantity_up, .cart_quantity_down').on('click', function(e) {
e.preventDefault();
var increment = $(this).data('increase');
var itemId = $('.cart_quantity_input').val();
$.ajax({
type:'post',
url:'getmsg',
dataType:'json',
data:{
'item_id': itemId,
'increase': increment
},
success:function(data){
$("cart_quantity_input").val(data.qty);
} });
});
});
</script>
</head>
<body>
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="javascript:void(0)" data-increase="1" > + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="{{1}}" autocomplete="off" size="2">
<a class="cart_quantity_down" href="javascript:void(0)" data-increase="0" > - </a>
</div>
</body>
<footer>
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
</script>
</footer>
Code in controller function
public function ajaxl(Request $request)
{
if ($request->ajax()) {
$id = $request->item_id;
if ($request->increase) {
//$cart->increment('qty');
$qty = 2;
} else {
//$cart->decrement('qty');
$qty = 0;
}
//echo"hello ajaxlara:";
return response()->json(array('qty'=> $id), 200);
}
}
And this routes.php
Route::get('/ajax',function(){return view('online_help');});
Route::post('/getmsg','Hello#ajaxl');
When I click + or - the value doesn't change and no error.
Please any one help me
The problem is very small.
This line:
$("cart_quantity_input").val(data.qty);
just you forgot to add . before cart_quantity_input
So change it to be :
$(".cart_quantity_input").val(data.qty);

Resources