I can't take the value attribute on button | jQuery AJAX - javascript

I made ajax script for delete button and have data attribute based on id on the table in database. This is the HTML :
<textarea name="komentar" id="komentar" cols="30" rows="10"></textarea><br>
<input type="submit" name="submit" id="submit" value="Submit"><br>
<br><br><hr><br>
<!-- Komentar akan ada di dalam sini -->
<div id="komentar_wrapper">
<?php
include_once 'db.php';
$query = "SELECT * FROM komentar ORDER BY id DESC";
$show_comments = mysqli_query($db, $query);
foreach ($show_comments as $comment) { ?>
<p id="komentar_<?php echo $comment['id']; ?>"><?php echo $comment['komentar']; ?>
<!-- data-id-> data attribute, buat spesifik id mana yang mau di hapus -->
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment['id']; ?>">Delete</button>
</p>
<?php } ?>
</div>
And when i try to console the data-id, it wont show the value on console. This is the script :
$(".hapus_komentar").on("click", function() {
console.log($(this).attr("data-id"));
});
When i click the button it say undefined, i think it should print the id based on button data-id

try this i have prepared a demo code for you and runs ok
<?php
$as = array(1,2,3,4,5,6,7);
foreach ($as as $comment) { ?>
<p id="komentar_<?php echo $comment ?>"><?php echo $comment; ?>
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment; ?>">Delete</button>
</p>
<?php
}
?>
<script type="text/javascript">
$(".hapus_komentar").on("click", function() {
alert($(this).attr("data-id"));
//console.log($(this).attr("data-id"));
});
</script>

use Jquery.data(). and use event delegation since your button is generated dynamically.
$(document).on("click",".hapus_komentar",function() {
console.log($(this).data("id"));
});
You can use $(this).data("id") to get the id.

Your code is correct. Just check in HTML weather data-id will have value or not. Maybe that's the reason you are not getting proper value. As well you have taken that button in the loop so make sure on individual button click you will get all buttons data-id.

$(".hapus_komentar").on("click", function() {
console.log($(this).data("id"));
});
now use this.

$(document).on("click",".hapus_komentar",function() {
console.log($(this).attr("data-id"));
});

Related

How do I get my delete button to remove data from database?

I have a delete button which when clicked it prompts user for conformation. It suggets it is working but when I check the database the data is still there.
How do I get my delete button to remove data from the database?
<?php
// build query
$sql= "SELECT blogID, title, made_by, description FROM blogs";
// execute query
$res=$mysqli->query($sql);
// get multiple results
while($row = $res->fetch_assoc()){
$blogID=$row['blogID'];
$title=$row['title'];
$made_by=$row['made_by'];
$description=$row['description'];
?>
<form action = "post_action.php" method="POST">
<div style="text-align:left">
<div class="row">
<div class="leftcolumn">
<div class="card">
<td><?php print($title);?></td><br>
<td> <?php print($description);?> </td> <br>
<td><?php print($made_by);?> </td><br>
<?//Create edit, comment and delete buttons for each blog?>
<button onclick="window.location.href = 'edit_blog.php';">Edit Blog </button>
<input type = "hidden" name="blogID" value= "<?php print($blogID);?>" >
<input type="submit" name="action" value="Insert Comment"/>
<input type="submit" onclick="deleteme(<?php echo $row['blogID']; ?>);" name="action" value="Remove Blog"/>
<? //Javascript code?>
<script language="javascript"> //inserts javascript code
function deleteme(delid)
{
if(confirm("You're about to delete this blog. Click OK to continue or click cancel.")){ //opens an alert window asking the user if they're they want ot remove the blog
window.location.href='post_action.php?del_id=' +delid+''; //If they click OK then it'll run the delete function on post_action.php
return true;
}
}
</script> <?//ends javascript code ?>
</form>
</div>
This is post_action.php
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_POST['blogID']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
Because you did not execute your delete action. Execute your delete query to remove the data to your database.
$mysqli -> query($query)
The problem is in $_POST['blogID'].
You are redirecting the user and passing the blog id in the query string, so it should be $_GET. Also the key is del_id and not blogID.
So in post_action.php, do
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_GET['del_id']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
PS: I am really worried about if you should delete something this way.

Variable assigned to HTML input's value through PHP is not understood by JS script

I'm working on a project of a website which shows a chart. User should be able to change a displayed chart (without changing the website) by clicking one of 'Available sensors' from dropdown options. Dropdown connects to MySQL database with used sensors. The sensor's id is assigned to HTML-input ID and its name is assigned to input value.
My intension is to use sensor ID in another data.php file which is responsible for connecting to tables (MySQL) with data collected by sensors. This ID would tell to which of the tables this programm should connect.
At the moment JS script's task is to alert an ID of the chosen sensor when it's clicked on the dropdown menu. Instead of a number I get a message saying 'undefined'. Eventually it would transfer the stored id to the mentioned data.php file.
Could you please tell me whether it's necessary to use AJAX in this case or what's a possible reason of this error in my code?
I also tried to use button insted of input. When clicking on sensors names on dropdown I've received only messages with '1'. However assigning sensorName worked out in both cases. Sensors ID is stored as INT, name as VARCHAR in MySQL table.
Thank you in advance for your help :)
<div id="header_btn" class="dropdown">
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?>
<input onclick="changeSensorID(this.value)" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>" value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script>
function changeSensorID() {
var sensorID = document.getElementsByClassName("btn_drop").id;
alert(sensorID);
};
</script>
</div>
please check this code, working fine
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?><input onclick="changeSensorID(event)" onmouseover="this.style.textDecoration='underline'"
onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>"
value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script >
function changeSensorID(event){
var sensorID = event.target.id;
alert(sensorID);
}
</script>
</div>
getElementsByClassName returns array of at least one item if found any. You have to provide index of element that you want to use.
Example
var sensorID = document.getElementsByClassName("btn_drop")[0].id;

Create form inside for loop

I'm using codeignitor and am very new to it so sorry in advance if the question is senseless,but i'm stuck with certain requirement while coding.I have a for loop as below:
<?php foreach($messages as $req):?>
//This loop will execute depending on number of rows and is working fine.
<?php echo form_open('message/addFrom_masterlist','id="myform"'); ?>
//form is having input fields.
<?php echo form_close();?>
\\this acts as a submit button to my form which submits the form using javascript.
<input type="button" name="button" id="b1" class="btn btn-primary" onclick="myFunction1()" value="Submit"/>
<?php endforeach; ?>
//Below is javascript code for from submit.
<script>
function myFunction1() {
document.getElementById("myform").submit();
}
the problem is i want the id name for form to be unique since each time a button is clicked same form is being submitted.I don't want to use the submit button inside the form.Please someone help me
use this code
<?php foreach($messages as $req):?>
<?php $count = 1; ?>
//This loop will execute depending on number of rows and is working fine.
<?php echo form_open('message/addFrom_masterlist','id="myform$count"'); ?>
//form is having input fields.
<?php echo form_close();?>
\\this acts as a submit button to my form which submits the form using javascript.
<input type="button" name="button" id="b1" class="btn btn-primary" onclick="myFunction<?php echo $count; ?>()" value="Submit"/>
<?php $count++; ?>
<?php endforeach; ?>
//Below is javascript code for from submit.
<?php
$arrayCount = count($messages);
if(!empty($arrayCount)){
for($i=1; $i<= $arrayCount; $i++){
?>
<script>
function myFunction<?php echo $arrayCount; ?>() {
document.getElementById("myform<?php echo $arrayCount; ?>").submit();
}
</script>
<?php
}
}
?>
Hope this will help you!!
Note: But the your concept like this is not good.

How to make HTML form fields automatically change when an option selected on a select field

Let's say I have a form like this in my CodeIgniter project.
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" name="S_happened">
<?php echo form_close(); ?>
What I want to do is if an user select one status, according to the it's type, show a text field to get an input.
I've made a way to get a type of the status like this: http://localhost/myapp/index.php/status/type/{status_id} where users can pass status ID and it will "echo" the type of the status.
I want to receive it back to the HTML page via a JavaScript method and show those text input fields. How do I do that?
Thank you. :)
As you have jQuery tag, so i suggest you this:
$('select').change(function(){
var inp = this.value.trim();
$(this).parent().find('input[type="text"][name^="'+inp+'"]').show().siblings(':text').hide();
});
I have posted the sample flow as per you want to do. hope this will helpful for you.
PHP:
<?php echo form_open(); ?>
<select>
<?php foreach($status_list as $status): ?>
<option value="<?php echo $status->id; ?>"><?php echo $status->name; ?></option>
<?php endforeach; ?>
</select>
<!-- Show this only if status type is, let's say "E" -->
<input type="text" id="E_happened" name="E_happened">
<!-- Show this only if status type is, let's say "S" -->
<input type="text" id="S_happened" name="S_happened">
<?php echo form_close(); ?>
JAVASCRIPT :
$('select').change(function(){
var statusId = $(this).val();
var statusType = $.get("http://localhost/myapp/index.php/status/type/"+statusId);
if(statusType == 'E')
{
$('#E_happened').value("what do you want here");
}
if(statusType == 'S')
{
$('#S_happened').value("what do you want here");
}
});

Multiple forms with AJAX on one page

I am developing a list of submissions in the admin area of my website, which I can approve/disprove with a form, with an ID of the submission in a hidden input, and the select box with Approve/Reject in. When the select box is changed, the ajax submits the form, along with the hidden ID input, then the PHP script edits the submission in the database.
It was all working fine with one submission (1 form) on the page, but now there is more than one form, it is POSTing the wrong values to the PHP script.
<tbody>
<?php
// connect to mysql
mysql_connect('#######', '#######', '#######');
mysql_select_db('jcvideos');
// query
$query = mysql_query("SELECT * FROM videos");
// loop thru
while($row = mysql_fetch_assoc($query)) {
?>
<tr<?php if($row['accepted']==0) {echo " class='warning'";}?>>
<td><?php echo $row['id'];?></td>
<td>
<a href="//youtu.be/<?php echo $row['ytid'];?>" target="_blank">
<?php
$url = "http://gdata.youtube.com/feeds/api/videos/". $row['ytid'];
$doc = new DOMDocument;
$doc->load($url);
echo $doc->getElementsByTagName("title")->item(0)->nodeValue;
?>
</a>
</td>
<td><?php echo $row['date'];?></td>
<td>
<a href="mailto:<?php echo $row['submitter'];?>">
<?php echo $row['submitter'];?>
</a>
</td>
<td>
<form id="form<?php echo $row['id'];?>" class="reviewform" method="post" action="review.php">
<input type="hidden" value="<?php echo $row['id'];?>" name="vidid">
<select name="status">
<option value="0"<?php if($row['accepted']==0) {echo ' selected';}?>>Pending review</option>
<option value="1"<?php if($row['accepted']==1) {echo ' selected';}?>>Rejected</option>
<option value="2"<?php if($row['accepted']==2) {echo ' selected';}?>>Accepted</option>
</select>
</form>
</td>
<td><?php echo $row['showdate'];?></td>
</tr>
<?php
} // end of loop
?>
</tbody>
</table>
<?php include('../includes/footer.php');?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
</script>
I tried using IDs, then it didn't POST at all. What am I missing here?
You can try this assign common class like i have assigned in fiddle (status) to selectbox then get the form by the change of its children (<select>) like in fiddle i tried to get the id of from by change event of its child element (<select>) ,once you got the id get the data of form and submit it
$('.status').on('change', function(){
var id=$(this).parent("form").attr('id');
alert(id)
$('#'+id).ajaxSubmit();
/* $("#"+id).serialize() form data */
});
See Fiddle
It depends on your event listener/selector:
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
This will always submit .reviewform even if a select of anoter form has been changed.
(Basicly it registers the function for the change event of all select tags in you page)
Please try:
$(".reviewform select").change(function(){
$('.reviewform').ajaxSubmit();
});
$(".anotherform select").change(function(){
$('.anotherform').ajaxSubmit();
});

Categories