How to save html values to MySQL using ajax? - javascript

I'm trying to make an HTML table dynamically. I'm just testing with sample, but It's not working as well as I expected. So, I'm asking this question. Let me show you this simple table, it is MySQL database. and I create HTML table.
What I want to do is when I click some node, like a '250', this number will be editable. Edited data will be saved to the MySQL database. So I use the contenteditable="true" attribute value, and when this node loses focus, run some JavaScript function that new data will be saved.
But... It's not working well. Honestly I don't know what the problem is exactly. Google chrome spit up "Uncaught Syntax Error, Unexpected token } ", But I couldn't find what the actual problem is. I'm newbie on this... Could you some guys help me?
sample.html
<body>
<?php
require_once("db_connect.php");
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
?>
<table border="1" style="border-collapse:collapse;">
<thead>
<tr><th>name</th><th>price</th></tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc()){
echo
"<tr>
<td contenteditable='true' onBlur='saveToDatabase(this,'name','$id')'>{$row['name']}</td>
<td contenteditable='true' onBlur='saveToDatabase(this,'price','$id')'>{$row['price']}</td>
</tr>\n";
}
?>
</tbody>
</table>
<script>
function saveToDatabase(editableObj, column, id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
</body>
</html>
saveedit.php
<?php
require_once("db_connect.php");
$result = mysql_query("UPDATE test SET ". $_POST["column"]. " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);
?>

You made it contenteditable but PHP needs an parameter. For example
<input type="text" name="parameter">
will send as $_POST['parameter'] but in your code <td> elements don't have a name. So PHP doesn't know if there is a parameter or what name is.
Maybe you can write your own editable function in Javascript like this:
function doTextArea(i) {
document.getElementById(i).innerHTML="<input type='text' name='table_value'>ssss.";
}
and your php loop can be like this ( I assume it is for loop):
for ($i = 1; $i <= 10; $i++) {
echo
"<tr>
<td><p id=$i ondblclick='doTextArea($i)'> sadasdasdasd</p></td>
</tr>\n";
}

Related

Read new update from database and then execute PHP code - AJAX

I'm currently studying a telegram chatbot and I got this idea that I want the bot to send only new data if there is new data in my database which is MySQL and it won't execute the PHP code if there is no new data. But I can't figure out how to do it, for now, I use the meta http-equiv= "refresh". Is there any other method that does something that I need to implement?
I tried to use AJAX long polling method but I don't really understand how to implement it on my project, but I think it might solve my problem. And I already tried to auto-refresh the page every 10 minutes, it works but it will spam the chat with the same data every 10 minutes if there is no new data.
For now this is my code for executing the chatbot so that it will send my data.
<?php
$orang = $db->query('SELECT time_stamp,group_name, message, nvalue, old_svalue, inactive_timestamp, ack_timestamp
FROM alarm ORDER BY time_stamp DESC LIMIT 2');
//$arrayAll = [];
foreach($orang as $orn){
$data = implode(" ",$orn);
$arrayAll[] = $data;
}
//new update function
//execute dibawah
if($orn["nvalue"] < 30){
echo "Tidak dikirim";
}else{
$arrayAll = implode("\n", $arrayAll);
$response = $telegram->sendMessage([
'chat_id' => "$idChat",
'text' => "\n$arrayAll",
'parse_mode' => 'HTML'
]);
}
?>
This is my HTML for showing the data on the database
<body>
<table>
<tr>
<th>Message</th>
<th>Group Name</th>
<th>Time Stamp</th>
</tr>
<?php
foreach($orang as $org){
?>
<tr>
<td>
<?php echo $org["message"];?>
</td>
<td>
<?php echo $org["group_name"];?>
</td>
<td>
<?php echo $org["time_stamp"];?>
</td>
<?php
}
?>
</tr>
</table>
</body>
Thank you.

Getting the value of dropdownlist in php

I have the following the html/php code :
<!DOCTYPE html>
<html>
<head>
<title>Voiture</title>
</head>
<body>
Welcome<br>
<form method="post" action="">
Liste de voiture<select name="selected" id="selected">
<?php
$sql = 'select Type from voiture';
$result = $conn->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['Type'], $json)){
$json[] = $row['Type'];
echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
}
}
?>
</select> <br>
<span id="sel" name="sel"></span>
<table border="1">
<tr id="header">
<td>Type</td>
<td>Model</td>
<td>Couleur</td>
<td>Prix</td>
<td>User</td>
<td>Action</td>
</tr>
</table>
<input type="submit" name="submit" hidden>
</form>
<script src="jquery-3.2.1.js"></script>
<script>
$(function(){
$('#selected').on('change',function(){
$('#sel').text(document.getElementById('selected').value);
$.getJSON('phpVoiture.php',function(data){
for (var x = 0 ; x < data.length ; x++){
$('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
'</td><td>'+data[x]['Couleur']+'</td>'+
'<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
}
});
});
});
</script>
</body>
</html>
And the following php page :
<?php
require_once ('./dbConnect.php');
include ('./Voiture.php');
$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$json[] = [
'type' => $row['Type'],
'model' => $row['Model'],
'couleur' => $row['Couleur'],
'prix' => $row['Prix']
];
}
}
else{
echo mysqli_num_rows($result);
}
echo json_encode($json);
The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.
You're not sending the selected value to the server. Add it to the AJAX call:
$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
//...
});
Also, your <option> elements don't have values. You used name instead, but that belongs on the <select>. Use value:
echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
Additionally, you're using a GET request instead of a POST request. So you need to look for the value in the $_GET array:
$sel = $_GET['selected'];
You have other typos too, such as an incorrect use of a variable in PHP:
"...".sel."..."
would be:
"...".$sel."..."
Though this brings up a point about SQL injection. You really shouldn't be directly concatenating the variable like that at all. Instead, use prepared statements with query parameters.
It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet. You'll want your debugging to include two things:
Looking at your PHP logs for errors.
Using your browser's debugging tools to observe the AJAX request/response.

How to update row status with jquery change() and display in respective table

I'm facing major issue in changing status of a particular row in table with <select> tag .
I'm using jquery-Ajax so, here go functionality by this when is click on <select on any particular row for Example: Lets say i have changed the status of table row of id 2 from Pending to Delivered. On this jquery change() event triggers and it fetchs the value from 'tag' and sends the value to other file through ajax. Till here everything goes right the data goes through ajax and row with particular id's status is getting updated successfully.
But on Front end it does not change the status of the particular row. but it changes status of only first row .
Here i need it to change status of the particular row.
Note : I have searched in stackoverflow for this question. but those answere not come close to my question. Here are those links below Link 1link2link3
THANK YOU IN ADVANCE
Here is the Output and i have explained details in images also
There is the full code
HTML page : index.php
<?php
include('processing.php');
$newobj = new processing();
?>
<html>
<head>
<title>Jquery Ajax select <tag> with PHP Mysql</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table border="1">
<tr>
<th>Id</th>
<th>Product name</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php echo $newobj->display();?>
</table>
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
$("#display").html(result);
}
});
});
});
</script>
</body>
</html>
AJAX HANDLER PAGE : ajaxreceiver.php
<?php
include('processing.php');
$newobj = new processing();
if(isset($_POST['statusname'],$_POST['getid'])){
$statusid = $_POST['statusname'];
$id = $_POST['getid'];
$newobj->getdata($statusid,$id);
}
?>
PHP CLASSES FILE : processing.php
<?php
class processing{
private $link;
function __construct(){
$this->link= new mysqli('localhost','root','','example');
if(mysqli_connect_errno()){
die ("connection failed".mysqli_connect_errno());
}
}
function display(){
$sql = $this->link->stmt_init();
$id=1;
if($sql->prepare("SELECT id,productname,status FROM ajaxselect")){
$sql->bind_result($id,$productname,$status);
if($sql->execute()){
while($sql->fetch()){
?>
<tr>
<td><?php echo $id;?></td>
<td><?php echo $productname;?></td>
<td><p id="display"><?php echo $status;?></p></td>
<td>
<select status-id=<?php echo $id;?> id="selectstatus" class="selectstatus">
<option>Pending</option>
<option>Delivered</option>
<option>Cancelled</option>
<option>Amount Paid</option>
</select>
</td>
</tr>
<?php
}
}
}
}
function getdata($statusid,$id){
$sql = $this->link->stmt_init();
if($sql->prepare("UPDATE ajaxselect SET status=? WHERE id=?")){
$sql->bind_param('si',$statusid,$id);
if($sql->execute()){
echo $statusid;
}
else
{
echo "Update Failed";
}
}
}
}
?>
the problem is in this line :
$("#display").html(result);
so what's going here ?
you are creating display id for every row, which is not good practice to do , specially in your particular .
there are various solutions for this problem ,
1)
("#display", $(this).parent().parent()).html(result);
here you are going to apply the action to particular ID which is belongs to the parent of the parent of the particular class which had received the change action
2)
giving the display row unique id for each row
for example like follows :-
<td><p id="display_<?php echo $id; ?>"><?php echo $status;?></p></td>
and then apply your action to it directly ,
$("#display_" + getid).html(result);
3)
and this solution is similar to the past one , by giving the parent <tr> a unique id
for example :-
<tr id='parent_<?php echo $id; ?>'>
and then apply your action it from your ajax like this
$("#display", $('#parent_' + getid)).html(result);
or even :
$('#parent_' + getid + ' #display').html(result);
Yes there is problem in $("#display").html(result); line because id ($("#display")) always select first element found in the DOM you can fix it by - following code-
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
// make jquery object that make reference to select in which click event is clicked
$this = $(this);
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
// this refer to the ajax callback function so we have to use $this which is initialized before ajax call
$($this).parents('tr').find("#display").html(result);
}
});
});
});
</script>

Collecting AJAX generated text box values with JavaScript

My script’s AJAX calls the following PHP file and prints a table with $attrib and text boxes.
Can somebody tell me how to collect the $attrib and text box in an array or something like that?
Code tried is giving values like "assetattrib%5B%5D=model". So please help me to correct this or show me a new way to do the same.
echo "<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id=addattrib >";
while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib'];
echo "<tr bgcolor='white'>
<td class='value'>$attrib</td>
<td class='value'><input type=text name=assetattrib[] value = '' </td>
</tr>";
}
echo "</table>";
echo "<input type=submit name='btnSaveAsset' id = 'btnSaveAsset' value='Save' >";
I tried the code below.
$(document).on("click", "#btnSaveAsset", function() {
$(document.getElementsByName('assetattrib[]')).each(function() {
var x = $(this).serialize();
alert(x);
});
});
IMPORTANT:
PHP mysql_ extension is deprecated and using it represents a major security issue. According to php.net
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used.
Now the actual answer:
I suggest some changes in your HTML, if you can make them:
Wrap the table where the <input>s are into a <form> element
Give the generated <input>s the name attribute given by $attrib, for example <input name="user" />
If you cannot modify the PHP/HTML code let me know and we'll find a workaround
I updated your jsfiddle using this changes. Your PHP code should end up like this:
<form id="btnSaveAsset" onsubmit="return false;">
<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id='addattrib'>
<?php while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib']; ?>
<tr bgcolor='white'>
<td class='value'><?php echo $attrib; ?></td>
<td class='value'><input type='text' name='<?php echo $attrib; ?>' /> </td>
</tr>
<?php } ?>
</table>
<input type=submit name='btnSaveAsset' id='btnSaveAsset' value='Save' />
</form>
Then, you collect your data with one of this options:
$(document).on("click", "#btnSaveAsset", function () {
var data = $("#myForm").serializeArray();
console.log(data); // Array of objects
});
OR
$(document).on("click", "#btnSaveAsset2", function () {
var tempData = $("#myForm").serializeArray();
var data = {};
$.each(tempData, function () {
data[this.name] = this.value;
});
console.log(data); // Just an object
});
Here is the jsfiddle updated: http://jsfiddle.net/jormaechea/sy0wx8gb/1/
Check your JS console (Press F12 and go to Console tab) to see the results.

How to auto fill a form with data from database based on drop menu selection

I'm working on a MySQL update form and struggle to make a drop down selectbox that will autofill the rest of the form with data from mysql. Basically its a table that consist of users and their credentials. When updating a second table with this form i want to be able to select the username from a drop menu and let that selection autofill the rest of the credentials before moving on to the rest of the form.
Here is some of the code for setting up the select and input:
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" />
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" /> </td>
</tr>
And then some javascript
<script>
function populateData()
{
//alert('in populateData');
y = document.getElementById("selectbox");
document.getElementById("klasse").value = [y.selectedIndex];
document.getElementById("klubb").value = [y.selectedIndex];
}
</script>
The result here is a number in the <td>klubb and <td>klasse based on my selection in the drop menu.
How can i connect the arrays with that index number in the javascript so that it will show the actual data from the array ?
I've been seeking an answers for a few days now but can't find anything that answers my question.
Thanks for any help!
Well you can use AJAX for that.
For a tutorial on how to use AJAX and PHP script with Mysql This can help you.
First you need to create a PHP script that will gather the data you need for filling up the forms.
Setup the AJAX to be triggered everytime you choose something in your Drop Down List and pass its value on the PHP script you created.
On your AJAX script configure it to call the PHP script you created for retrieving the data (a value will be thrown in this script based on your drop down list).
Once you receive a response from your AJAX call just use a simple Javascript to fill up the forms based on the data your received.
Another tip is to use JQuery since it is easier for you to setup your AJAX request.
Use AJAX here.
In the populateData() function, use ajax to send the request to retrieve the user credentials & through Javascript, populate your textboxes with the retrieved values.
You could echo the two php arrays as javascript objects, and then access those in your populate function (this is the quick solution). But a better way is to ajax in the actual data
<script>
var klasse = <?=json_encode($klasse)?>
var klubb = <?=json_encode($klubb)?>
</script>
Well you can use Ajax. Make this as your form.
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<div id="some_container">
</div>
Your AJAX request :-
<script type="text/javascript">
$('select').on('change', function() {
var selectedVal = this.value; // or $(this).val()
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?selectedVal="+selectedVal,
dataType: "html", //expect html to be returned
success: function(response){
$("#some_container").html(response);
}
});
});
});
</script>
file.php
<?php
echo '
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" value="$phpValueHere"/>
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" value="$phpValueHere> </td>
</tr>';
?>
In your file.php, get the value of selectedVal via $_GET['selectedVal'] and then extract data from table, after extracting echo the data in those input boxes.

Categories

Resources