Javascript passing parameters from form to function --> update DB - javascript

can anyone help please. I have a form generated dynamically, when it is submitted it should send values to a function and add them back to a database. I'm having real problems getting this to work, it seems simple: 1. Form --> 2. submit received --> 3. update function. The code is below:
Dynamically generated form:
function renderResults(tx, rs) {
e = $('#status');
e.html("");
for(var i=0; i < rs.rows.length; i++) {
r = rs.rows.item(i);
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input value=\"" + r.name + "\" name=\"name\" />" +
"<input value=\"" + r.amount + "\" name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});
}
}
Handles the form submit and passes to function:
$('#theform').submit(function() {
updateRecord($('#thename').val(), $('#theamount').val());
});
Function to set values:
function updateRecord(id, name, amount) {
db.transaction(function(tx) {
tx.executeSql('UPDATE groupOne SET (name, amount) VALUES (?, ?) WHERE id=?', [name, amount, id], renderRecords);
});
}
The DB update code has the id set to 4 as a test just to see if anything happens to row 4, i've been fiddling with this line for ages to get it to work. If i set it to:
tx.executeSql('UPDATE groupOne SET name = 4, amount = 5 WHERE id=?', [id], renderRecords);
it will work with set values, but can someone help me get the form values into it please.

You are missing the row id in your jQuery selector. You are passing:
$('#thename').val();
But your field has an id of "thename" + r["id"]:
'<input type="text" ... id="thename' + r['id'] + '" ...>'
You need to get your value by passing the full input id.
$("#thename" + rowId).val();
Edit: Looking more closely at your code, I notice you are creating multiple forms with the same id, which is invalid html. I see now that you've got one form per record. Good, just lose the id from the form and its inputs. Instead, use names for the inputs.
var f = $("<form>" +
"<input type=\"hidden\" name=\"rowId\" value=\"" + r.id + "\" />" +
"<input name=\"name\" />" +
"<input name=\"amount\" />" +
"<input type=\"submit\" />" +
"</form>");
e.append("id: " + r.id, f);
f.submit(function(e)
{
updateRecord(this.rowId.value, this.name.value, this.amount.value);
});

Related

How does jQuery().change work with ajax?

I have an input field which I add to html using ajax here:
function WritePrices(categories) {
var strResult = "from: <input class=\"price\" type=\"text\" id=\"minCost\" value=\"" + categories.MinPrice + "\" />";
strResult += "from: <input class=\"price\" type=\"text\" id=\"maxCost\" value=\"" + categories.MaxPrice + "\" />";
$("#price-range").html(strResult);
}
And then I want to catch a moment when this input is changed by the user. That's why in the script I also have change method
jQuery("input#minCost").change(function () {
//...
});
But this method doesn't "hear" any changes to my input field. It hears changes only when my input field is created in html(not during in the script). what should I change to make jQuery seen changes to my input field?
You must assign event just after the creation. Please find working snippet below:
function WritePrices(categories) {
var strResult = "from: <input class=\"price\" type=\"text\" id=\"minCost\" value=\"" + categories.MinPrice + "\" />";
strResult += "from: <input class=\"price\" type=\"text\" id=\"maxCost\" value=\"" + categories.MaxPrice + "\" />";
$("#price-range").html(strResult);
jQuery("input#minCost").change(function () {
alert("working");
});
}
var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price-range"></div>
You need to use document change pattern
$(document).on('change','input#minCost',function(){
...
});

Get the ID from "append(<tr><td="ID">..."

I am filling a table with some data that I get from firebase database, and for that I am using append()
$("#table_body").append("<tr><td>" + nome + "</td>" +
"<td>" + marca + "</td>" +
"<td>" + modelo + "</td>" +
"<td>" + setor + "</td>" +
"<td>" + responsavel + "</td>" +
"<td><div buttons>"+
"<button>Delete</button>"+" "+
"<button>Edit</button>"+
"</div></td></tr>");
But then, I don't know how to use the "Remove" and "Edit" buttons on each row of the table, shouldn't I have the ID of each row? But then, how do I get the ID of each row if the rows are added dynamically?
You have an object ID from your data model ... add that as an attribute to the row.
Then use a traverse to closest() row to isolate instances
Following assumes a button with class added :
<tr data-id="idFromFirebaseObject">
....
<button class="delete-btn">Delete</button>
Then use event delegation to account for elements that don't yet exist at run time
$("#table_body").on('click','.delete-btn', function(e){
// "this" is element event occurred on
var $row = $(this).closest('tr'),
rowId = $row.data('id');
// do your thing with FB then in success callback remove row
....
$row.remove();
})

How to change database values with dynamically created buttons in PHP

I am dynamically creating html content with PHP and I am creating a button and when that button is clicked It should invoke a PHP script that will update the values of a column of a specific row in the database
Here is my code:
<?php
session_start();
if(!isset($_SESSION['id'])){
header("Location: login.php");
}else{
require_once("mysqli_connect.php");
$query = "SELECT * FROM markeri WHERE odobreno ='F'";
$response = #mysqli_query($dbc,$query);
if($response){
echo "<hr>";
while($row = mysqli_fetch_assoc($response)){
echo "<div align='center' id='markeri'><h3>Naziv: " . $row['naziv'] . "</h3>";
echo "<h3>Ulica: " . $row['ulica'] . "</h3>";
echo "<h3>Opis:</h3>" . "<p>" . $row['opis'] . "</p>";
echo "<h4>Email: " . $row['email'] . "</h4>";
echo "<img src='" . $row['link_slike'] . "' width='300px' /></br>";
echo "<form action='update.php' method='POST'>";
echo "<textarea rows='10' cols='30' maxlength='500' placeholder='Komentar' name='" . $row['marker_id'] . "'></textarea></br>";
echo "<input type='button' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
}
}
}
?>
I tried something like making the name of the textarea equal to the marker_id in my database and making the name of the button the value of marker_id + the string "b" but I don't know how to call them on my update.php script. Usually when it is a normal case and when there is no dynamic content I know how to do it with $_POST['name'];
EDIT:
I used AJAX to dynamically create the HTML as you told me but I've encountered another problem
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'><a href='odobri_prijavu.php?id=" + m.marker_id + "'>Odobri</a>" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>IzbriĆĄi</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
</script>
I tried to use buttons but I couldn't figure how to add event handlers to dynamically created buttons that will post a request via AJAX to some php script with the proper id as the value and the value of the textarea. So I used the anchor tag and I was able to send the id, but I can't send the value of the textarea because I don't know how to reference it and even if I referenced it, it will be NULL because its value is set to the anchor tag at the very beginning and I want to type in text in the textarea.
try this
$(".btn_class_nm").click(function(){
$.ajax({
type: "POST",
url: "http://domain.com/phpscript_filenm.php",
data: {
val1:"val1",
val2:"val1",
},
success: function(msg){
alert( "record updated"); //Anything you want
}
});
});
First of all give a Class Name to the Button as it is being generated dynamically and the number of them can vary based on the number of records the query returns. Something like this:-
echo "<input type='button' class='btn btn-primary btn-xs btn-block active view_data' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
Note that I have add view_data in the class definition. This will help is trapping the onclick event through jquery.
the jquery will be something like
$('.view_data').click(function(){
var yourvariable = JSON.stringify($(this).val()); //Gets Clicked button value
$.ajax({
url:"workstatus.php",
method:"post",
data:{yourvariable:yourvariable, anymoreyourvariables:anymoreyourvariables, , },
success:function(data){
$('#htmldivID').html(data);//If you want result there.
alert( "record updated"); //Anything you want
}
});
I hope this helps you.

Iterate through Superglobal with dynamic name

For a school assignment I have to build a client side shopping cart. The assignment states that I can only use PHP for sending the order confirmation. I am using hidden form fields (that are generated after iterating through cookies) to send the order details to a checkout page, where PHP will take over.
The form fields on one page
NumberOrdered = 0;
NumberOrdered = readCookie("NumberOrdered");
for (i=1; i <= NumberOrdered; i++){
NewOrder = "Order"+ i;
thisCookie = "";
thisCookie = readCookie(NewOrder);
fields = new Array();
fields = dezeCookie.split("|");
document.write("<input type=hidden name=\"ID_"+ i +"\" value=\"" + fields[0] + "\">");
document.write("<input type=hidden name=\"BRAND_"+ i +"\" value=\"" + fields[1] + "\">");
document.write("<input type=hidden name=\"MODEL_"+ i +"\" value=\"" + fields[2] + "\">");
document.write("<input type=hidden name=\"MATERIAL_"+ i +"\" value=\"" + fields[3] + "\">");
document.write("<input type=hidden name=\"PRICE_"+ i +"\" value=\"" + fields[4] + "\">");
}
Im having troubles iterating trough the values of the $_POST superglobal. I want to use a for loop that stores the values in an array. I am really doing this wrong though.
After Submit
<?php
for ($i = 1; $i > 12; $i){
if(!empty($_POST["ID_$i"]) && !empty($_POST["BRAND_$i"]) && !empty($_POST["MODEL_$i"]) && !empty($_POST["MATERIAL_$i"]) && !empty($_POST["PRICE$i"])){
$i = array ('id' => $_POST["ID_$i"],
'brand' => $_POST["BRAND_$i"],
'model' => $_POST["MODEL_$i"],
'material' => $_POST["MATERIAL_$i"],
'price' => $_POST["PRICE_$i"],
);
echo "$i";
}
}
?>
Iterating through the $_POST superglobal does not work.. What would work?
Miss interpretation of concatenation:
$_POST['ID_' . $i],
$_POST['BRAND_' . $i],
Alternatively if you always have the same number of fields with values, like, for sure, you could set name for each field as ID[], and access as a normal array: $_POST['ID'][0], $_POST['ID'][1], $_POST['ID'][2], ...
Though you have to be sure that all fields have some value. Empty, null or missing values will not be represented as empty value to $_POST and relation between data would be lost.
Btw, your $i = array(... would overwrite your own counting variable
And your for loop is wrong. You would never reach a loop, actually, because you have written: for ($i = 1; $i > 12; $i++);

Using only one function to update different columns of a table in database

id car make sales
1 panamera porsche 100
2 italia ferrari 200
3 volante astonmartin 300
4 avantador lamborghini 400
5 slk mercedes 500
So guys, i have this simple table in my database. And i'm gonna echo this table in a while loop.
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" id="'.$row['id'].'">'.$row['car'].'</li>';
echo '<li class="editable2" id="'.$row['id'].'">'.$row['make'].'</li>';
}
?>
</ul>
The idea is to update this table using jQuery in-place editor. So here is the code-
$(document).ready(function()
{
$(".editable").bind("dblclick", replaceHTML);
$(".editable2").bind("dblclick", replaceHTML2);
$(".btnSave, .btnDiscard").live("click", handler);
function handler()
{
if ($(this).hasClass("btnSave"))
{
var str = $(this).siblings("form").serialize();
$.ajax({
type: "POST",
async: false,
url: "handler.php",
data: str,
});
}
}
function replaceHTML()
{
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"car\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + $(this).attr("id") + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
function replaceHTML2()
{
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"make\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + $(this).attr("id") + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
}
);
This is an in-place edit code i got it from the internet and i just tore it down to basic level just to understand the codes. Dont worry bout the update query, its is in "handler.php".
The problem here is, i have to write separate function for each column. In this case, i have to write a separate function to update 'car' column, separate function to update 'make' column and goes on. I dont think this is the correct method to do. Because, here i just have 3 columns. What if i had 10 to 15 columns? I dont think writing 15 functions is the correct method. And "$(this).html()" takes only one form's value. Please help.
Modify your PHP script to generate HTML similar to this:
<table>
<tbody>
<tr data-id="1">
<td data-col="car">panamera</td>
<td data-col="make">porsche</td>
<td data-col="sales">100</td>
</tr>
</tbody>
</tbody>
The id of the database row corresponding to each HTML table row is specified with data-id in each tr. And each td specifies to which DB column it corresponds using data-col.
Using these information you can pass enough information back to the PHP script that updates the database. So essentially when a cell is clicked, you can get its column name using:
$(this).data('col')
And you can get the ID for its row using:
$(this).parent('tr').data('id')
Then you can pass these to the PHP page that updates the DB.
EDIT 1:
You can use ul/li instead of table/tr/td. You can also use class=car, class=make, etc. instead of data-col='car', data-col='make', etc. if you are using an older version of jQuery that does not support HTML5-style data- attributes.
EDIT 2: Complete solution
Change your while loop to this:
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" data-id="'.$row['id'].'" data-col="car">'.$row['car'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="make">'.$row['make'].'</li>';
}
As you can see we store the database row ID in data-id and the database column name in data-col.
Now with this setup you would only need one handler:
function replaceHTML()
{
var rowId = $(this).data('id');
var colName = $(this).data('col');
var buff = $(this).html().replace(/"/g, """); // Are you sure you need this?
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"" + colName + "\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + rowId + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
$(".editable").bind("dblclick", replaceHTML);
Finally, always try to write readable code! Please! :)
EDIT 3: JSFiddle
Please see this live solution. It shows how you can get the column name and row ID. You just have to adopt it to work with your PHP script.

Categories

Resources