passing td value to javascript - javascript

I am trying to pass the the td value to java script,from java script i post that value to the php page where it contains query.can any one guide me how to pass the td value to java script,i tried but i don't know how to pass this value .thanks
Below is my js code :
<script>
function myFunction() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
var url = "testpage2/config.php";
var vars = "mcc="+mcc+"&mnc="+mnc;
hr.open("POST", url, true);
hr.send(vars);
}
</script>
Html
<?php
$sql = mysql_query("SELECT * FROM supplierprice ");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo ' <td class="edit region '.$rows["supp_price_id"].'">'.$rows["region"].'</td>
<td class="edit country '.$rows["supp_price_id"].'">'.$rows["country"].'</td>
<td class="edit networkname '.$rows["supp_price_id"].'">'.$rows["networkname"].'</td>
<td id="mcc" class="edit mcc '.$rows["supp_price_id"].'">'.$rows["mcc"].'</td>
<td id="mnc" class="edit mnc '.$rows["supp_price_id"].'">'.$rows["mnc"].'</td>
<td class="edit mnp '.$rows["supp_price_id"].'">'.$rows["mnp"].'</td>';
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i=0;
while($rows1=mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows1[0];
echo '<td width="0px;" class="edit '.$columnArray[$i].' '.$rows["supp_price_id"].'">'.$rows[$columnArray[$i]].'</td>';
echo '<td><input type="button" onclick="myFunction()" value="" /></td>';
$i++;
}
echo '</tr>';
}
?>

value is for input elements. For others(like td, th, div, span...) use innerHTML:
var mcc = document.getElementById("mcc").innerHTML;
var mnc = document.getElementById("mnc").innerHTML;

Related

Get selected value from dynamic dropdown in table

I have a button that adds a row to a table so that data can be inserted. One of the <td> tags populates a dropdown menu. I need to get the value from that dropdown to post in an ajax call back to a php page to insert the data in the database. Everything I've tried has returned undefined for position_ID.
I'm getting a 500 Error on the POST and I think it's due to var position_ID = $(this).parents('tr').find('.positionList').val();, in the Insert function, not being set.
HTML Code:
<html>
<head>
<script src='jquery-3.4.1.js' type='text/javascript'></script>
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<button type="button" name="add" id="add">Add</button>
<table id="dataTable">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Location Number</th>
<th>Position</th>
</tr>
</table>
</body>
</html>
PHP Code:
<?PHP>
$sql = "SELECT positionID, name FROM position";
$result = mysqli_query($db,$sql);
$position_arr = array();
while( $row = mysqli_fetch_array($result) ){
$positionID = $row['positionID'];
$name = $row['name'];
$position_arr[] = array("positionID" => $positionID, "name" => $name);
}
// encoding array to json format
$JSON_array = json_encode($position_arr);
echo $JSON_array;
?>
<?PHP>
if(isset($_POST["last_name"], $_POST["first_name"], $_POST["location_num"], $_POST["position_ID"]))
{
$lastName = mysqli_real_escape_string($db, $_POST["last_name"]);
$firstName = mysqli_real_escape_string($db, $_POST["first_name"]);
$locationNum = mysqli_real_escape_string($db, $_POST["location_num"]);
$positionID = mysqli_real_escape_string($db, $_POST["position_ID"]);
$sqlInsertEmployee = "INSERT INTO employee(lastName, firstName, positionID, locationID) SELECT ?, ?, positionID, locationID from location join position p on p.positionID = ? where number = ?";
$stmtInsertEmployee = mysqli_prepare($db,$sqlInsertEmployee);
mysqli_stmt_bind_param($stmtInsertEmployee, "ssss", $lastName,$firstName,$positionID,$locationNum,);
mysqli_stmt_execute($stmtInsertEmployee);
mysqli_stmt_close($stmtInsertEmployee);
}
?>
Script code:
$('#add').click(function(){
var html = '<tr>';
html += '<td contenteditable id="lastName"></td>';
html += '<td contenteditable id="firstName"></td>';
html += '<td contenteditable id="locationNum"></td>';
html += '<td contenteditable id="positionID"><select class="positionList"><option></option></select>';
$(document).ready(function() {
var data
$.ajax({
dataType: 'json',
url: 'get-position.php',
data: data,
success: function(data) {
// begin accessing JSON data here
console.log(data)
//data = jQuery.parseJSON(data);
var html_to_append = '';
html_to_append += '<option value="0">-- Select One --</option>'
$.each(data, function(i, item) {
html_to_append += '<option value="' + item.positionID + '">' + item.name + '</option>';
});
$(".positionList").html(html_to_append);
},
})
})
html += '</td><td><button type="button" name="insert" id="insert">Insert</button></td>';
html += '</tr>';
$('#dataTable tr:first').after(html);
});
$(document).on('click', '#insert', function(){
var last_name = $('#lastName').text();
var first_name = $('#firstName').text();
var location_num = $('#locationNum').text();
var position_ID = $(this).parents('tr').find('.positionList').val();
console.log(position_ID);
if(first_name != '' && last_name != '' && location_num != '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:{last_name:last_name, first_name:first_name, location_num:location_num, position_ID:position_ID},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">'+data+'</div>');
$('#dataTable').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
else
{
alert("All Fields is required");
}
});
The .val() method is used to get the value of an element.
Also note that #Kaka Sarmah is correct. Even this will not work because you're creating multiple elements with the same ID. IDs must be unique. Try giving it a class instead.
html += '<td contenteditable class="positionID"><select class="positionList"><option></option></select>';
Then in your javascript you can try to locate it using that class. Something like:
var position_ID = $(this).parents('tr').find('.positionList').val();

TypeError: document.getElementById(...).files is undefined

function uppp(id){
var eleme = "uploaded_image"+id;
alert(id);
var name = document.getElementById(id).files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
}
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById(id).files[0]);
var f = document.getElementById(id).files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("Image File Size is very big");
}
else
{
form_data.append("file", document.getElementById(id).files[0]);
$.ajax({
url:"http://localhost/wat/admin/category/uppp/"+id,
method:"POST",
data:form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
},
success:function(data)
{
var x = document.getElementById(eleme);
x.style.color = 'green';
x.innerHTML= "done";
}
});
}
}
this function function is supposed to get the file name from the input control then post the details to a php file which will upload the name in the database. the function is working "selectively"... that is sometimes it works and sometimes it produces the error above... here is the php file from where the file name is taken... please help
while($row = mysqli_fetch_assoc($result)) {
$document_id= $row["document_id"];
$document_description = $row["document_description"];
$output .= "</tr>";
$output .= "<tr> ";
$output .= " <td class='text-center'><p class='nums'>".$count."</p></td>
<td>
<input type='text' name='' class='textdd' value= '".$document_description."' disabled>
</td>
<td word-wrap:break-word'>
<input type='file' name='file' id='$document_id' size='20' required />
</td>
<td>
<button name='$document_id' onclick='uppp(this.name)'>Upload</button>
</td>
<td id='uploaded_image$document_id' color='red'></td>
";
$output .= "</tr>";
$count++;
}
$output .= "<tr> <td> <input type = 'submit' value='Save Documents' class='btn btn-info'> </td> </tr> ";
$output.= " </tbody> </table>";
echo $output;
}
else{
$output .="<td class= 'noresults'> NO documents Found </td> </tr> ";
$output.= " </tbody> </table></form>";
echo $output;
i realized that i had elements from different tables with the same id on the same page . this was because of creating the ids dynamically from 1 to 100. so when the function is passed an id which belongs to two elements that`s when the error occurred.
i realized that when creating ids dynamically for elements the creation process should be as unique as possible

How do I run a click event for a php created html table

I have php creating a table based on the results of a search and this table overwrites a previous table. When clicking a row of this table I want the details of the row to be displayed. However while clicking on the previous table works when clicking on the results table the click event is not triggered.
The initial table code and containing div:
<div id="fixInfo" style="overflow-y: auto; overflow-x:hidden;max-height:350px; width: 1000px;">
<table class="standard" id= "list">
<?php
include 'DATA.php';
$sql = "SELECT * FROM FIX";
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)){
while ($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo '<td style="width:150px;">'.$row["FIX_ID"].'</td>';
echo '<td style="width:150px;">'.$row["TIME"].'</td>';
echo '<td style="width:150px;">'.$row["DATE"].'</td>';
echo '<td style="width:150px;">'.$row["PROVIDER_ID"].'</td>';
echo '</tr>';
}
}
mysqli_close($conn);
?>
</table>
</div>
The jquery click event code:
<script>
$("#list tr").on("click",function(){
var ID = $(this).find("td:first").text();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("fixstuff").innerHTML = this.responseText;
}
};
var params= "ID="+ID;
xmlhttp.open("POST","fixdetails.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
});
</script>
The result table creation code(searchFix.php):
<?php
$sort = $_POST['sort'];
$search= $_POST['search'];
include 'DATA.php';
if($search==""){
$sql = "SELECT * FROM FIX";
}
else{
$sql= "SELECT * FROM FIX WHERE ".$sort." =". $search;
}
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)){
while ($row = mysqli_fetch_assoc($result)){
echo '<tr>';
echo '<td style="width:150px;">'.$row["FIX_ID"].'</td>';
echo '<td style="width:150px;">'.$row["TIME"].'</td>';
echo '<td style="width:150px;">'.$row["DATE"].'</td>';
echo '<td style="width:150px;">'.$row["PROVIDER_ID"].'</td>';
echo '</tr>';
}
}
mysqli_close($conn);
?>
As you are altering the dom you will need to do a rebind.
$.on does not work the same as the deprecated $.live
try changing initial line to
$(document).on('click','#list tr', {} ,function(e){

Populating data from an html table row

The given snippet has a javascript function and a table in which I want to show content of each row using a modal.
But the problem is when I am using alert in middle for debugging for any number of row when I click in view button it always shows the first value of m_id but it must show the corresponding values. $v object is returning expected data only no problem in that.
I need help since I am just a beginner in ajax.
<script type="text/javascript">
function view_message(){
//alert("aa gyaksjhfjxvhk");
var m_id = document.getElementById('m_id').value;
var c_name = document.getElementById('c_name').value;
var message = document.getElementById('message').value;
alert(m_id);
//alert(loc);
$.ajax({
type: "POST",
url: "view_message.php",
data:
{ 'm_id' :m_id,
'c_name' : c_name,
'message' : message
},
success: function(data){
// alert("success");
$(".message_container").html(data);
}
});
}
</script>
foreach($v_message as $v)
{
echo '<tr>';
echo '<td>'.$v->time.'</td>';
echo '<td>'.$v->c_name.'</td>';
echo '<input id="m_id" name="m_id" value="'.$v->id.'" hidden />';
echo '<input id="c_name" name="c_name" value="'.$v->c_name.'" hidden />';
echo '<input id="message" name="message" value="'.$v->message.'" hidden />';
echo '<td data-toggle="modal" data-target="#myModal">';
echo ' <input type="button" id="view" onclick="view_message()" value="view"></input>';
echo '</td>';
echo '<td data-toggle="modal" data-target="#myModal1">
<span>Delete</span>';
echo '</td>';
echo '</tr>'; ?>
<div id="message_container">
</div>
change your selector $(.message_container) to $(#message_container)
modified code is below.
<script type="text/javascript">
function view_message(){
//alert("aa gyaksjhfjxvhk");
var m_id = document.getElementById('m_id').value;
var c_name = document.getElementById('c_name').value;
var message = document.getElementById('message').value;
alert(m_id);
//alert(loc);
$.ajax({
type: "POST",
url: "view_message.php",
data:
{ 'm_id' :m_id,
'c_name' : c_name,
'message' : message
},
success: function(data){
// alert("success");
$("#message_container").html(data);
}
});
}
</script>
because your selector is document, its find first element with target id, so always first row element return in result.in php code replace onclick="view_message()" with class="view-btn" and use my answer javascript,
<script type="text/javascript">
$(document).ready(function() {
var view_message = function(){
var row = $(this).closest('tr');
var m_id = $(row).find('#m_id').val();
var c_name = $(row).find('#c_name').val();
var message = $(row).find('#message').val();
alert(m_id);
}
$(".view-btn").on('click', view_message);
});
</script>
foreach($v_message as $v)
{
echo '<tr>';
echo '<td>'.$v->time.'</td>';
echo '<td>'.$v->c_name.'</td>';
echo '<input id="m_id" name="m_id" value="'.$v->id.'" hidden />';
echo '<input id="c_name" name="c_name" value="'.$v->c_name.'" hidden />';
echo '<input id="message" name="message" value="'.$v->message.'" hidden />';
echo '<td data-toggle="modal" data-target="#myModal">';
echo ' <input type="button" id="view" class="view-btn" value="view"></input>';
echo '</td>';
echo '<td data-toggle="modal" data-target="#myModal1">
<span>Delete</span>';
echo '</td>';
echo '</tr>'; ?>
<div id="message_container">
</div>
IDs must be unique in the document. See: stackoverflow.com/a/9454716/2181514.
Your for loop generates multiple items with the same id, so when you do $(#id you get the first one.
You can fix this by using classes and passing a reference to the current row:
Change
onclick="view_message()"
<input id="m_id" name="m_id"
to
onclick="view_message(this)"
<input class='m_id' id="m_id" name="m_id"
then:
function view_message(el){
var row = $(el).closest("tr");
var m_id = $(".m_id", row).val();
Update: typo - should have been $(el).closest, not $(this)
Example fiddle: https://jsfiddle.net/37tkgsnm/
html:
<tr>
<td><input class='m_id' value='123' /></td>
<td><button type="button" onclick="view_message(this);">click</button></td>
</tr>
js:
function view_message(el) {
var row = $(el).closest("tr");
alert($(".m_id", row).val())
}

Pass the td value to php page using Javascript

I have a HTML table the displays record from database.
Below is a screenshot of my table
There is a button in a TD (i.e column 5,7,9), when I click the button I want to perform function to display a popup box with html table.
Before that I want to pass the value of mcc and mnc and also want to pass the column name (i.e if i clicked the button near 5xx i want pass 5xx if 6xx I want to pass 6xx) to the page where there is a query to display the table. And have separate php code to retrieve th and td from database.
I tried but I don't know how to pass this value to javascript then to php page that contains query to display the table. Thanks
This is my HTML markup:
<table>
<th style="text-align:center;width:92px">MCC</th>
<th style="text-align:center;width:92px">MNC</th>
<th style="text-align:center;width:92px">MNP</th>
<?
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i = 0;
while($rows = mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows[0];
echo "<th>" . $columnArray[$i] . " <span> <img id='logo' src='/image/Picture2.png' style='margin:-62px -21px -9px 32px'></span></th>";
echo "<th style= 'width:20px;'></th>";
$i++;
}
?>
<?php
$sql = mysql_query("SELECT * FROM supplierprice ");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo ' <td class="edit region '.$rows["supp_price_id"].'">'.$rows["region"].'</td>
<td class="edit country '.$rows["supp_price_id"].'">'.$rows["country"].'</td>
<td class="edit networkname '.$rows["supp_price_id"].'">'.$rows["networkname"].'</td>
<td id="mcc" class="edit mcc '.$rows["supp_price_id"].'">'.$rows["mcc"].'</td>
<td id="mnc" class="edit mnc '.$rows["supp_price_id"].'">'.$rows["mnc"].'</td>
<td class="edit mnp '.$rows["supp_price_id"].'">'.$rows["mnp"].'</td>';
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i=0;
while($rows1=mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows1[0];
echo '<td width="0px;" class="edit '.$columnArray[$i].' '.$rows["supp_price_id"].'">'.$rows[$columnArray[$i]].'</td>';
echo '<td><input type="button" onclick="myFunction()" value="" /></td>';
$i++;
}
echo '</tr>';
} ?>
</table>
Javascript
<script>
function myFunction() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "testpage2/config.php";
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
var vars = "mcc="+mcc+"&mnc="+mnc;
hr.open("POST", url, true);
hr.send(vars);
}
</script>
but it not passing the value of mcc and mnc also the column
First of all assign Id to table:
<table>
like:
<table id="contentTable">
Now use below code of jQuery:
$(document).ready(function ()
{
$('#tableId').find('th').each(function ()
{
$(this).click(function ()
{
var thValue = $(this).html();
alert(thValue) // here is value of th on you have click
});
});
});
Cheers!!!
You could try to use something like "generic javascript":
<?php //some stuff
$mcc = "some value";
?>
<script type="text/javascript">
var myVariable = <?php echo $mss; ?>
</script>

Categories