result of my js calculation is not stored in mysql - javascript

Good day,
I experimented with a simple JS math calculation.
this calculation works as expected, but additionally I wanted to store the math calculation in a database where all values (the input fields and the result .textContent) should be stored. Afterwards the calculation should be named and populated by a dropdown menu, but that's a different story.
So, I added some nice ajax code, see this: https://phppot.com/php/php-mysql-inline-editing-using-jquery-ajax/
Everything works as expected, the only issue I have is that I don't get the result of the math automatically updated into the database, so if I change the math input fields or refresh the site, the result is lost.
I put up an live example with mysql backened to show you exactly what I mean:
http://90.153.105.10:8888/djdp42Bjjr39399nfjjj39xleit832991vnJ39921/live/test.php
dbcontroller.php:
<?php
class DBController {
private $host = "ip";
private $user = "root";
private $password = "thepassword";
private $database = "the database";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function executeUpdate($query) {
$result = mysqli_query($this->conn,$query);
return $result;
}
}
?>
saveedit.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = $db_handle->executeUpdate("UPDATE database_table set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);;
?>
test.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj) {
$(editableObj);
}
function saveToDatabase(editableObj,column,id) {
$(editableObj);
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj);
}
});
}
</script>
</head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style>}
</style>
<body>
<table class="tbl-qa">
<tr>
<td >DESCRIPTION:</td>
<td contenteditable="true" id="Event" onBlur="saveToDatabase(this,'event','0')" onClick="showEdit(this);">This is a simple stored description for the following math. As you can see, the result and math values are editiable. But the RESULT is not beeing stored nor will it get calculated when refreshing the site :/<br></td>
</table>
<hr>
<table class="tbl-qa">
<tr>
<td>VALUE 1:</td>
<td contenteditable="true" id="Tank" size="2" oninput="output();output2();output3();" onBlur="saveToDatabase(this,'Tank','0')" onClick="showEdit(this);">10</td>
<td>VALUE 2:</td>
<td contenteditable="true" id="Spritverbrauch" size="2" oninput="output();output3();" onBlur="saveToDatabase(this,'Spritverbrauch','0')" onClick="showEdit(this);">2</td>
</tr>
<tr>
<p></p>
<td>RESULT: </td>
<td contenteditable="true" size="2" id="StintlangeRd" oninput="output();output3();" onBlur="saveToDatabase(this,'StintlangeRd','0')" onClick="showEdit(this);"></td>
</tr>
</table>
<script type="text/javascript">
function output(){
var value2 = document.getElementById('Tank').textContent;
var value3 = document.getElementById('Spritverbrauch').textContent;
document.getElementById('StintlangeRd').innerHTML = (parseFloat(value2) / parseFloat(value3)).toFixed(2);
}
</script>
<script type="text/javascript">
setTimeout(function(){
location.reload();
},60000);
</script>
</body>
</html>

After updating try to run a query with 'COMMIT' to confirm the update on mysql database!

You could check if the values arrive at your update script. I think the problem may lie within your AJAX call:
function saveToDatabase(editableObj,column,id) {
$(editableObj);
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj);
}
});
}
Inside this function, you set the data by passing a query string. Instead of a query string, you should use a plain old javascript object.
data: {
column : column,
editval : editableObj.innerHTML,
id : id
},

Change Ajax Post Data you are sending data in GET method and trying to get data by POST Method
function saveToDatabase(editableObj,column,id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data: {
column : column,
editval : editableObj.innerHTML, // just check it or use $(editableObj).html() if necessary
id : id
},
success: function(data){
// you will get your response here which is sent from server
}
});
}

Related

How to view data from DB with AJAX immediately after script counts it?

I am practising AJAX by implementing editable HTML table looking like this:
The logic is this:
User clicks on left column (containing integer);
JS script catches its value and by using AJAX adds them to database;
PHP script fetches this value, makes some calculations, adds them to database and shows result in right column (date in <td>).
Now as expected PHP script needs page refreshing to show calculation result (date in <td>). I'm trying to write JS script which will retrieve calculated data from database and immediately show in HTML table's cell.
Having troubles with it. Asking for help with this issue.
index.php:
<form id="form-wrap" action="functions.php" method="POST">
<select name="select1" required>
<?php
for ($i = 1; $i <= 20; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
<br>
<input type="text" id="name" name="name">
<input type="date" id="day" name="day">
<input type="submit" name="button_ok" id="button_ok" value="Write">
<input type="submit" name="show" id="show" value="Show table">
</form>
functions.php:
<?php
require_once 'dbconnect.php';
$loged = $_POST["name"];
$day = $_POST["day"];
class Count_Add_Class {
public function CountDays() {
global $day, $loged, $day_remind1, $days_before1;
$currenttime = time();
$days_before1 = $_POST["select1"];
// ... make some calculations with user's input ...
$this->AddDate();
}
public function AddDate() {
global $pdo, $loged, $day, $day_remind1, $days_before1;
if (isset($_POST['button_ok'])) {
// ... insert in database user's inpt and calculation result ...
}
}
}
$obj = new Count_Add_Class();
$obj -> CountDays();
function Count_days_new_data() {
global $pdo, $day, $loged, $day_remind1_updated,
$stmt = $pdo->prepare("SELECT select1 FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $row) {
$day_remind1_updated = $row['select1'];
}
$day_remind1_updated = $day - ($days_before1_updated * 86400);
$day_remind1_updated = date('Y-m-d', $day_remind1_updated);
}
Count_days_new_data();
function Show() {
global $pdo, $loged, $faq, $day_remind1_updated;
$stmt = $pdo->prepare("SELECT * FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$faq = $stmt->fetchAll();
$s1 = $_POST['editval'];
$id = $_POST['id'];
$stmt2 = $pdo->prepare("UPDATE tablex SET select1=? WHERE
id=?");
$stmt2->execute([$s1, $id]);
$stmt3 = $pdo -> prepare("UPDATE tablex SET day_remind1=?,WHERE
id=?");
$stmt3->execute([$day_remind1_updated, $id]);
require_once 'table.php';
}
Show();
?>
table.php:
<div id="day-data">
<tbody>
<?php
foreach($faq as $key=>$value) {
?>
<tr class="table_row">
<td><?php echo $value['name']; ?></td>
<td aria-label="First" contenteditable="true" onBlur="saveToDatabase(this,'select1','<?php echo $faq[$key]["id"];
?>')" onClick="showEdit(this);"><?php echo $faq[$key]["select1"]; ?>
</td>
<td><?php echo $value['day_remind1']; ?></td>
</tr>
<?php
}
?>
edit.js:
function showEdit(editableObj) {
$(editableObj).css("background","#FFF");
}
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat
right");
$.ajax({
url: "functions.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
show.js: (inspired by this answer)
$(".tbl tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the
clicked tr
var value = $(this).find("td")[1].text()
$.ajax({
url : "table.php",
dataType: "text",
success : function (data) {
$(".day-data").html(data);
},
error: function (data) {
(".tbl").html('No such file found on server');
}
});
});
When user clicks on HTML-table left column it is higligted well; when he changes it, data is addiing to database well. Now when page is refreshed new data is calculated, added to database and shown in HTML-table's right column.
I suppose problem is in show.js. Need some help in correcting this script!
Update1:
Added illustartion of my task's logic:
It is unfortunate, that you have everything in the functions.php file. It doesn't just count the values, it also renders the table. So when you call the function saveToDatabase, the request that you make to functions.php (and i understand it coorectly) already returns the table with the updated data (as argument of the success function). Try removing show.js and changing the success function content in edit.js from this:
$(editableObj).css("background","#FDFDFD");
to this
$(editableObj).css("background","#FDFDFD");
$(".day-data").replaceWith(data);

Return json array from PHP to jQuery AJAX

Im trying to do something experimental. i would want to search product in MySQL database by product name and retrieve price in 'price input', sell price in 'sellprice input'.
example picture
Everything is ok, except retrieve fetch.php array as javascript variable to get price and sellprice input value.
i tried to use json_encode in php file to get php array in javascript, still dosen't working. I don't have much knowledge about javascript. Probably I didn't coded properly thats why javascript not getting php array. Any kind of help would be appreciated. Thanks :)
index.htm
<html>
<head>
<script src="js/jquery.js"></script>
</head>
<body>
<div class="productdetail">
<table class="productdetail">
<th>Product</th>
<th>Price</th>
<th>Sell price</th>
<tr>
<td><input class='product' type='text' name='product' /></td>
<td><input class='price' type='text' name='price' /></td>
<td><input type='text' class='sellprice' name=''/></td>
</tr>
</table>
<div id="result"></div>
</body>
</html>
<script>
$(function(){
$('.productdetail').delegate('.product,.price,.sellprice','keyup',function(){
var tr = $(this).parent().parent().parent();
var product = tr.find('.product').val();
if(product != '')
{
$.ajax({
url:"fetch.php",
method:"post",
data:{product:product},
dataType:"text",
success:function(data)
{
console.log(price);
var price = jQuery.parseJSON(price);
console.log(sellprice);
var sellprice = jQuery.parseJSON(sellprice);
//var price = "test price";
//var sellprice = "test sell price";
tr.find('.price').val(price);
tr.find('.sellprice').val(sellprice);
$('#result').html(data);
}
});
}
});
});
</script>
fetch.php
<?php
$product = strtolower($_POST["product"]);
require_once ('db.php');
$sql = "SELECT * FROM tbproduct WHERE product LIKE '$product'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) { {
$array = array(
'price' => $row["price"],
'sellprice' => $row["sellprice"],
);
echo json_encode($array);
}
}
} else {
echo 'Data Not Found';
}
?>
i got it. Working now :)
$(function(){
$('.productdetail').delegate('.product,.price,.sellprice','keyup',function(){
var tr = $(this).parent().parent().parent();
var product = tr.find('.product').val();
if(product != '')
{
$.ajax({
url:"fetch.php",
method:"post",
data:{product:product},
//dataType:"json",
success:function(data)
{
var getarray = jQuery.parseJSON(data);
var price = getarray.price;
var sellprice = getarray.sellprice;
tr.find('.price').val(price);
tr.find('.sellprice').val(sellprice);
//$('#result').html(data);
}
});
}
});
});
Try to replace the price argument in ajax with data eg
$.ajax({
url:"fetch.php",
method:"post",
data:{product:product},
dataType:"text",
success:function(data)
{
console.log(data);
var price = jQuery.parseJSON(data);
Then console the data
I think that the two arrays that you want is the data[0] and data[1]

AJAX cannot print elements onclick

I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?
Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].

Update database with onClick (NewB)

Thanks for the help mighty Johan. but I cant get get my db to update. If you do have time please look over my two files and tell me what the F is wrong
my hire_staff.php
<?php
session_start();
include("header.php");
?>
<?php
$chief_aerodynamicist = $staff['chief_aerodynamicist'];
$chief_designer = $staff['chief_designer'];
$commercial_director = $staff['commercial_director'];
$pit_crew = $staff['pit_crew'];
$technical_director = $staff['technical_director'];
?>
<head>
<script>
function bye(){
alert('bye');
}
$(document).ready(function(){
function hire(){
$.ajax({
url: "update.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
}
});
</script>
</head>
<center><h2>You can hire new staff here</h2></center>
<table cellpadding="3" cellspacing="5">
<tr>
<td>Chief Aerodynamicist:</td>
<td><i><?php echo "Level $chief_aerodynamicist"; ?></i></td>
<td><form><input type="button" value="Hire!" onClick="hire();"</form></td>
</tr>
<tr>
<td>Chief Designer:</td>
<td><i><?php echo "Level $chief_designer"; ?></i></td>
</tr>
<tr>
<td>Commercial Director:</td>
<td><i><?php echo "Level $commercial_director"; ?></i></td>
</tr>
<tr>
<td>Pit Crew:</td>
<td><i><?php echo "Level $pit_crew"; ?></i></td>
</tr>
<tr>
<td>Technical Director:</td>
<td><i><?php echo "Level $technical_director"; ?></i></td>
</tr>
</table>
<?php
include("footer.php");
?>
My test1.php file
<?php
include("functions.php");
connect();
if(isset($_POST['uid'])){
connect();
mysql_query("UPDATE `staff` SET `driver` = '3' WHERE `id`='".$_SESSION['uid']."'") or die(mysql_error());
$query = mysql_query("SELECT FROM `staff` WHERE `id`='".$_POST['uid']."'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
?>
its actually the staff in the 's that I want to update but driver is also in the same table
Use jQuery and Ajax:
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "update.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
//the button
<input type="button" id="button" value="Hire!"/>
//update.php
if(isset($_POST['uid'])){
//connect to the db etc...
mysql_query("UPDATE `staff` SET `driver` = '3' WHERE `id`='".$_POST['uid']."'") or die(mysql_error());
//this'll send the new statistics to the jquery code
$query = mysql_query("SELECT FROM `staff` WHERE `id`='".$_POST['uid']."'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
with "update some fields" in the success function of the ajax call, I mean that you can update the statistics on the page which you just changed in the database, so that the statistics on the webpage automatically change in both the database and on the page itself
Edit
Put this in the header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function bye(){
alert('bye');
}
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "test1.php",
type: "POST",
data: {uid: 12341234}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
</script>
Then give your button the id 'button' like this:
<form><input type="button" id="button" value="Hire!"/></form>
Make sure that the url parameter of the ajax request (url: "test1.php",) is pointing to the right php page.
I hope this helped!
Edit
This is the code if you want to select a driver:
<form><input type="button" class="button" id="3" value="Hire!"/></form> //the id is different for every guy
The javascript code:
$(document).ready(function(){
$(".button").click(function(e){
$.ajax({
url: "test1.php",
type: "POST",
data: {colID: e.target.id}, //this sends the user-id to php as a post variable, in php it can be accessed as $_POST['uid']
success: function(data){
data = JSON.parse(data);
//update some fields with the updated data
//you can access the data like 'data["driver"]'
}
});
});
});
As you can see, I changed the # into a ., I added the argument e to the callback function and I added the colID to the data object.
This'll be the new PHP code:
if(isset($_POST['colID'])){
//connect to the db etc...
$colID = mysql_real_escape($_POST['colID']); //for security
$userID = mysql_real_escape($_SESSION['uid']);
mysql_query("UPDATE `staff` SET `$colID` = 'newValue' WHERE `id`='$userID'") or die(mysql_error());
//this'll send the new statistics to the jquery code
$query = mysql_query("SELECT FROM `staff` WHERE `id`='$userID'")or die(mysql_error());
$results = mysql_fetch_assoc($query);
echo json_encode($results);
}
I hope this is what you meant :)

Set input fields value attribute from MYSQL database when selecting data from dropdown list

I'm trying send select query and set the result as value attribute for different input fields, the query should be sent upon selecting a value from dropdown list. After doing some researches I found this can be reached through jQuery.
jQuery will send request to php file which contains my query and fetch result and then return values in json format. At this point everything is working great, my php file is working and return valid json data but I cannot get these data append in the input fields I have. Here is my script that should run the php file and return the results in json then append results in text fields.
Check my code on fiddle
<script>
var flight_destination = $('#destination).text();
var flight_departure = $('#departure).text();
var flight_arrival = $('#arrival).text();
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){
var flight_destination = data[1];
var flight_departure = data[2];
var flight_arrival = data[3];
}
}
$('#destination').val(flight_destination);
$('#departure').val(flight_departure);
$('#arrival').val(flight_arrival);
})
</script>
getFlightData.php
<?php
include "dbConnect.php";
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => $row['departure'],
'arrival' => $row['arrival']
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
GOOD NEWS
A friends of mine helped me out with a syntax error in data: line. I did change it from data:'flight_number='+$('#flight_number').val(), to data:{'flight_number':$('#flight_number').val()},
In browser console window the json objects returned perfectly on change the drop down list value but still cannot append these objects to the input fields as value attribute
Update 2
Now I have this Still the data returned in the browser's console window perfectly, but the only what appended in the first text field is [object]
of the browser after selecting option from drop down list
Update 3
With great help and effort from #satyrwilder I'm now able to retrieve the first text field value. This is working version of the script snippet
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
I'm now looking forward to append the datetime-local values as well. I will keep this question updated regularly until it's 100% compelted
you must declare what type of data going to receive your inquiry.
 
dataType: "json"
$.ajax({
url: "getFlightData.php",
type: "get",
data: '?flight_number=$flight_number',
success: function(data){ ... },
dataType: "json", //<--------- this
});
Documentation of $.ajax()
And header from json in the start of you code php
For JSON:
header('Content-Type: application/json');
For JSON-P:
header('Content-Type: application/javascript');
Finally I came to the final working code where everything is working perfectly. First I'd like to thank #satyrwilder for correcting my javascript part.
Here is the final code, which appends values from database into text and datatime-local fields using jquery + php
getFlightDate.php
<?php
header('Content-Type: application/json');
include "dbConnect.php";
function datetime()
{
return date( 'Y-m-d\TH:i:s', time());
}
$flight_number = $_GET['flight_number'];
$query = mysql_query("SELECT * FROM flights WHERE flight_number='$flight_number'");
$data = array();
while($row = mysql_fetch_array($query))
{
$row_data = array(
'flight_number' => $row['flight_number'],
'destination' => $row['destination'],
'departure' => datetime($row['departure']),
'arrival' => datetime($row['arrival'])
);
array_push($data, $row_data);
}
echo json_encode($data);
?>
print.php
<?php
include "dbConnect.php";
$flight_numbers = mysql_query("SELECT flight_number FROM flights");
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Test</title>
</head>
<body>
<select id="flight_number">
<?php while($row = mysql_fetch_array($flight_numbers))
{
Print "<option>".$row['flight_number'] . "</option> ";
}
?>
</select>
<br>
<input type="text" id="destination">
<input type="datetime-local" id="departure" />
<input type="datetime-local" id="arrival" />
<script>
$(function(){
var flight_destination = $('#destination');
var flight_departure = $('#departure');
var flight_arrival = $('#arrival');
var flight_number = $('#flight_number');
$('#flight_number').on('change', function() {
var flight_info = $('#flight_number :selected').text();
$.ajax({
url: "getFlightData.php",
type: "get",
dataType: "json",
data: { 'flight_number' : flight_number.val() }
})
.done(function(data) {
$("#destination").val(data[0].destination);
$("#departure").text(data[0].departure).val(data[0].departure);
$("#arrival").text(data[0].arrival).val(data[0].arrival);
});
});
});
</script>
</body>
</html>
The trick was to change the datetime format before json_encode, because datetime-local input fields shows values in specific format which is 2014-12-05T08:30:59 -> Y-m-d\TH:i:s

Categories