PHP: multiple button with different name to update MySQL database with AJAX - javascript

I have an problem, I have multiple button generate with while, with different names (button[$nostation]).
Now, I want to update MySQL database (table: smt, column: no) with the same id ($nostation).
How I can generate AJAX function for that?
This is my code:
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
echo "
<div class='col-xs-2-2'>
<form action='coba.php' method='post'>
<button name='button[$nostation]' value='2' style='background-color:#02780d; width:140px; height:75px; margin : 2px; border-radius:10%;'>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
";}?>
And this is my code for update database with PHP:
<?php
include 'connect.php';
$array=$_POST['button'];
foreach ($array as $nostation => $value) {
$updch=mysqli_query($connect,"UPDATE smt SET status='$value' WHERE no='$nostation'");
}?>
How I can update with AJAX without refreshing the page?

View Part :-
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
?>
<div class='col-xs-2-2'>
<form method='post'>
<input type="hidden" value="<?php echo $nostation;?>" id="name_<?=$nostation;?>" name="name">
<button type="submit" id="button_<?=$nostation;?>" data-id="<?=$nostation;?>">SAVE</button>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
<?php } ?>
jQuery / AJAX Part:-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ //when DOM is Ready.
$("[id^=button_]").click(function () { //when Button is Clicked.
var id = $(this).data('id'); // Get the ID of the button that was clicked on.
var name = $("#name_"+id).val(); // value from `input` which is connected the clicked button.
// console.log(id+"---"+name);
$.ajax({ // AJAX request
url: 'update.php', // send request to server.
method: 'POST', // method is POST.
data: { //data which is sent to server.
id: id,name: name
},
success: function (data) { //success function called.
alert(data); // alert success data.
}
});
});
});
</script>
update.php:-
And in the php-side We catch it by:-
echo $id = $_POST['id'];
echo $name = $_POST['name'];
//use update query.
Note:- For more info regarding click()
https://api.jquery.com/click

Related

PHP / MySQL: Error in multiple delete, only latest ID deleted

I got some problems with my code. I want to delete multiple data from MySQL database that populate from Select Option.
Example: I select data with id 5, 2, 4, then press the delete button, it only deletes the latest id which is 5.
Can I know what is the problem? Below is my code:
index.html
<?php
include("configPDO.php");
$smt = $conn->prepare("SELECT * FROM frame_list ORDER BY framework_name ASC");
$smt->execute();
$results = $smt->fetchAll();
?>
<form method="post" id="multiple_select_form">
<select name="framework[]" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
<?php foreach ($results as $row2): ?>
<option value= <?php echo $row2["framework_id"]; ?>><?php echo $row2["framework_name"];?></option>
<?php endforeach ?>
</select>
<br><br>
<input type="hidden" name="framework_id" id="framework_id" />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
$('#multiple_select_form').on('submit', function(event){
event.preventDefault();
if($('#framework').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"delete.php",
method:"POST",
data:form_data,
success:function(data)
{
//console.log(data);
$('#framework_id').val('');
$('.selectpicker').selectpicker('val', '');
alert(data);
}
})
}
else
{
alert("Please select framework");
return false;
}
});
});
</script>
delete.php
<?php
include("configPDO.php");
$smt = $conn->prepare("DELETE FROM frame_list WHERE framework_id = '".$_POST["framework_id"]."'");
$smt->execute();
if($smt){
echo "Data DELETED";
}else{
echo "Error";
}
?>
Appreciate it if anyone can solve my problem.
Thank you very much.
this is where framework id got overwritten:
$('#framework').change(function(){
$('#framework_id').val($('#framework').val());
});
delete.php will only run when your ajax request send(in this case, when you click submit button).
so maybe you'll want to pass several id at a single request if you want delete them at the same time. or you may want to delete them one by one by sending the ajax request each time you choose a id.

Submit button intermittently not submitting form information

So I've got this form for adding comments under a post. The methods utilized here are MYSQL(holds the submitted form data in a database) PHP(communicating with the database) and JavaScript, more specifically AJAX (for hooking up the submit button and handling events).
Typing in your comment into the form and pressing submit is supposed to print the comment onto the screen.
When I click submit, it doesn't print anything. Then, when I type another comment and click submit once more, it prints the contents of that comment. Other times, it successfully prints the contents of the comment instead of failing to submit.
I checked it out in inspect element and in the console log, whenever it misses, it still sends some blank <p> tags through with the class of the comment that should be submitted.
The PHP page for the comment form:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="Forums.css">
</head>
<body>
<?php
$result = mysqli_query($link, $displayPost); ?>
<?php $row = mysqli_fetch_assoc($result);?>
<p> <?php echo $row["title"];?> </p>
<br>
<p> <?php echo $row["body"];?> </p>
<form action="<?php echo $url ?>" method="post" id="form-group">
<div class="forum col-md-12">
<textarea type="text" style="overflow: auto; resize: none;" name="body" class="txtBody"></textarea>
<input type="submit" name="submit" class="btnCreate" style="margin-bottom: 4px;">
</div>
</form>
</body>
<script>
function refreshData() {
$.ajax({
type:'GET',
url: 'getcomments.php?id=<?php echo $id ?>',
dataType: 'html',
success: function(result){
console.log(result);
$('#comments').html(result);
}
});
}
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData
});
refreshData();
event.preventDefault();
});
});
</script>
<div id="comments"></div>
The PHP page for getting previously submitted comments and printing them on the screen
<?php
$link = mysqli_connect("localhost", "root", "WassPord64", "forum");
$id = $_GET["id"];
$displayPost = "SELECT * FROM comments WHERE post_id='$id'";
$link->query($displayPost);
$result = mysqli_query($link, $displayPost);
if (mysqli_num_rows($result) > 0) :
// output data of each row
while($row = mysqli_fetch_assoc($result)) :
$row = mysqli_fetch_assoc($result);?>
<p class="postBody"><?php echo $row['body'];?></p>
<?php endwhile; ?>
<?php endif; ?>
You are calling refreshData() when the Ajax is not done. You can make a callback function by using $.ajax.success
Try this:
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData,
success: function(){
refreshData();
}
});
event.preventDefault();
});
});

PHP search using AJAX with checkbox

How do I let AJAX know what I have checked with checkbox? I have a list of categories that are selected from a database. So how do let the AJAX know what I have checked?
This is my search PHP:
<div class ="search-category-container">
<div class ="search-category-header featured-header">
<label class ="featured-font">category</label>
</div>
<div class ="search-category-content">
<?php
$result=mysqli_query($connection,"SELECT * FROM category");
while($row= mysqli_fetch_array($result)) { ?>
<label class="checkbox category-list ">
<input type="checkbox" name="category_list[]" value="<?php echo $row['name']; ?>" form="search-form"><?php echo $row['name']; ?>
</label>
<?php
}
?>
</div>
</div>
This is my search function using on search before without AJAX. Now I was trying to use AJAX to get data can I use back the function?
<?php
if($filter == "post" && $time == "all" && $status == "all" && isset ($_POST['category_list'])) {
foreach ($_POST['category_list'] as $category) {
$result = mysqli_query($connection, "SELECT * FROM category WHERE name IN ('$category')")or die(mysqli_error($connection));
while($row= mysqli_fetch_array($result)) {
$getCategory = $row['id'];
$getPostIDRow = mysqli_query($connection, "SELECT * FROM post_category WHERE category_id = '$getCategory'") or die(mysqli_error($connection));
while($row2= mysqli_fetch_array($getPostIDRow)) {
$getPostID = $row2['post_id'];
$result2 = mysqli_query($connection,"SELECT * FROM post WHERE title LIKE '%$search%' AND id = '$getPostID'") or die(mysqli_error($connection));
$count2 = mysqli_num_rows($result2);
if($count2>0) {
while($row2= mysqli_fetch_array($result2)) {
$postID = $row2['id'];
$result3 = mysqli_query($connection, "SELECT * FROM user_post WHERE post_id = '$postID'") or die(mysqli_error($connection));
while($row3 = mysqli_fetch_array($result3)) {
$getUserName = mysqli_query($connection, "SELECT * FROM user WHERE id = '".$row3['user_id']."'")or die(mysqli_error($connection));
while($row4 = mysqli_fetch_array($getUserName)) {?>
<div class ="post-container" id="search-container">
<div class ="post-header-container">
<div class ="post-header">
<a href ="post.php?id=<?php echo urlencode($row2['id']);?>&user=<?php echo $row3['user_id']; ?>">
<p class ="post-header-font"><?php echo ($row2['title']); ?></p>
</a>
</div>
<div class ="post-user">
<p class ="faded-font">by : <?php echo $row4['username']; ?></p>
</div>
</div>
<div class ="post-content-container">
<p class ="post-content-font">
<?php echo ($row2['summary']); ?>
</p>
</div>
<div class ="post-info-container">
<div class ="post-info">
<span class ="glyphicon glyphicon-eye-open"> views: <?php echo ($row2['views']);?></span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-pencil"> answers:</span>
</div><div class ="post-info">
<span class ="glyphicon glyphicon-ok"> status: <?php echo ($row2['status']);?></span>
</div>
</div>
</div><?php
}
}
}
}
}
}
}
?>
This is AJAX search function
$(document).ready(function(){
function search() {
var searchWord = $("#search").val();
var filter = $("#filter:checked").val();
var time = $("#time:checked").val();
var status = $("#status:checked").val();
$.ajax({
type:"post",
url:"searchFunction.php",
data:"search="+searchWord+"&filter="+filter+"&time="+time+"&status="+status,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
$("#searchButton").click(function(){
search();
});
$("#search").keyup(function(e){
if(e.keyCode == 13) {
search();
}
});
});
To answer you ajax question I highly recommend changing your code to use the 'form' DOM for user experience and easier maintenance, just fyi and use the serialize function which will also send out the 'checked' checkboxes.
https://api.jquery.com/serialize/
function search() {
var postData = $('myForm').serialize(); // i.e <form id="myForm">
$.ajax({
type:"post",
url:"searchFunction.php",
data: postData,
success:function(data) {
$("#searchContainer").html(data);
$("#search").val("");
}
});
}
That will do all the work for you automatically instead of having to run a bunch of jQuery selection calls and putting together the HTTP query your self. If you ever need to know what your ajax is running. Go in inspector mode of your browser and look for "Network" tab, click that and you should see the ajax call to that search file, with everything you need to know. What HTTP request and response headers are and body.
P.s make sure you return false on the submit event and that the name of the fields on your HTML form match the $_POST key names for the ajax.
$("#myForm").on('submit', function(){
search();
return false;
});
Good luck!

Filling form with Jquery click function

I'm trying to create a GUI to let the user edit any row that is displayed in my table. I've manage to create a form that pops up when the user clicks an image which symbolize an edit icon. Now I like to use Jquery (if possible) to fill this form with data from my DB. The error code is down bellow and I can't seem to get any results at all
Script
<script type="text/javascript">
$(document).ready(function(){
$('#edit').click(function() {
$.ajax({
url: 'edit.php?itemid=$itemid',
success: function(response) {
$('#itemid').val($itemid);
......
$('#status').val($status);
}
});
});
});
</script>
Edit.php
<?php
$DB = new mysqli("localhost", "root", "", "book1");
$result2 = mysqli_query($DB, "SELECT * FROM booking WHERE itemID='$itemid'");
while($row = mysqli_fetch_array($result2)){
$itemid = $row['itemID'];
......
$status = $row['status'];
}
echo (array($itemid, $userid, $description, $manufacturer, $model, $caldate, $duedate, $shelf, $status);
?>
Form
<div id="light1" class="white_content">
<form id="editform" name="myForm" action="checkout.php" method="POST">
<h2>Edit Instrument</h2>
<label>ItemID:</label>
<input type="text" id="itemid"/>
<br>
......
<a>Status: </a>
<input type="text" id="status"/>
<br>
<input type="submit" value="Accept">
<input href = "javascript:void(1)" onclick = "document.getElementById('light1').style.display='none';document.getElementById('fade').style.display='none'" type="reset" value="Close">
<br>
</form>
</div>
Error
ReferenceError: $itemid is not defined
$('#itemid').val($itemid);
change
$('#itemid').val($itemid);
to
$('#itemid').val('<?php echo $itemid; ?>');

AJAX comment system Validation problems

So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique

Categories