Getting ID value of clicked row - jquery - php

ok .. quick overview.
I have a table and each row has the ID attribute value assigned based on the ID form the db record
I have a click event that shows / hides a div and I want the data it displays
in that div to be based on the results from the DB for that corresponding ID value
Here is my table code showing the ID
<td class="hidden-xs">
<a data-toggle="toggle" href="#comp_info" class="showcompinfo" id="<?php echo $complistr['company_id'];?>">
<?php echo $complistr['registered_office_address'];?>
</a>
</td>
This is where I want the data displayed
<div class="panel-heading">
<i class="fa fa-building" style="color:orangered"></i>
<span id="showcompname"></span>
</div>
Here is the jquery code
$(document).ready(function () {
$('#comp_info').hide();
$('.showcompinfo').click(function () {
var id = $('.showcompinfo').attr('id');
$('#comp_info').toggle();
var companyid = id;
var dataString = 'companyid=' + companyid;
$.ajax({
type: 'POST',
url: '../inc/dataforms/complist.php',
data: dataString,
success: function (result) {
$('#showcompname').html(result);
}
});
});
});
Here is the PHP code for the query
include('../config.php');
if (!empty($_POST['companyid'])) {
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc, "SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if ($result) {
echo $result['name'];
}
}
Please dont say .. your code is open to SQL injection .. i've said before its on a closed system with no external access and the people using it can barly use a PC
All I want it to do is to display the company name in the showcompname span box
If possible am I also able to display different result data in different divs ?

To retrieve the ID from the clicked <a> tag, in your jQuery code change this line:
var id = $('.showcompinfo').attr('id');
For this one:
var id = $(this).attr('id');
That way you are retrieving the id attribute from the element that was the target of the click event.
Your original code was retrieving an array of ids of all elements with the class showcompinfo.

Your problem lies in the selector for the id, var id = $('.showcompinfo').attr('id');.
You are selecting every showcompinfo in the page.
You would be better off by using this in that selector.
This would correctly select your id, based off the clicked td.
var id = $(this).attr('id');

Related

Php delete images from mysql table without showing ID to frontend

My Database tables:
posts:
ID
post_title
etc.......
12
Title
more
images:
ID
post_id
img_url
1
12
uploads/61d878f77397a4.61355537.jpg
My current method of deleting images:
<?php
$stmt_images = $conn_posts->prepare("SELECT * FROM `images` WHERE `post_id` = ?");
$stmt_images->bind_param("i", $row['ID']);
$stmt_images->execute();
$stmt_images_results = $stmt_images->get_result(); // get result
while($row_image = $stmt_images_results->fetch_assoc()){
echo '<img src="'.$row_image['img_url'].'">';
echo '<button id="delete_button" type="button" data-id="'.$row_image["ID"].'">Delete</button>';
}
?>
Ajax:
<script>
$(document).ready(function() {
$('#delete_button').on('click', function() {
var deleteId = $(this).data('id');
var x = confirm("Are you sure you want to delete?");
if(x){
$.ajax({
url: "inc/ajax/delete_images.php",
type: "POST",
data: {
iid: deleteId,
},
cache: false,
success: function(result){
$("#info").html(result);
}
});
}
});
});
</script>
Then in inc/ajax/delete_images.php:
I run a simple delete query based on the iid, "iid = ID of the image row"
Now a frontend user can change that data-id I am blocking that by checking in delete_images.php that only the owner of the post can delete the images related to the post that was submitted but i thought of checking some websites and i see OLX does not have any id or hidden input or data variables how can I delete and images without displaying ids frontend as i dont like using data-id
I know I am doing backend checking but i want to make it even more secure by not showing the images ID
OLX Code image:

PHP AJAX HTML: changing unique table data in foreach loop

I'm new to PHP and Ajax. I am trying to create a table of object data where I can select the displayed data based on a <select><option>... form.
I have a PHTML template which looks like the following:
<?php
$content = "";
// creates data selector
$content .= "
<form id = select_data>
<select id = data_selection>
<option value = data1>Data 1</option>
<option value = data2>Data 2</option>
<option value = data3>Data 3</option>
<option value = data4>Data 4</option>
</select>
<input id = selected_data type=submit />
</form>";
// creates table header
$content .= "
<tr>
<th>Data</th>
</tr>";
$array_ids = array(1, 2, 3); // etc, array of object id's
foreach ($array_ids as $array_id) {
$object = // instantiate object by array_id, pseudocode
$object_data = $object->getData('default-data'); // get default data to display
// create table item for each object
$content .= "
<tr>
<td><p>$object_data</p></td>
</tr>";
}
print $content;
?>
This prints out the table content, loads objects by their id, then gets and displays default data within the <p> tag.
And then I have some Javascript which looks like the following:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){ // get selected data type
e.preventDefault();
var data_selected = $("#data_selection :selected").val(); // create var to pass to ajax
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected},
success: function(data){
$("p").html(data); // replace all <p> tag content with data
}
});
});
});
</script>
This Javascript gets the selected data type, creates a variable out of it to pass on to the ajax which then calls post.php, which looks like the following:
<?php
$attribute = false;
if (isset($_POST['data_selected'])){
$data = $_POST['data_selected']; // assigns variable out of ajax data
$object = //instantiate object, again pseudocode
$object_data = $object->getData($data); // get new data to replace into the ```<p>``` tag
echo $object_data;
}
?>
The problem is that the Javascript that I have changes every single <p> tag to the last data iterated by the foreach loop because each <p> tag is not uniquely identified and the Ajax does not update the data based on a unique identifier, such as maybe the $array_id. Which brings me to my attempted solution.
I tried to identify each <p> tag with the following:
<td><p id = $array_id>$object_data</p></td>
And then creating a new Javascript variable out of the array ID:
var p_tag_id = <?php echo $array_id; ?>;
And finally making the Ajax success function target element ID's based on var p_tag_id:
$("#" + p_tag_id).html(data);
While this does not change all the <p> tags like previously, it only changes the final <p> tag and leaves all instances before it unchanged because the Javascript is not iterating over each <p> tag, or because the foreach loop does not call the Javascript as a function for each $array_id.
How can I rewrite this code so that the Ajax updates the data of each table item uniquely instead of updating them all with the same data? Is there a better way to approach this problem?
You need a way to identify the table row containing the <p> tag you wish to update, and perhaps the value attribute of the SELECT element could help.
You can get the number of the clicked option from your data_selected variable by using slice to strip-off the last character (i.e. the number):
var num = data_selected.slice(-1) - 1;
(Subtract 1 because the table rows are zero-indexed)
Then, in the AJAX code block's success function:
$('table tr').each(function(i,v){
if (i == num){
$(v).find('td').find('p').html(data);
}
});
The above grabs all the table rows (as a collection) and loops through them one-by-one. In the function, i is the index number of the row and v is the row itself. Index numbers begin at zero, which is why you earlier subtracted 1 from the (for eg) data3 [3] value, leaving num == 2. When you find the right row number, use .find() to find the <td> in that row, and then the <p> in that <td> and Bob's yer uncle.
I haven't tested the above code so there could be bugs in the example, but off-the-cuff this approach should work.
I figured out a solution. I assigned the $array_id to each <p> tag after all in order to identify them uniquely:
<td><p id = $array_id>$object_data</p></td>
Then I looped over all the <p> tags and assigned the $array_id of this <p> tag to a variable like so:
$("p").each(function() {
var array_id = $(this).attr("id");
And finally I made the Ajax success target elements based on their ID:
$("#" + array_id ).html(data);
Here is the full Javascript code for anybody who is interested. Hopefully this helps someone else out!
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){
e.preventDefault();
var data_selected = $("#data_selection :selected").val();
$("p").each(function() {
var array_id = $(this).attr("id");
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected, array_id: array_id},
success: function(data){
$("#" + array_id).html(data);
}
});
});
});
});
</script>

Delete button works on only first row not on the rest of the rows

I have fetched the values(card details) from an array and put them in an html table, I have also added the delete button for deleting the particular card.
I am deleting this through ajax. When i click on the delete button of the first row, it works perfect but when i click on the other delete buttons from 2nd or 3rd row, there is no action.
Please suggest the correct path to sort out this problem.
Thanks in advance
Here is my code
<tr>
<td><?php echo $val['last4'];?></td>
<td><?php echo $val['exp_month'];?></td>
<td><?php echo $val['exp_year'];?></td>
<td><button id = "del">Delete</button></td>
</tr>
Ajax part
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$('#del').click(function() {
//var a=document.getElementById("").value;
var val0 = $('#id').val();
var val01 = $('#cust').val();
var fade = document.getElementById("fade");
var show = function(){
fade.style.display = "block";
}
show();
$.ajax({
type: 'POST',
url: 'mywebsite.com/deleting.php',
data: { card_id: val0,cust_id: val01 },
success: function(response) {
fade.style.display = "none";
// alert(response);
mystring = response.replace(/^\s+|\s+$/g, "");
$('#result11').html(mystring);
}
});
});
</script>
You have the same id on your buttons. Id's must be unique within the html document and can not be shared between multiple elements. Read more about the html id attribute
Change the button to use a class instead:
<td><button class="del">Delete</button></td>
Then change your jQuery to bind to that class instead:
$('.del').click(function(e) {
// Since we're using ajax for this, stop the default behaviour of the button
e.preventDefault();
// Get the value from the clicked button
var val0 = $(this).val();
I also added the event e in the function call, and stopped the default behaviour of the button (which is to submit the form) when it's clicked.
You need to give delete buttons a class and bind event on that class not with id. Then on bind function select values from that row elements and then pass them to Ajax.

jquery to get database query based on user click and populate select list

I am working on a form where a user can select a letter from A - Z to select a list of users whose username begins with that letter.
What i am trying to do is when the user clicks a letter, a php script is called to do a database query that pulls any username which begins with the clicked letter.
I have found this page which has started me off http://openenergymonitor.org/emon/node/107 and also this one which is closer to what i want to do Simple Ajax Jquery script- How can I get information for each of the rows in the table?
What i want to do with the returned results is put them in a SELECT list and also when a user click a different letter, that list contents is replaced with the new query results.
What i'm not sure is how to and if possible pass the letter to the php script so i can search the database for usernames that begin with that letter.
EDIT: I have got it hopefully improved to this but i'm getting Ajax error: ParseError
this is my code so far
<div>
<ul>
<li class="alphabets" id="All">All</li>
<li class="alphabets" id="A">A</li>
<li class="alphabets" id="B">B</li>
<li class="alphabets" id="C">C</li>
<li class="alphabets" id="D">D</li>
</ul>
</div>
<div id="recipients">
$(document).ready(function(){
$("li.alphabets").click(function(){
var the_letter = $(this).text();
alert(the_letter);
$.ajax({
url: 'php/selectuser.php', type: 'GET', data: {'letter':the_letter}, dataType: 'json', success: function(rows) {
var options = '';
for (var i in rows) {
var row = rows[i];
var id = row[0];
var vname = row[1];
options += '<option value="' + id + '">' + vname + '</option>';
}
$("#userlist").html(options);
}
});
});
});
<select id="userslist" name="recipients" size="5">
</select>
</div>
jQuery's .ajax() method has a parameter called data which allows you to pass variables:
// Get letter from SELECT element
the_letter = $("#myselect").val();
$.ajax({
url: 'somepath/to/my/script.php',
type: 'GET',
data: {'letter':the_letter}
});
It is passing it as a GET parameter, easily retreivable in your PHP script with:
$letter = $_GET['letter'];

Displaying data as a table using $.ajax() and jQuery

I'm new to jQuery and PHP.
I'm developing a web page to display a set of records taken from a database. Here I have used PHP and jQuery.
I need to display a set of records as a table. Data is retrieved from a MySQL database using php. Set of rows is passed to the html page as a string using json_encode().
The problem is that I can't display those data in a table row by row. I'm using a table created with <div>. So I need to know how to display this string of data row by row and separating the value for each column.
Here is what I have done to display only one row, but the data is not displayed as a table. No compile error either. I need help to extend this to display multiple rows too.
demo.html (page I'm going to display the records):
<div class="table">
<div class="headRow">
<div class="cell">ID</div>
<div class="cell">First Name</div>
<div class="cell">Last Name</div>
<div class="cell">Age</div>
<div class="cell">Class</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'beta.php' ,
data:"",
dataType: 'json',
success:function(data){
var elementArray = new Array(); //creating the array
elementArray = data.split(""); //splitting the string which was passed using json_encode()
var id = elementArray[0]; //passing values corresponding to the columns
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
$("<div>", { //creating a new div element and assiging the value and appending it to the column 1
"class":"cell",
"text":id
})
.appendTo("document.body");
$("<div>", { //cloumn 2 value
"class":"cell",
"text":fnam
})
.appendTo("document.body");
$("<div>", { //cloumn 3 value
"class":"cell",
"text":lname
})
.appendTo("document.body");
$("<div>", { //cloumn 4 value
"class":"cell",
"text":age
})
.appendTo("document.body");
$("<div>", { //cloumn 5 value
"class":"cell",
"text":grade
})
.appendTo("document.body");
}
});
});
</script>
</div>
</div>
demo.php (retrieving data from the database):
$result = mysql_query("SELECT * FROM student WHERE StuId=1",$con) or die (mysql_error());
$resultArray = mysql_fetch_row($result);
echo json_encode($value);
If someone can help me it would be a great.
try this one....
var id = elementArray[0];
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
then create table using these values something like this....
$("<table>").appendTo("document.body");
$("table").html("<tr><td>"+id +"</td><td>"+fname +"</td><td>"+lname +"</td><td>"+age +"</td><td>"+grade +"</td></tr>);
Here is a Jfiddle, if you use .html and append to a empty table on your page you can append the var contents returned from your ajax query just the same
http://jsfiddle.net/L4G79/1/
this your code will look something like
var id = elementArray[0]; //passing values corresponding to the columns
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
$("table").html("<tr><td>"+id +"</td><td>"+fname +"</td><td>"+lname +"</td><td>"+age +"</td><td>"+grade +"</td></tr>");

Categories