I've got a page where I display rows from MySQL table.
while($row2 = $result2->fetch_assoc()) { ?>
<p>
<span class="label label-primary">
<?php echo ($row2["miasto"]); ?>
</span>
<span class="label label-primary delete" id="<?php echo ($row2["miasto"]); ?>"><i class="fa fa-times"></i></span>
</p>
on a span click .delete I would like to get this row deleted from a database and page refreshed without those rows and with alert to be present.
I'm able to do a on click action in Jquery:
$(document).ready(
function(){
$(".delete").click(function () {
$.post( "miastousun.php", { mdu: (this.id)} );
and than on php of miastousun.php:
$sql = "DELETE FROM miasta_zmiany WHERE Miasto_dodaj='".($_POST['mdu'])."";
but does not seem to work. What I'm doing wrong?
Try this ajax code.
$( document ).on( 'click', '.delete', function() {
var thisId = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'miastousun.php?mdu='+thisId,
success: function(data){
alert('Message something');
},
error: function(errorThrown){
alert(errorThrown);
}
});
});
Related
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();
});
});
Loading image being displayed below the button of 1st result in while loop no matter which button is clicked from which result. For example, if I click submit button on the first result the loading image is displayed below it. That's okay. But when I click on the submit button of any other result except the first then also the loading image is displayed below the first result only and not below the submit button of that particular result.
<?php while($a = $stmt->fetch()){ ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $mbs_id; ?>" class="memid">
<select class="validity" class="upgrade-valsel">
<?php while($mv = $mval->fetch()){ extract($mv); ?>
<option value="<?php echo $mv_id; ?>"><?php echo $mv_validity; if($mv_validity == 1){ echo " month"; }else{ echo " months"; } ?></option>
<?php } ?>
</select>
<input type="submit" value="Upgrade" class="submit">
<div class="center-align" style="margin-left: -20px"><img src="images/loading.gif" width="auto" id="loading-rent" style="margin-right: 0px; height: 40px"></div>
</form>
<?php } ?>
Script
$(document).ready(function() {
$(".submit").click(function () {
var dataString = {
memid: $(this).parent().find(".memid").val(),
memname: $(this).parent().find(".memname").val(),
validity: $(this).parent().find(".validity").val()
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to upgrade your membership to ' + dataString.memname + '?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "upgrade-process.php",
data: dataString,
cache: true,
beforeSend: function () {
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function (json) {
setTimeout(function () {
$(".message").html(json.status).fadeIn();
$("#submit").show();
$("#loading-rent").hide();
}, 1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Upgrade Cancelled!</span>');
}
}
});
return false;
});
});
Use .classes when it comes to generating a number of elements with a loop.
Use #id for unique elements.
To fix your code do the following:
add and fix any missing class
replace all id attributes in your code with class
use event delegation to listen for click event on any submit button. Read the following: jQuery API Docs on event delegation
On the following line you have set an id tag for the loading image; this has to be unique for each iteration of the while loop otherwise you get problems like you're experiencing. Either use unique ids and/or use javascript to select the nearest loading image to display.
<div class="center-align" style="margin-left: -20px"><img src="images/loading.gif" width="auto" id="loading-rent" style="margin-right: 0px; height: 40px"></div>
I have an code where it is supposed to delete the data without refreshing. the delete process works but i have to refresh to to remove the data.
heres my code please help me
Ajax:
$(function () {
$(".trash").click(function () {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type: "POST",
url: "delete.php", //URL to the delete php script
data: info,
success: function () {}
});
$(this).parents(".record").animate("fast").animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
Here's my html:
<td style="padding-left: 23px">
<img class="photo" data-toggle="modal" data-target="#gallery<?php echo $photo; ?>" src="<?php echo $r1['photo']; ?>" />
<div class="hotel">
<button class="trash" id="<?php echo $r1['photo_id']; ?>" > <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</td>
If I hover the button to the image the .trash button will appear and if I click it the image must be deleted. help me please.
You can give a data image id attr to parent tr,
<tr data-image-id="<?php echo $r1['photo_id']; ?>">
After successful delete process (in your ajax success function) you can run code below.
$("tr[data-image-id="+del_id+"]").remove();
Your code works, maybe do you need show the complete html, or at least the classes ".record" to analyze the "error"
No need to add extra attribute for ID in table row(TR).
$('.glyphicon-remove').on('click',function() {
$(this).closest( 'tr').remove();
return false;
});
Try This:
function delete_value(id)
{
if(confirm('Are you sure you want to delete this?'))
{
// ajax delete data from database
$.ajax({
url : "<?php echo site_url('yoururl/del')?>/"+id,
type: "POST",
success: function(data)
{
$("tr[id="+id+"]").remove();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
<button class="btn btn-danger" onclick="delete_value(<?php echo $row->id;?>)"><i class="glyphicon glyphicon-remove"></i></button>
<!--- add tr id --->
<tr id="<?php echo $row->id; ?>">
var num = parseInt($.trim($(this).text()));
$(this).html('<i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"></i>', ++num);
After a certain div gets clicked the count must go up. This actually works but alongside with that an icon has to be added to the clicked div. How would I do this? The above sample work, but only the <i> gets inserted.
EDIT:
The dataset-postid="{{ $post->id }}" defines the post_id that has this like button. What has to be changed is {{ $likes}}
```
<div class="wis-numbers">
<?php $likes = $post->likes->count() ?>
<span id="like" class="like" data-toggle="tooltip" data-placement="bottom">
<i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"></i>
{{ $likes }}
</span>
</div>
I tried to solve this with only updating text with Jquery, like this:
var num = parseInt($.trim($(this).text()));
$(this).text(++num);
But then this disappears from my html <i class="zmdi zmdi-thumb-up" data-postid="{{ $post->id }}"> So I have to include it somehow with the count.
This is my full AJAX/Jquery for this button, basically if the button ges clicked, the count must go up (or down if disliked) and a class 'active' needs to be added
$('.like').on('click', function(event) {
event.preventDefault();
postId = event.target.dataset['postid'];
if($(this).hasClass('active')) {
$(this).removeClass("active");
$.ajax({
method: 'POST',
url: urlLike,
data: { postId: postId, _token: token },
});
console.log('unlike');
} else {
$(this).addClass("active");
$.ajax({
method: 'POST',
url: urlLike,
data: { postId: postId, _token: token },
});
console.log('like');
}
First time AJAX attempt.....
I am attempting to update a based on a selection made with a button.
I am currently just alerting the ID back, as that is all I can figure out what to do.
Is it possible to put the file my_page.php into the div with class "populated_info"?
Then when I press a different button, the page will function will run again, and populate the div with the new result. I have the my_page.php already built and running based on the ID, just can't get it to render in the correct place.
HTML:
<form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX:
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Your approach:
With regards to your button, I'd suggest separating the inline Javascript handler to keep your HTML and Javascript separate. I'll use a custom data attribute to store the ID here:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
Then jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
Your AJAX request:
You can shorten that whole function and use $.load() to get the data into your div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
Doesn't look like you need a callback function here, but if you do you can put it in after the data parameter. A useful application of a callback here might be for your error handler. See here how to implement one.
An an aside, if you're just getting data, you should probably be using the GET HTTP method instead of POST.
if you successfully get the response from the server just replace alert(resp) with $('.populated_info').html(resp);
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>