value "ID" for the selected row is not parsing on AJAX JQUERY [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an HTML table where the data was retrieved from a database using PHP hence I used a loop to echo the rows. Which created my initial problem of trying to retrieve the correct ID using AJAX. I was recommended using class to create my JQUERY Code I don't knoe what I am doing wrong.
My objective:
I am trying to parse the selected row's ID into my jquery code which then parses into a second php script.
This is my code of the HTML table:
<form id="mainform" >
<table id="table1">
<?php
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
echo "<tr data-rows='$ID'><td>$ID</td>";
echo "<td><input type='hidden' class='hf' value='$ID' /></td>";
echo "<td><input type='button' class='abc' value='select' /></td></tr>";
}
?>
</table>
</form>
This is my JAVASCRIPT code:
<script>
$( document ).ready(function() {
$(".abc").each(function(){
var btn = $(this);
btn.on("click",function(){
$("#newdiv").empty();
var rowId = $(this).closest('tr').attr('data-row');
$('.hf').each(function(){
$.get("boom.php", { ID: rowId } ,function(data) {
$("#newdiv").append(data);
});
});
});
});
});
</script>
I don't know where I went wrong?
I edted the CODE to my latest version

Convert this line
echo "<tr><td>".$ID."</td></tr>";
To this:
echo "<tr data-row='$ID'><td>$ID</td>";
Then, in your javascript, use the power of jQuery to find that attribute in your onClick handler.
btn.on("click",function() {
var rowId = $(this).closest('<tr>').attr('data-row');
}
The variable rowId should now match which row you are on. From there you can pass that in your AJAX calls.
EDIT: You also have mismatched selectors on your jQuery each() function. You have
$("#abc").each(function(){
}
But in the HTML, the button has no ID selector, only a class. Change that line to this:
$('.abc').each(function () {
}

Related

How to use ID from a table and send it to php file for query [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
So I've this admin-dashboard where I want to click on the options link which will take me to another page or show a modal of that particular person's details.
So basically, I want to get the ID of one particular person and send it to backend for query and display the details.
My doctor-details.php file
<?php
require('config.php');
$sql = "SELECT * FROM doctor";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0){
while($rows = mysqli_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['id'];?> </td>
<td><?php echo $rows['f_name'];?></td>
<td><?php echo $rows['l_name'];?></td>
<td><?php echo $rows['email'];?></td>
<td><?php echo $rows['contact_number'];?></td>
<td><?php echo $rows['gender'];?></td>
<td> Options</td>
</tr>
<?php
}
}
?>
my ajax code for doctor's details
//For Doctor
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$.ajax({
url: 'views/admin/doctor-details.php',
type: 'POST',
success: function(result){
$("#response-doctor").html(result);
}
});
});
});
//Hide table on login
$("#show-doctor-details").hide();
$(document).ready(function(){
$("#load-doctor-data").click(function(){
$("#show-doctor-details").show();
$("#show-patient-details").hide();
});
});
window.addEventListener('load', function() {
var trs = document.getElementById('response-doctor').querySelectorAll('tr');
for (var i = 0; i < trs.length; i++) {
var tds = trs[i].querySelectorAll('td');
tds[tds.length-1].querySelector('a').setAttribute('href', '/user/'+tds[0].innerHTML);
}
});
My bad, this sloution more easier (inside doctor-details.php):
<td> Options</td>
You can make entire table row as link
For example:
<tr a="profile.php?id=<?php echo $rows['id'?];">
...
<tr>
This is how you can add link on every row which leads you to profile.php file where you can show personal information. When you are in profile.php you can access person's id with $_GET['id'] and fetch data from database using this id. If you are looking for more detailed answer don't hesitate to ask.

Selecting multiple items to perform a task [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to select multiple items to delete the records in the database. But i am not being able to. My delete.php is fine. How can i use it to delete multiple selected items. I just created a checkbox. How can i make that checkbox work.
echo"<TR><TD>Select</td><TD>S.N.</td><td><B>Full Name</B></td><td><B>Options</B></td></TR>";
while ($myrow = $result->fetch_assoc())
{
echo "<tr><td><input type='checkbox'name='mycheck'onclick='toggleform('document.myform','mycheck','ptext')'></td>";
echo "<TD>".$myrow['id']."</TD>";
echo "<TD>".$myrow['name']." </TD>";
echo "<TD>View ";
echo "Delete ";
echo "Edit";
}
<input type="button" name= "ptext" value="Delete selected">
You have to create checkbox name as array type i.e. mycheck[]. Then, In delete_all.php page, find total checked checkbox and delete it accordingly.
<form method='POST' action="delete_all.php">
<?php
echo"<TR><TD>Select</td><TD>S.N.</td><td><B>Full Name</B></td><td><B>Options</B></td></TR>";
while ($myrow = $result->fetch_assoc())
{
echo "<tr><td><input type='checkbox' name='mycheck[]' value=".$myrow['id']."></td>";
echo "<TD>".$myrow['id']."</TD>";
echo "<TD>".$myrow['name']." </TD>";
echo "<TD>View ";
echo "Delete ";
echo "Edit";
}
?>
<input type="submit" name= "ptext" value="Delete selected">
</form>
delete_all.php
<?
extract($_POST);
$totalCheckboxChecked = sizeof($mycheck);
for($i=0;$i<$totalCheckboxChecked;$i++)
{
$idToDelete = $mycheck[$i];
echo "DELETE FROM table_Name WHERE id_ColumnName = '$idToDelete'";
// Execute Your Querys
}
?>
Are you getting all ids on the delete.php page? if yes then simple use
DELETE FROM tableName
WHERE id IN ($id1 , $id2 , $id3 , etc);
if not, The way i would do it is, i would use form, and then post it in the delete.php page using method post, and then simply take the values from super global
$_POST[]
and use the above query, hope this helps.

Why wont javascript get values of php generated html?

im using ajax to query my mysql to my database.
But im stock at issue with my php generated html form input - javascript/jquery will simply not pick up the value. From normal html is no issue of course.
php (works fine, all echos are good)
<?php
function getAge() {
$age = "<select name='age'>";
$result = $mysqli->query("select * from ages");
while ($row = $result->fetch_row()) {
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
}
$age.="</select>";
return $age;
}
?>
html
<form id="myform">
<input name='name' value='Nick'>
<input name='sport' value='Football'>
<?php echo getAge(); ?>
<input type='submit'>
</form>
javascript
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = {}
$.each(this.elements, function(){
json[this.name] = this.value || '';
});
}
Everything works well except it wont get the value of the <select>. If i make a normal html select it works.. ?!
Also anybody know how to delete the submit button from the json object? :-)
Any dynamically generated HTML will not have the events applied to them, as those events are applied on page load. So if you apply the events to the document, you will be able to pull values from dynamically generated html. Like so:
var json = {};
$(document).on('submit', 'form#myform', function(e){
$('*', this).each(function(){
json[$(this).attr('name')] = $(this).val();
});
});
Hope this helps!
change this line:
$age.="<option value=" . $row[0] . ">". $row[1] ."</option>";
to this:
$age.="<option value='" . $row[0] . "'>". $row[1] ."</option>";
//----------------^---------------^------put quotes
And i think you can make use of .serializeArray() which does the same you want but in a different way like multiple objects with multiple [{ name : value}] pairs:
$(function(){ //<-----put this block too
$("form#myform").on('submit', function(e){
e.preventDefault();
var json = $(this).serializeArray();
}); //<----checkout the closing
}); //<---doc ready closed.

Delete a database row using JQuery

I am using a PHP function to format any 2D PHP array to HTML table, In that table I need to add a delete button in each row, So when the user clicks the delete button jQuery should take particular fields ( 3 fields ) and submit in a php file and it should give the response without reloading the page, I have several dynamic tables in same PHP files, So i have used $table_name as the form ID to differentiate the FORMS, and In the del.php ( Where my form get submitted ) I decide which table should I look up to delete the row using the PRIMARY KEY. My Problem is Do I have to create Forms Within each table to do this task? or can I simply put some fields and submit the form using jQuery?
Any help would be much appreciable .
function formatArrayToTable($foo, $deletable = 0, $restaurant_id ='', $table_name = '') {
//open table
echo '<table class="imagetable">';
// our control variable
$first = true;
foreach($foo as $key1 => $val1) {
//if first time through, we need a header row
if($first){
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<th>'.$key2.'</th>';
}
if($deletable) {
echo "<th>'Delete'</th>";
}
echo '</tr>';
//set control to false
$first = false;
}
echo '<tr>';
foreach($val1 as $key2 => $value2) {
echo '<td>'.$value2.'</td>';
}
if($deletable) {
$primary = $val1["id"];
echo "<input type='hidden' name='table_name' value='{$table_name}' />";
echo "<input type='hidden' name='restaurant_id' value='{$restaurant_id}' />";
echo "<td><input class='delete_class' type=\"button\" name=\"delete_id\" value={$primary} onclick='SubmitForm($table_name)'/></td>" ;
}
echo '</tr>';
}
echo '</table>';
}
My Javascript Function
function SubmitForm(formId){
var message = "";
$("#"+formId+" input").each(function() {
message += $(this).attr("name");
});
$.ajax({
type: "POST",
url: "del.php",
data: message,
success:
function() {
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide()
}
});
}
-Regards
Your question seems to ask if you can remove items from a DB using just jQuery. Conventionally, as far as I know, this is not doable, because your DB is server-side and your jQuery is client-side. That being said, I am sure some kook has created a library for it. Despite that, to answer your actual question:
You need to know how you can use jQuery to simulate direct removal of a table row from a DB table. Here is a rough example of your needed jQuery, a sample output of your current php function, and something that should live in del.php to handle the actual delete.
Example Table
Quick notes. Add thead and tbody tags to help browsers with the displaying. Remove the onclick="" bit, you are using jQuery, so just add your callbacks with a JavaScript block. Make sure your code adds the `.submittable' class (or other descriptive name) to your table. You could wrap the whole table in a form, then use a plugin like jquery form to handle submissions of each form, but that seems like overkill for only handful of fields, so I will explain how to do it with the raw materials.
<table class="imagetable submittable">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>file</th>
<th>meta</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type='hidden' name='table_name' value='secret_image_table' />
<input type='hidden' name='restaurant_id' value='123' />
<input class='delete_class' type='button' name='delete_id' value="Delete" />
</td>
<td>Silly Cat Image</td>
<td>yarny-cat.jpg</td>
<td>{"submitter":"De Zéro Toxin"}</td>
</tr>
</tbody>
</table>
jQuery code block
It is a terrible idea to submit your table name from any client-side form, ajax or otherwise. That is super sensitive information, and any programmer/hacker could use that knowledge to their advantage when trying to attack your site. Despite that, I don't know the usage of this, so it may be fine in your setting. Still bad practice though.
// any time any element with the 'delete_class' on it is clicked, then
$(document).on('click', '.delete_class', function(e) {
var row = $(this).closest('tr');
var data = {
table: $('[name="table_name"]').val(),
id: $('[name="restaurant_id"]').val()
};
$.post('del.php', data, function(r) {
// do some special stuff with your json response 'r' (javascript object)
...
// do what you showed us you are doing, displaying a message
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Entry is Deleted </p>")
.hide();
// remove the row, since it is gone from the DB
row.remove();
}, 'json');
});
del.php
Again, table_name on submission = bad-idea. Horse beaten.
// define a delete function that accepts a table name an id
// define some functions to sanitize your $_POST data, to prevent SQL Injection.
// run said functions before you get to this point
// json response function, since you said you want a response from your js
function respond($data) {
echo #json_encode($data);
exit;
}
if (empty($_POST)) respond(array('error' => 'Invalid request'));
$table_name = $_POST['table_name'];
$id = $_POST['id'];
$response = deleteRecord($table_name, $id);
if ($response == $what_you_expect_on_a_successful_delete) {
// create a response message, in associative array form
$message = array('success' => true);
// add some other information to your message as needed
$message['sideNote'] = 'I like waffles.';
// respond with your message
respond($message);
}
// if we got this far your delete failed
respond(array('error' => 'Request Failed'));
Hope this helps.
If you really want to use jQuery to delete a row in a DB directly, you will need to establish a DB connection from jQuery. Not such a bright idea. Instead, you should have a server side function to do the job and call that function using an AJAX call from jQuery.

JQUERY .val not working......HTML table created using PHP unable to get the specific row value

I have created a HTML table using a echoing each row in a by looping through the rows of the database which is stored into the PHP fetch array function after retrieving from the database using the SELECT statement. Along with this I added another column which is a submit button hence it looped through every each row.
I did this so that I could get the "ID" of each row when submitted and run another script using AJAX JQUERY. But the problem is that my javascript code only gets the value of the first row when submited and it is unresponsive to the other rows.
Table code:
<form id="mainform">
<table>
<th>ID</th>
<?php
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result)) {
$ID = $row['ID'];
echo "<td><input type='hidden' id='hiddenfield' value='$ID'></td>";
echo "<td><input type='submit' value='select' /></td>";
}
?>
</table>
</form>
Javascript:
$("#mainform").on("submit", function(){
$("#testdiv").empty();
$.get("boom.php", { ID: $("#hiddenfield").val() },
function(data) {
$("#newdiv").append(data);
});
});
</script>
With this AJAX code I am trying to get the value to boom.php where now I am just testing if the correct value has been parsed.
Anyone can help me out? I am stuck...
There are two problems: first, you can't reuse the same id on multiple fields. They must be unique. Use a class:
echo "<td><input type='hidden' class='hiddenfield' value='$ID'></td>";
even then, .val() will only return the first matching item's value.
Assuming you want to pass a list of ID values, you'll need to build the list yourself:
$("#mainform").on("submit", function(){
$("#testdiv").empty();
var vals = [];
$('.hiddenfield').each(
function() {
var field = $(this);
vals.push(field.val());
}
);
$.get("boom.php", { ID: JSON.stringify(vals) },
will pass a string version of the list (e.g. ["1","2","3"]);
If you want to send each ID separately, do so within the each loop:
$('.hiddenfield').each(
function() {
var field = $(this);
$.get("boom.php", { ID: field.val() },
}
);

Categories

Resources