Updating database when editing a field in a table - javascript

I have a table, for which the data are pulled from a database and users can edit the data in each cell. So when user edits a field of the table, how should I update the database? I have to mention for editing, I use prompt() method. Should I use ajax? I know my question is so general but I just need some clue.
Updating my question:
This is part of my code: (My table has more cells, the following is just one cell of my table).
while($array=mysql_fetch_array($res))
{
<tr>
<td >
<center>
<?php
$var=$array['Legacy Data Conversion Required?'];
if($var)
echo
"<p id=$idl>" . $var . "</p>" . "<img style ='cursor:pointer; ' class='onInput' src='http://nimbuzz007.hexat.com/icon4/icon%2015.png' id='input_img' onclick='legacyFunction($idl)'>";
else
echo
"<p id=$idl>" . " " . "</p>" . "<img style ='cursor:pointer; ' class='onInput' src='http://nimbuzz007.hexat.com/icon4/icon%2015.png' id='input_img' onclick='legacyFunction($idl)'>" ;
?>
</center>
</td>
</tr>
}
and this is part of the Javascript section:
function legacyFunction($idl) {
var data1 = prompt("Legacy Data Conversion Required?Yes/No");
if (data1 != null) {
document.getElementById($idl).innerHTML =
data1;
}
};
So when the user clicks on the edit image there will be a pop up message with input box (I used prompt() method), and after user clicks on OK button, the data in the cell of the table will change, but I also need to update the database. So how can I do that?I mean after what action should I call the ajax function to update the database?

It would be nice if you could provide your code. How is the table cell being edited? Is it with content edible or a textbox or textarea? Here is my suggestion from the information provided from you. Do this: <input type="text" oninput="save(this.value);">
function save(textValue)
{
//put your ajax request here
}
If this doesn't work then just tell me and I will try again. Good luck :-) Merry Christmas!

Create a form and set the action attribute of that form to your server side file such as writeToDatabase.php. In your form, have all the necessary inputs and fields that you want updated in your database. You may submit the form via AJAX or simply by a POST/GET method. Assuming you are using PHP for your server side, establish a connection to your database and update/write the data to the database. Here is more info:
Database connection: http://www.w3schools.com/php/php_mysql_connect.asp
Form Handling: http://www.w3schools.com/php/php_forms.asp
Updating Data: http://www.w3schools.com/php/php_mysql_update.asp

Related

Pass javaScript variable to php or workaround for just php

I'm trying to get a JavaScript variable to php without refreshing the page or submitting the form. I think my problem is that php is on the server side. I have a button that's set in a php echo...
<input type='button' value='Edit' name='editbtn' onmouseup='reply_click(this.id)' onclick='edit()' id = '" . $row['id'] . "'
This button works correctly. I didn't provide all the code surrounding it, just the part in question. I can inspect the button element in the browser and the "id" shows the correct id number.
Next I'm using some test JavaScript in an effort to get the id to php with having to refresh the page or submit the form.
echo "<script type='text/javascript'>
function reply_click(clicked_id){
var selid = clicked_id;
alert(selid);
document.writeln(selid);
} </script>";
This code works. I get the correct id to show in an alert or document.writeln. The problem comes when I try to set this to a php variable like this...
$testid = "<script type='text/javascript'>document.writeln(selid);</script>";
echo $testid;
$testid returns nothing.
Is there a way to do this or is there a workaround using only php? I need to do this without submitting the form or refreshing the page. Is that possible? The end goal is to create another MySQL statement using that id value. For example: SELECT * FROM table WHERE id = the $testid from JavaScript.
Thank you!

How to display a modal when PHP id is clicked in data table?

I have some php code fetching data from database and inserting the data into a bootstrap data table and I have a cell in a row that shows a modal.
When that button is clicked it contains and ID with child stuff that I want to show in a modal.
//#Example datatable
foreach($xx as $item) {
if($item) {
if ($item->state){
$id = $item->id;
$dname = $item->district_name;
$state = $item->state;
$city = $item->city;
$schools = $item->schools;
$students = $item->students;
global $stateId;
$stateId = $item->state_district_id;
}
}
echo ' <tr>
<td class="icon-class"></td>
<td align="center">' . $dname . '</td>
<td align="center">' . $state . '</td>
<td align="center">' . $city . ' </td>
<td align="center">' . $schools . '</td>
<td align="center">' . $students . '</td>
<td align="center">
<button onclick="myFunChild('. $stateId .')">View Schools</button>
</td>
<td align="center"><button onclick="myFunctionz(' . $id .')">Request District</button></td>
</tr>';
this is my function and I realize I'm not doing anything with the $stateId that i passed yet
function myFunChild(strg){
"use strict";
("#myModal").modal('show');
}
Then I have similar code like section: #Example datatable to fetch data from database using the $stateId
but obviously it only takes the last ID the database gives me after setting up the first data table
what I'm trying to do is taking the current/right ID of that particular row that was clicked to "View Schools"
I.E. I'm putting data into the main data table and at the same time my child table is also populating but I need to wait until a user has clicked view more to populate child table with correct ID.
How do I go about this?
Thanks!
You've passed the PHP var to JS correctly. Just reference it using the strg JS arguent and not $stateId and it will be unique each time. Everything else you want to show in JS will need to be passed through to JS as an argument to a JS function.
It's important to realize the PHP will only be processed one time. It is a backend language and runs on an entirely different machine. The JS variables are client side and can change at runtime, they have no idea what has occurred in PHP. Example: after the page loads stateId was already permanently placed in the page and is no longer accessible as a variable. To the client and JS it is now as if it was hard-coded there in the first place.
So what you have done is generated code such as:
<button onclick="showModal(1)">
<button onclick="showModal(2)">
<button onclick="showModal(3)">
This is good.
Now since JS has no idea what PHP is or that it was used to build the page, the above is all it sees. Press view source to see what javascript sees. Nothing outside of a $_REQUEST query like POST/GET is accessible to it.
So in JS you must write the function:
function showModal(id) {
alert("You clicked button " + id);
}
If you try to incorrectly write instead:
function showModal(id) {
alert("You clicked button " + $somePHPVariable);
}
Then press View Source and you will see that you have already written this function to be alert("You clicked button " + 3); before the JS code even knew what happened.
So your answer is you must use the strg in myFunChild to create a unique dialog each time.
function myFunChild(strg){
"use strict";
("#myModal" + strg).modal('show');
}
With any other data you want to pass here, it must be another argument, an array, passed through AJAX, or URL #query... somehow it must become JS accessible before it is used.

Bootstrap Modal - How to provide data from php (database)

This is probably very simple, but am learning PHP, Javascript as I go. I find it easier to learn using real examples than the contrived examples given online.
I am creating an attendance register page, based on selecting a class, then all members of that class ordered by Surname and Firstname.
The table row has it's id set, by PHP, as the record's mem_id, and contains just forename+" "+surname, and some checkboxes.
All this is working fine, but now I have been asked to add a link so that clicking on it brings up a modal containing related data for the person selected. The extra data is already in the $a_fetch array.
Have added a glyphicon link for every row and clicking it displays a modal alright, and by having a javascript function I know I can get the row index and row id
<tbody>
<?php
while($g_fetch = $a_query->fetch_array()) {
$checked = array();
$memid = $g_fetch['mem_id'];
$name = $g_fetch['firstname'].' '.$g_fetch['lastname'];
$attendences = explode(",",$g_fetch['attend']);
for ($x = 0; $x <= 12; $x++) {
if ($attendences[$x]!="0") {
$checked[$x] = 'checked = "checked"';
}
else $checked[$x] = '';
}
echo "<tr id='".$memid."'>";
echo "<td>".$name."</td>";
echo "<td align='center'><div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre'></div>";
for ($y = 0; $y <= 12; $y++) {
echo '<td align="center"><input type="checkbox" value = "" '.$checked[$y].'></td>';
}
}
unset($checked);
unset($attendences);
?>
</tbody>
</table>
I am at a loss as how to proceed - is it even possible to pass data to the modal to display related data?
If it is would I need to run a new query (SELECT), or as the row is the same index as the data in the $A_fetch, and the row id has the correct mem_id is it possible to get the data from the existing $a_fetch array using either of those, or would I need to run a new SELECT?
Many thanks
There are multiple ways to provide data to the modal - and (in my opinion) it depends on how much data you need to pass to your modal and how many rows you have.
I want to describe you two ways:
Light+Easier Solution
If you don't want to display a lot of data and you have just a few rows.
The idea is to add the data directly to each div.glyphicon (as data attributes) and then use it in the modal
In your foreach add it to your model like that:
<div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre' data-link='".$g_fetch['additional_link'] ."' data-moreInfo='".$g_fetch['moreInfo']."'></div>
You haven't posted the modal's HTML or your JS code, but you wrote you are using bootstrap, so stick to
https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content
and fetch/set the relevant data (related clicked glyphicon) as it's described.
More complex solution
For more data / more rows. The additional data is not provided in the inital loaded HTML page - Therefore not all data needs to be loaded in the beginning.
Instead the additional data is loaded via ajax when clicking on one row.
For that you need to provide an additional endpoint (php) which provides the modal content for one row.
Check out second answer in Bootstrap 3 - How to load content in modal body via AJAX?
Basically you have a php file (e.g. getAdditionalData.php)
In this file you access the mem_id via GET
$mem_id = $_GET['mem_id'];
fetch the additional data from database
and print/render out the modal content (full html like in the second answer)
And in JS (inital page) you load the modal content onClick (fetched from php with provided mem_id as parameter)
var clicked = $(e.relatedTarget);
$(this).find(".modal-body").load("%PATH%/getAdditionalData.php?mem_id="+clicked.attr("id"));
I hope it will help you solving your problem and if you need additional infos just let me know. There are more ways to archive your goal but I think this 2 possibilities are enough in the beginning :-)

jQuery responds with html table containing a (form in each row plus jquery code to edit each row) newly created forms ignore submit()

Three days and I cannot find an answer to this or a solution. I am far from being a jQuery guy.
User arrives at a php page that shows a form to choose the language code and submit. Form gets submitted and the jQuery response builds a table in a div container in the original page. So far so good. The resulting table contains hundreds of rows where the language variables can be edited. On clicking the edit button, I get nothing, no errors in console, nothing. If I use on click, I can fire an alert. On submit, bind, and many others do not work.
I am attempting to load the table, perform basic editing, submit the edits to the db, and refresh the div.table.row with the edited results. I have not gotten to the part where I refresh the rows with the edited data, still stuck trying to submit the dynamic form in each row.
One interesting thing that happens when I use on click, it works with just the first button I click on, it somehow disables all the other rows. I need to be able to submit a row for changes, have that row refresh and move on to the next row all without redirecting. Is this too much to ask? Or should I just move them from page to page?
The ajax php page returns the table using the following code:
if(!empty($_POST['edit_language']) && $_POST['edit_language'] == 1){
edit_language($_POST['lang']); //call function to edit language
} else {
echo "You got here but no variables<br>"; //testing
print_r($_POST); //testing
}
function edit_language($lang){
//query table to get language vars list
$sql = "SELECT lang_site.lid, lang_codes.iso_code, lang_codes.`language`, lang_varnames.varid, lang_varnames.varname, lang_site.varval FROM lang_codes LEFT JOIN lang_site ON lang_site.langid = lang_codes.langid LEFT JOIN lang_varnames ON lang_site.varid = lang_varnames.varid where lang_codes.iso_code = '" . $lang . "'";
$result = db_query($sql);
//generate report table
echo "<table cellspacing='0' border='1'><tr><th>Count</th><th>Language</th><th>Variable Id</th><th>Variable Name</th><th>Variable Value</th><th>Edit</th></tr>";
$a=1; //count the rows to number the rows for easy viewing
while($data = db_fetch_assoc($result)){
//create form in each tr
echo "<form name='edit_" . $data['lid'] . "' id='edit_" . $data['lid'] . "' action=''><tr><td>" . $a++ . "</td><td>" . $data['language'] . "</td><td>" . $data['varid'] . "</td><td>" . $data['varname'] . "</td><td><textarea class='form-control' name='varval' id='varval' cols='100' wrap='virtual'>" . $data['varval'] . "</textarea></td><td id='editresponse'><button type='submit' class='button' type='submit' id='but_" . $data['lid'] . "'>Edit</button></td></tr></form>";
?>
//jquery to post edits
<script language="javascript">
$(document).ready(function()
{ //using $.ajax() function
//alert("document ready"); //this alerts each row
//this function will not work, no errors, simply nothing
$(document).on("submit", "#edit_<?php echo $data["lid"]; ?>", function(e)
{
//alert("button clicked"); //this does not work
var data = $("#edit_<?php echo $data["lid"]; ?>").serialize();
$.ajax({
type : "POST",
url : "/lang/ajax_langs.php",
data : data,
success : function(response)
{
{
$("#editresponse").html(response);
};
}
});
e.preventDefault();
});
});
</script>
<?php
}
echo "</table>";
}
?>
How do I get the jQuery to submit the individual form in each row to effect an edit and then refresh each row individually as languages are edited? I need to add another form to each row to delete an entry then remove the row dynamically, but I am stuck here without being able to submit any of these forms.
I should add that this generated form shows well in the website, but is not shown in view source. Using chrome browser. I'm open to any suggestions. Thanks in advance for reading. I seriously hope I can find a solution here. Otherwise, I'm back to the 90's on this software.
It's not working because you are only submitting one id. You need to make each of your forms be of the same class. Therefore, any form clicked will be processed. Like
<form class="myForm" .....
Then, the Jquery would look like this
$(".myForm").submit(function(e){
var inputToChange = this.varval; // saw input varVal, but use whatev
var dataToChange = inputToChange.value;
// then send the data to php for processing using ajax or post
Then, use inputToChange.value = whatever new value you want to put into the form input or other div/td etc. you want to change. If you want to change data that isn't in an input, just make that td a text input and disable it from being edited by the client
<input type="text" name="lname" disabled>
then on callback send new data to this.lname.value = (many other ways to do this as well)
Don't forget, if you send through ajax you want to stop the form itself from submitting so use e.preventDefault()

PHP multiple records insert

I am attempting to reword my issue.
I have a datatable that can return thousands of records, each with multiple columns. There is a checkbox in the first column that, once the user checks it, they then click a button, and the CONTAINER_NUMBER that is associated with the row is sent to a modal window to be used in a form.
Here is the code for the checkbox:
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\" name=\"checkMr[]\" /></td>";
This is the javascript that retrieves the CONTAINER_NUMBER and sends it to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
});
$(".modal-body .containerNumber").val( selectedID );
});
});
</script>
This is the section of the modal window that displays the CONTAINER_NUMBER:
<div class="modal-body">
<form action="" method="POST" id="serviceModalForm" name="serviceModalForm">
<input type="text" name="containerNumber" id="containerNumber" class="containerNumber">
Here is the section of PHP that takes the id="containerNumber" and converts it to a PHP variable. After that, there is an INSERT statement that inserts the containerNumber into a database table:
<?php
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$container = mysql_real_escapse_string(stripslashes($container));
$sql = "INSERT INTO myTable (container_num) VALUES ('$container')";
if(mysql_query($sql)){
echo "Insert complete";
}
else {
echo "Insert was not completed";
}
?>
This code is fine. It works good. It does what it's supposed to do...for when the user checks ONE checkbox. It DOES NOT work when the user checks multiple checkboxes.
Basically, from what I've been researching is that I need to separate the records from the variable $container, as there can be multiple containers in that variable, which is why the query does not work when there are more than one container numbers selected.
I need to be able to separate the container numbers and store them in an array or something. The query will read each record separately and generate multiple INSERT statements for each record.
I've tried several times to create an array and get the sql statement to recognize it, but have been unsuccessful. I'm not sure if I'm placing the array in the right place. I'm not sure if this has to be done in the javascript before the container gets sent to the modal window.
I know I need to utilize a FOREACH loop to go through the array, but like I said, I'm not sure where the array needs to go in my code.
Please help. I know I need to learn PDO or MYSQLI. I will be sure to utilize PDO or MYSQLI on my next application. Until then, please help me with this issue.
Thank you, and sorry for so much wording.
Your containerNumber will be posted as a converted string from a js array. Something like id1, id2, id3[...]
In your php code, convert the $container back to an array ($containerArray = explode(",", $container)) and construct the sql dynamically to add all the rows in a single query so that the statment becomes something like
INSERT INTO myTable (container_num) VALUES ('$containerArray[0]'), ('$containerArray[1]')[...]

Categories

Resources