Using PHP connecting mysql and Knockout - javascript

I am trying to connect MySQL database using PHP as a REST API and Knockout JS to display the database in the UI. I am able to make a connection from database to PHP and query the data. As am new to knockout, I am not sure on how to display the data properly using Knockout. Please find my code below. Thanks for your help in advance.
PHP Code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employeedb";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT `id`, `firstname`, `lastname`, `currentAddress`, `permanentAddress` FROM `employeedata` WHERE 1";
$result = $conn->query($sql);
$records = array();
while($row = $result->fetch_array()) {
$records[] = array(
'id' => $row['id'], 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'currentAddress' => $row['currentAddress'], 'permanentAddress' => $row['permanentAddress']
);
}
echo json_encode($records);
?>
JS Code:
var dataModel = function () {
var self = this;
this.employeeRecord = ko.observableArray([]);
// Display Records
this.displayRecord = function () {
$.ajax({
type : 'GET',
datatype: "json",
url: "js/phpapi.php",
success: function (data) {
var id = data['id'];
var firstname = data['firstname'];
var lastname = data['lastname'];
var currentAddress = data['currentAddress'];
var permanentAddress = data['permanentAddress'];
self.employeeRecord.push(data);
}
});
};
this.displayRecord();
console.log (self.employeeRecord());
};
ko.applyBindings(new dataModel());
I am able to 'GET' the 'URL' correct but the entire data is displayed in array [0]. Let me know if I am missing something.
Output: when console.log (data)
"[{"id":"1","firstname":"Test Data","lastname":"number 1","currentAddress":"Temporary Current Address 1","permanentAddress":"Permanent Address 1"},
{"id":"2","firstname":"Test Data","lastname":"number 2","currentAddress":"Temporary Current Address 2","permanentAddress":"Permanent Address 2"}]"

Related

How to pass variable from controller to ajax request in view and then retrieve it in php script (codeigniter)

Hello I want to pass this variable: ID_person to view and then send it to php script to get requested data from database.
Controller:
public function view($id){
$data = array();
if(!empty($id)){
$data['zakaznici'] = $this->Zakaznici_model->getRows($id); //$data['temperatures'] = $this->Temperatures_model->getRows($id);
$data['title'] = 'Údaje o zákazníkovi';
$data['ID_person'] = $id;
$this->load->view('zakazniciview', $data);
}else{
redirect('/zakaznici');
}
}
So far I'm using this request in my view:
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
It is working but I need to get somehow that ID_person variable from controller and sent it to chart_vypozicky.php script and then retrieve it in query in this script.
Php script:
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID= "; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Is it somehow possible to get this done? I will be really thankful for all suggestions.
In your view pass ID_person and then Use $_GET['ID_person'] in chart_vypozicky.php page
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
data:{ID_person:'<?php echo $ID_person; ?>'},
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$person_ID=$_GET['ID_person']
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID='".$person_ID."'"; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Use this updated code

retrieve json array from php json decode

i have a javascript to create json array and it has a ajax post method, i have to know how this json array should decode in the php side?
My javascript function:
var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"datee" : "2017-09-09" ,"total" : tot }], invoiceLine: []};
for(i=1; i<=count+arr.length-1; i++){
var ss = String(i);
if(arr.includes(ss)){
continue;
}
invoices.invoiceLine.push({
"itemName" : document.getElementById('item'+i).value ,
"qty" : document.getElementById('inputQty'+i).value ,
"value" : document.getElementById('value'+i).value
});
}
$.ajax({
type: "POST",
url: "saveInvoice.php",
data: {json : JSON.stringify(invoices)},
cache: false,
success: function(data) {
alert(data);
location.reload();
}
});
and this is my php:(it will not save data to the database. I want first invoice data to save in the database for now. Then i can use invoiveLine data to another table inserting.)
$dbhost = "localhost";
$dbuser = "root";
//$dbpass = "dbpassword";
$dbname = "inventory";
$jsonInvoice = json_decode($POST['invoices'],true);
$customerName = $jsonInvoice.["invoice"][0].["customerName"];
$reciptionName = $jsonInvoice.["invoice"][0].["reciptionName"];
$date = $jsonInvoice.["invoice"][0].["datee"];
$total = $jsonInvoice.["invoice"][0].["total"];
mysql_connect($dbhost, $dbuser, '');
mysql_select_db($dbname) or die(mysql_error());
$query = "insert into invoice (customerName,reciptionName,date,total) values ('$customerName','$reciptionName','$date',$total)";
$qry_result = mysql_query($query) or die(mysql_error());
$insertId = mysql_insert_id();
echo $insertId;
Could you try this:
$customerName = $jsonInvoice["invoice"][0]["customerName"];
I think that you are getting sintax errors, caused by dots.
json_decode returns an array, you have to access the attributes in the way that I wrote above. (see this for further info)
Also, take care of the recommendations that other users gave you about mysqli

How to insert jstree checkbox value into database

<script type="text/javascript">
$(document).ready(function(){
//fill data to tree with AJAX call
$('#tree-container').jstree({
'plugins': ["wholerow", "checkbox"],
'core' : {
'data' : {
"url" : "response.php",
"dataType" : "json" // needed only if you do not supply JSON headers
}
}
})
});
</script>
<div id="tree-container"></div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "defectsystem";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM `treeview_items` ";
$res = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_assoc($res) ) {
$data[] = $row;
}
$itemsByReference = array();
// Build array of item references:
foreach($data as $key => &$item) {
$itemsByReference[$item['id']] = &$item;
// Children array:
$itemsByReference[$item['id']]['children'] = array();
// Empty data class (so that json_encode adds "data: {}" )
$itemsByReference[$item['id']]['data'] = new StdClass();
}
// Set items as children of the relevant parent item.
foreach($data as $key => &$item)
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
$itemsByReference [$item['parent_id']]['children'][] = &$item;
// Remove items that were added to parents elsewhere:
foreach($data as $key => &$item) {
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
unset($data[$key]);
}
// Encode:
echo json_encode($data);
?>
I had successfully create a jstree with checkbox. However, how I can insert the checkbox value into the database when I click it and submit.
Thankss if anyone could help me!! If any question can ask me below comment.
Try some thing like this:
var array = [];
// create an array
$.each($("input[name='user_permission']:checked"), function(){
permissions.push($(this).val());
});
// Iterate over each checkbox which is checked and push its value in the array variable.
Ex:
......
var permissions = [];
$.each($("input[name='user_permission']:checked"), function(){
permissions.push($(this).val());
});
$.ajax({
url : 'add_permission.php',
method : 'post',
data :
{
permissions : JSON.stringify(permissions)
}
....
});
// After complete iteration you will get the value of each checked checkbox.
Now insert it in database using ajax call

$_GET PHP is misbehaving

I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.
The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";

How to save my jquery array to php using ajax

I have a script that gets the contents of a table that i added.
And i want to do is save the content into a database.
In the picture the table and the content of my dataSet variable that i get from the table.
i check the dataSet and alert it to check if it has value.
My problem is im having trouble saving the array that i passed to php cause its not working its not saving. I got an error in my saveTable.php invalid argument foreach.
script:
var names = [].map.call($("#myTable2 thead th"), function (th) {
return $(th).text();
});
var x = [].map.call($("#myTable2 tbody tr"), function (tr) {
return [].reduce.call(tr.cells, function (p, td, i) {
p[names[i]] = $(td).text();
return p;
}, {});
});
var dataSet = JSON.stringify(x);
alert(dataSet);
$.ajax(
{
url: "saveTable.php",
type: "POST",
data: { tableArray: dataSet},
success: function (result) {
}
});
saveTable.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tableArray = isset($_REQUEST['tableArray']) ? $_REQUEST['tableArray'] : "";
$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES (:name, :age, :gender, :action)";
$sth = $dbc->prepare($sql);
foreach( $tableArray As $v){
$sth->bindValue(':name', $v[0], PDO::PARAM_STR);
$sth->bindValue(':age', $v[1], PDO::PARAM_STR);
$sth->bindValue(':gender', $v[2], PDO::PARAM_STR);
$sth->bindValue(':action', $v[3], PDO::PARAM_STR);
$sth->execute();
}
?>
new error:
It looks that you are trying to use a String type in the foreach loop. Try:
$tableArray = isset($_REQUEST['tableArray']) ? json_decode($_REQUEST['tableArray']) : array();
This should make it work. Good luck, hope this helps!
You have to convert the string to an array using json_decode to be able to use it as an array.

Categories