how to post data from php while loop with ajax - javascript

I am trying to create a friend button like fb.I have a while loop that echos the name and some other data i need to save into a table in my database for every user request seperatly.My problem is that i don't know how to pass them with ajax because i have same id on textboxes buttons.I tried to pass them with same ids but this passed 3 times the same data or only one of them.So i tried to use the id="something$row[id]" to define every textbox and button but i don't know how to trigger the jquery function and post them with ajax.a picture of what i am trying
my php file
echo "<div class='col-xs-12'>
<div class='row fixed-table'>
<div class='table-content'>
<table class='table table-striped text-muted' id='mytable'>
<tbody>";
while($row = mysqli_fetch_array($requests)){
$username=("SELECT * FROM users WHERE user_id=".$row['patient']);
$found=mysqli_fetch_array(mysqli_query($sql_link,$username));
echo "<tr>
<td class='text-center'>
<p>
$found[username]
<p>
</td>
<td class='text-center'>";
$patient_username=$found['username'];
$patient_id=$found['user_id'];
echo"<input type='text' id='patient_id$row[id]' class='hidden' value='$patient_id'>
<input type='text' id='patient_username$row[id]' class='hidden' value='$patient_username'>
<input type='text' id='doctor_id$row[id]' class='hidden' value='$doctor_id'>
<input type='text' id='doctor_fname$row[id]' class='hidden' value='$doctor_fname'>
<input type='button' id='accept_btn$row[id]' class='btn btn-primary' value='Accept'>
</td>
</tr>";
}
echo "</tbody>
</table>
</div>
</div>
</div>";
my js file
function decision(){
var patient_id = $('#patient_id').val();
var patient_username = $('#patient_username').val();
var doctor_id = $('#doctor_id').val();
var doctor_fname = $('#doctor_fname').val();
$.ajax({
type:"post",
url:"php/add.php",
data: {"patient_id": patient_id,"patient_username": patient_username,"doctor_id": doctor_id,"doctor_fname": doctor_fname},
success:function(data){
$("#decision").html(data);
}
});
$('#accept_btn').click(function(){
decision();
});

This is easy with JQUERY as you dont even need to know the IDs within the form. However first you will need to wrap all your inputs into a form and assign an ID to the form and a name to each input.
var data = $("#myForm").serialize();
$.post('myPHPFILEURL.php', data,function(retData){
//CODE THAT HANDLES SERVER RESPONSE
});
echo "<div class='col-xs-12'>
<div class='row fixed-table'>
<div class='table-content'>
<form id='myForm'>
<table class='table table-striped text-muted' id='mytable'>
<tbody>";
while($row = mysqli_fetch_array($requests)){
$username=("SELECT * FROM users WHERE user_id=".$row['patient']);
$found=mysqli_fetch_array(mysqli_query($sql_link,$username));
echo "<tr>
<td class='text-center'>
<p>
$found[username]
<p>
</td>
<td class='text-center'>";
$patient_username=$found['username'];
$patient_id=$found['user_id'];
echo"<input type='text' name='patient_id$row[id]' id='patient_id$row[id]' class='hidden' value='$patient_id'>
<input type='text' id='patient_username$row[id]' name='patient_username$row[id]' class='hidden' value='$patient_username'>
<input type='text' id='doctor_id$row[id]' name='doctor_id$row[id]' class='hidden' value='$doctor_id'>
<input type='text' id='doctor_fname$row[id]' name='doctor_fname$row[id]' class='hidden' value='$doctor_fname'>
<input type='button' id='accept_btn$row[id]' name='accept_btn$row[id]' class='btn btn-primary' value='Accept'>
</td>
</tr>";
}
echo "</tbody>
</table>
</form>
</div>
</div>
</div>";
Simply select your form and serialize() the data then pass the new serialized string into the data argument of your AJAX function.

You could add data-id="userID"
attribute to your input instead of having it in the ID
<input type='button' id='accept_btn$row[id]' class='btn btn-primary' value='Accept'>
So your input would look something like this:
<input type='button' id='accept_btn' data-id='$row[id]' class='btn btn-primary' value='Accept'>
And then in you jquery/javascript code use like this:
$("#accept_btn").on("click", function(){
var userID = $(this).data("id"); //this will get the value from data-id from the clicked button
//rest of your code here...
});
You can also add this for all of your input fields and retrieve data from them as well.
$("#patient_username").data("id")
Hope this helps. You can check this sample jsfiddle https://jsfiddle.net/Lz3k1he1/

I finally made it. It took me hours but it works and i wanto thank you all for your help and specially Igor Ilic.
The solution
php
<tbody>";
while($row = mysqli_fetch_array($requests)){
$username=("SELECT * FROM users WHERE user_id=".$row['patient']);
$found=mysqli_fetch_array(mysqli_query($sql_link,$username));
echo "<tr>
<td class='text-center'>
<p>
$found[username]
<p>
</td>
<td class='text-center'>";
$patient_username=$found['username'];
$patient_id=$found['user_id'];
echo"<buuton id='accept_btn$row[id]' class='btn btn-primary' data-patient_id='$patient_id' data-patient_username='$patient_username' data-doctor_id='$doctor_id' data-doctor_fname='$doctor_fname'
href='#' onclick='decision(this);'>
Accept</button>
</td>
</tr>";
}
echo "</tbody>
and js
function decision(p){
var patient_id = $(p).data('patient_id');
var patient_username = $(p).data('patient_username');
var doctor_id = $(p).data('doctor_id')
var doctor_fname = $(p).data('doctor_fname');
$.ajax({
type:"post",
url:"php/add.php",
data: {"patient_id": patient_id,"patient_username": patient_username,"doctor_id": doctor_id,"doctor_fname": doctor_fname},
success:function(data){
$("#decision").html(data);
}
});
}

Related

Insert from dynamic table input to mySQL

I have a dynamic table form input form which you can add/remove rows as you like. As someone who doesn't have much experience, I'm stuck on how to save those input into the mySQL database.
Here's what the input.php looks like
<form action="insert.php" method="post">
<div class="box-body no-padding">
<table class="table table-bordered">
<tr>
<th>Item</th>
<th>#</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
<tr>
<td><input type="text" id="item" name="item"></td>
<td><input type="text" id="no" name="no"disabled></td>
<td><input type="number" id="qty" name="qty"></td>
<td><input type="number" id="price" name="price"></td>
<td><input type="number" id="total" name ="total" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
</table>
</div>
<div class="box-body">
<div class="button-group">
<i class="fa fa-plus-circle"></i> Add Item
</div>
</div>
<div class="box-footer">
<div class="button-group pull-right">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</form>
And here is the JS (jQuery) code that I use to add/remove rows
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function(){
$(document).ready(function(){
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item'></td>";
var no = "<td><input type='text' id='no' disabled></td>";
var qty = "<td><input type='number' id='qty'></td>";
var price = "<td><input type='number' id='price'></td>";
var total = "<td><input type='number' id='total' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
$(".table").on('click', '.remove-row', function(){
$(this).closest("tr").remove();
});
});
});
</script>
Here's what the page looks like:
input page
insert.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db", $connection);
if(isset($_POST['submit'])){
$item = $_POST['item'];
$no = $_POST['no'];
$qty = $_POST['qty'];
$price = $_POST['price'];
$query = mysql_query("insert into table(item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
?>
I know the insert.php won't work for my case because I need to input it as arrays. The thing is:
1. I don't know how to implement the front end so I won't have duplicate id/names when I click "Add Item"
2. I don't know how to insert the arrays (that I don't know to create) to the mysql.
I'd like to know how can I implement the save button in my case. Thank's for your help.
First, please research the mysql_* functions. They should no longer be used because they can lead to SQL injection security issues. Use mysqli_* instead or a DB layer like PDO.
Second, if you append "[]" to your input tag names then PHP will receive the data as arrays and you can loop through it in your insert.php.
<tr>
<td><input type="text" id="item" name="item[]"></td>
<td><input type="text" id="no" name="no[]" disabled></td>
<td><input type="number" id="qty" name="qty[]"></td>
<td><input type="number" id="price" name="price[]"></td>
<td><input type="number" id="total" name="total[]" disabled></td>
<td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td>
</tr>
And be sure your javascript code also adds the name attribute:
$(".add-row").on('click', function(){
var item = "<td><input type='text' id='item' name='item[]'></td>";
var no = "<td><input type='text' id='no' name='no[]' disabled></td>";
var qty = "<td><input type='number' id='qty' name='qty[]'></td>";
var price = "<td><input type='number' id='price' name='price[]'></td>";
var total = "<td><input type='number' id='total' name='total[]' disabled></td>";
var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>";
var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>";
$("table").append(markup);
});
Then in PHP you can have:
<?php
$connection = mysqli_connect("localhost", "root", "", "db");
if(isset($_POST['submit'])){
$rowCount = count($_POST['item']);
// Note that this assumes all the variables will correctly be submitted as arrays of the same length. For completeness and robustness you could add a !empty check for each value.
for ($i = 0; $i < $rowCount; $i++) {
$item = $_POST['item'][$i];
$no = $_POST['no'][$i];
$qty = $_POST['qty'][$i];
$price = $_POST['price'][$i];
$query = mysqli_query($connection, "insert into `table` (item, no, qty, price) values ('$item', '$no', '$qty', '$price')");
}
}
?>

Mapping html form input to javascript object inside a newly formed element

I have the following html. Please have a look at it and I will explain the problem as and when we go along.
<table>
<tbody>
<tr id="<?php echo $record['id']?>" style="...">
<td><?php echo $record['id']; ?></td>
<td><?php echo $record['url']; ?></td>
<td><input type="button" name="edit" value="Edit" onclick="edit(<?php echo ($record['id'])?>)"></td>
</tr>
</tbody>
</table>
What I am trying to achieve here is that when I click the "Edit" button, it clears that field and creates new empty fields in its place where those details can be entered again and in place of the edit button, the update button appears.
This is what the edit function looks like:
<script>
function edit(id){
var element = document.getElementById(id);
$(element).empty();
$(element).append("<td><input name='id' value="+id+" disabled></td>" +
"<td><input type='text' name='url' ></td>" +
"<td><input type='text' name='title'></td>" +
"<td><input type='button' value='Update' onclick='testFunction()'></td>");
}
The update button fires a function called testFunction. Now in this testFunction, I want to send the new values into the new form that I have created with jQuery so that I can send those values to the MySQL so that the new value of title is updated for a given id.
Please look over the code and tell me how should I go about solving this?
var testFunction = function(newID){
console.log("This is the NEW id of the object that we are changing----->");
console.log(newID);
console.log("--------------------------END------------------");
$.post( "update", { id: newID})
.done(function( ) {
document.getElementById(id).style.display = "none";
});
};
</script>
//test record
var record = {
id: 12345,
title: 'Some title',
url: 'https://stackoverflow.com/posts/45861223/edit'
};
function action(id) {
var $element = $('#' + id),
$title = $('[name=title]', $element),
$url = $('[name=url]', $element),
$btn = $('[type=button]', $element),
isUpdate = ($btn.attr('value') != 'Edit');
$title.prop('readOnly', isUpdate);
$url.prop('readOnly', isUpdate);
$btn.attr('value', isUpdate ? 'Edit' : 'Update');
if (isUpdate) {
// show some loading mask
$.post("update", {
title: $title.val(),
url: $url.val(),
id: id
})
.done(function() {
// here you have the new id from the server
// hide the loading mask
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr id="12345">
<td><input type='text' name='title' value="Some title" readOnly></td>
<td><input type='text' name='url' value="https://stackoverflow.com/posts/45861223/edit" readOnly></td>
<td><input type="button" name="edit" value="Edit" onclick="action(12345)"></td>
</tr>
</tbody>
</table>

How to Check if other page field value is empty using jquery

I'm getting all contacts from Mysql db and then showing it on html row. Each row has onClick() method After click on each row it will show a details of contact to the right side of all contacts.
showing All contacts:
echo "<tr onclick='getDetails($cdid), showthirdbox($cdid), visited(this);'>";
echo "<td class='' valign='top' align='left' width='20'>$companyName</td>";
echo "<td class='' valign='top'>$family_name</td>";
echo "<td class='' valign='top'>$given_name</td>";
echo "<td class='' valign='top'>$department</td>";
echo "<td class='' valign='top'>$title</td>";
echo "</tr>";
This getDetails() call the getContactDetails.php (Contact Details) page. In this page I've a field called Note where user can enter notes.
So now I want to show a Confirm message to the user Only if user write something on Enter Note box but click other row (all contacts) without save this Enter Notes
Confirm mesaage will be : Do you want to save this Notes box before you go to other Contact ? Yes Or No. If Yes then saveNote() will be call otherwise it will load the new contact row.
I've no idea how can I do this using Jquery or Javascript ? Do you have any idea or solution ? Thank you.
getDetails() function:
function getDetails(id) {
id = id;
$.ajax({
type:"post",
url:"getContactDetails.php",
data:"id="+id,
success:function(res){
$('#visiable').show();
$('#notebox_visiable').show();
$('#thirdBox').show();
$('#all_contact_details').html(res);
showthirdbox(id);
//showNotexBox(id);
//showAllNotesBox(id);
}
});
}
getContactDetails.php page have Note field:
<tr>
<td colspan="2">Enter Note<p id="demo"></p></td>
</tr>
<tr>
<td colspan="2">
<center><img id="loading-image" src="images/loading-image.gif" style="display:none; margin-bottom:10px !important;"/></center>
<div id="Notesboxsuccess"></div>
<form action="" method="post" id="showNotesBox" name="notebox">
<input type="hidden" value="<?php echo $id; ?>" name="cdid" id="cdid"/>
<tr>
<td colspan="2"><textarea name="contentText" id="contentText" cols="35" rows="4" placeholder="enter note"></textarea></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save" name="submit" class="submit" id="addNewNotes"/></td>
</tr>
</form>
Home page view after click on a row (All contacts) :
change only triggers on blur, so as long as the user stays in the textbox there is nothing to do.
jQuery change()
Attach a change event handler:
$("#contentText").change(function() {
$("#contentText").attr("ididwritesomething","yep");
}
In the save button remove the attribute jQuery removeAttr()
$("#contentText").removeAttr("ididwritesomething");
In the click handler for your contact list, check if the attribute is set (from this question):
var attr = $("#contentText").attr("ididwritesomething");
if (typeof attr !== typeof undefined && attr !== false && attr=="yep"){
//do you want to save?
}
Here you can use jQuery Change function to do this.
For example,
<input id="field" type="text" value="abcd">
<a id="pid" href="#">Link</a>
For the above html code the jQuery code is following
$(document).ready(function(){
$("#pid").click(function(){
$("#field").change(function(){
alert("The text has been changed.");
});// end of change
});// end of click function
});//end of document

how to print textbox value in php

In my code,when any text is entered into the textbox and click on add attribute button, entered value displayed on page for two times, one in first row of table and another one is in first row of second table. Now question is, when i entered text into another textbox which is in second row of second table, it should display the entered text.but it can't display. it is not working.
<script>
var i = 0;
document.getElementById('add-val').innerHTML='';
function insRow()
{
i++;
var x=document.getElementById('myTable').insertRow(-1)
var a=x.insertCell(-1)
var txt=document.getElementById('add-val').value;
a.innerHTML=txt;
// for <tr> of table
var row = document.getElementById("myRow");
var newrow=document.getElementById("myRow1");
var x = row.insertCell(-1);
var y = newrow.insertCell(-1);
x.innerHTML=txt; //+ '<br>' +
y.innerHTML='<input type="text" name="nm" />';
}
document.getElementById('add-val').innerHTML='';
</script>
& this is html code.
<form method="post" name="form">
<input type="text" name="attr" id="add-val"> <input type="button" onClick="insRow()" value="Add Attribute">
<table width="27" height="17" id="myTable"> </table>
<table cellpadding="13px">
<tr id="myRow"> </tr>
<tr id="myRow1"> </tr>
</table>
<input type="submit" value="Add option" onClick="insRow()"/>
<?php
if(isset($_POST['submit']))
{
$val= $_POST['add'];
echo $val;
}
?>
</form>
It should be
y.innerHTML='<input type="text" name="nm[]" />';
The []'s after nm
name="nm[]"
Serve to store all new generated fields into an array, which can then be accessed by $_POST
Which you then just access like so....
$val = $_POST['nm'];
foreach($val as $v){
echo $v; // display what user entered
}
// var_dump($val) will show you all the users seperate input for each field
HTML Code :
<form method="post" name="form">
<input type="text" name="attr" id="add-val"> <input type="button" onClick="insRow()" value="Add Attribute">
<table width="27" height="17" id="myTable"> </table>
<table cellpadding="13px">
<tr id="myRow"> </tr>
<tr id="myRow1"> </tr>
</table>
<input type="submit" value="Add option" onClick="insRow()"/>
<?php
if(isset($_POST['submit']))
{
$val= $_POST['nm'];
echo $val;
}
?>
</form>
put the name of input whos value you want to print in place of attr
$val= $_POST['attr'];

Store updated forms as an array w/jQuery

I am currently building an internal tool for viewing and editing SQL-like tables via the web. I have some PHP and html written that generates these tables and jQuery written that does this, so far:
Delete Rows
Add New Rows
Output form value after entry
The ultimate goal, of course, is to generate a SQL statement using INSERT, UPDATE, DELETE, etc on the modified data. I have a grasp on how to concatenate the results into such a statement, but could use help targeting columns for it.
My main concern is modifying the form value output function so that I can store any updated entries in an array and output them as a CSV string. I've read about .each, .map, .push, and .serializeArray. I'm not sure exactly how to use/combine these methods to accomplish the desired result. Here are some code snippets:
The current jQuery:
$('#add_row').on('click', function(){
$('<tr><td id="data"><input class ="new_row"></td><td id="data"><input class ="new_row"></td><td id="data" style="text-align:center;"><input class ="new_row"></td><td id = "Delete_Button"><button class="rmv_row">-</button></td></tr>').appendTo('#SQLdata');
});
$("table").on('keyup', 'input', function(){
$('#output').text($(this).val());
});
$('table').on('click', '.rmv_row', function(){
$(this).closest('tr').remove();
});
});
and the PHP/HTML:
<table id="SQLdata">
<tr style="background-color: margin-left:#6b685c;">
<td style="background-color: margin-left:#6b685c; font-family:tahoma,arial,verdana,sans-serif"; colspan="3">
<form style="color:black;" method="post" action="WebEventsStructureColumnTool.php">
Select your table name:
<select method="post" name="table_name" id="picker">
<option>Removed For Security</option>
</select>
<input type="submit" value="Go" name="submit">
</form>
</td>
<td><button id="add_row">Add a Row</button></td>
</tr>
$tableName = $_POST['table_name'];
$statementObject = $pdo->prepare("SELECT a, b, c FROM tab WHERE _id =?");
$statementObject->bindParam(1, $tableName, PDO::PARAM_STR);
$statementObject->execute();
$statementObject->bindColumn('a', $Col1);
$statementObject->bindColumn('b', $Col2);
$statementObject->bindColumn('c', $Col3);
while ($statementObject->fetchAll(PDO::FETCH_BOUND)){
// Gets an array from the CSVs in the column :
$Column1 = explode(",", $Col1);
$Column2 = explode(",", $Col2);
$Column3 = explode(",", $Col3);
}
//Fetches the total number of values from each exploded array:
$Count1 = count($Column1);
$Count2 = count($Column2);
$Count3 = count($Column3);
//Establishes the total length/height of the table:
$largest = $Count1;
if ($Count2 > $largest){
$largest = $Count2;
}
if ($Count3 > $largest){
$largest = $Count3;
}
echo '
<tr>
<th>a</th>
<th>b</th>
<th style="text-align: center">c</th>
<th>delete row</th>
</tr>';
for($i = 0; $i < $largest; $i++){
$tableRows[] =
"<tr>
<td id='data'>
<input type='text' value='" . $Column1[$i] . "'>
</td>" .
"<td id='data'>
<input type='text' value='" . $Column2[$i] . "'>
</td>" .
"<td id = 'data' style='text-align:center;'>
<input type='text' value='". $Column3[$i]. "'>
</td>
<td id = 'Delete_Button'><button class='rmv_row'>-</button></td>";
}
foreach ($tableRows as $row){
echo $row;
}
echo '</table><div><table><tr id="output" colspan="4"></tr></table>'
If anyone also has advice/recommendations on existing code, feel free to criticize. I am a young developer just starting out and could use all the help I can get. Thanks!
I added this bit this morning and am now successfully getting CSVs:
var string = new Array()
function updateString(){$('#output').text(string);}
$('input').each(function(){
string.push($(this).val());
});
Working on creating three different arrays for each data manipulation option and limiting printing to conditionals.

Categories