Loading image being displayed only on the 1st result in while loop - javascript

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>

Related

delete record from database without refreshing

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; ?>">

To hide the div on ajax call if I get result

Here, I am getting result through ajax.
I want to hide div if I get the result from ajax.
The below div that I want to hide if get the result through the ajax.
Here is my code,
$("button").click(function(){
var dateselect=$("#dateselect").val();
var userselect = $("#employee").val();
$.ajax({
type: 'GET',
url: "<?php base_url() ?>manage_attendance/listing",
data:'dateselect='+dateselect+'&userselect='+userselect,
dataType: "json",
success: function(data) {
$('.clkin_time').html(data.result);
if(data.clkout_result != "0000-00-00 00:00:00") {
$('.clkout_time').html(data.clkout_result);
//document.getElementById('selecttime').style.display = "hidden";
}
else
{
$('.clkout_time').html("---");
}
}
});
});
My html part is,
<div id="selecttime">
<label class="col-lg-4 control-label">Select Time</label>
<div class="input-group date col-lg-2" id="datetimepicker5" style="display:inline-flex;">
<select id="time_date1" class="form_control" name="time_date1">
<?php
for($i=00;$i<=23;$i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
<select id="time_date2" class="form_control" name="time_date2">
<?php
for($i=00;$i<=59;$i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
<select id="time_date3" class="form_control" name="time_date3">
<?php
for($i=00;$i<=59;$i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
}
?>
</select>
</div>
</div>
Here, I want to hide this div if I get the result as above.
How can we do this?
Try like following. Use display attribute value none instead of hidden.
document.getElementById('selecttime').style.display = "none";
Or you can use jquery hide() function like following.
$("#selecttime").hide();
You have to use
//this will do display:none in style
$("#selecttime").hide();
and for show use
//this will do remove display:none from style
$("#selecttime").show();
Please check Document

inserting an ajax response into div

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>

Getting value from contenteditable div

Up to this point, I've been using a textarea as the main input for a form. I've changed it to use a contenteditable div because I wanted to allow some formatting.
Previously, when I had the textarea, the form submitted fine with Ajax and PHP. Now that I've changed it to use a contenteditable div, it doesn't work anymore and I can't tell why.
HTML:
<form>
<div name="post_field" class="new-post post-field" placeholder="Make a comment..." contenteditable="true"></div>
<input name="user_id" type="hidden" <?php echo 'value="' . $user_info[0] . '"' ?>>
<input name="display_name" type="hidden" <?php echo 'value="' . $user_info[2] . '"' ?>>
<ul class="btn-toggle format-post">
<button onclick="bold()"><i class="fa-icon-bold"></i></button>
<button onclick="italic()"><i class="fa-icon-italic"></i></button>
</ul>
<div class="post-buttons btn-toggle">
<button class="btn-new pull-right" type="submit">Submit</button>
</div>
</form>
JQuery Ajax:
$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'php/post.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
}
});
});
});
PHP (post.php): Just your typical checks and echo a message back. This is just a snippet of the code.
<?php
$user_id = $_POST["user_id"];
$display_name = $_POST["display_name"];
$post_content = $_POST["post_field"];
$array = array('message' => $post_content);
echo json_encode($array);
?>
For some reason, it's not sending back the post content anymore ever since I added the contenteditable div.
Please help!
The contents of the div are not serialized. You would have to add them on your own.
var data = $(this).serialize();
data += "post_field=" + encodeURIComponent($("[name=post_field]").html());

Multiple forms in while loop with ajax

I have a product page whos products are created dynamically from mysql along with "add to cart" buttons and quantity inputs on each item. These items are submitted via AJAX. I'm able to submit the correct product but the success message returned from ajax uses a hidden div which hides the add to cart button then displays text that your item in now in the cart. It hides ALL of the cart button and shows the hidden div containing the success message in every form. Any help to solve this is appreciated!
My PHP/HTML
//inside while loop
?>
<div class="form">
<form action="cart_action.php" method="post" name="form" id="form_<?php echo $item_no; ?>">
<input type="hidden" class="text" name="order_code" value="<?php echo $item_no; ?>" id="order_code<?php echo $item_no; ?>" />
<input type="hidden" class="text" name="minorder" value="<?php echo $min; ?>" id="min_<?php echo $item_no; ?>" />
<br><br><div style="float:left; padding:5px;"><b>Qty</b>: <input class="text" type="text" name="quantity" value="<?php echo $min; ?>" size="3" id="quan_<?php echo $item_no; ?>" ?></div>
<div id="status"></div>
<input type="image" src="images/add_to_cart.png" class="psubmit" alt="submit" name="submit" id="submit_<?php echo $item_no; ?>" />
</div><div class="added"><b><div style="color: rgb(85, 176, 90);"><br /><b>Added to Cart </b>(View Cart)</div></b></div>
</form>
<?php
} //end loop
JAVASCRIPT:
$(document).ready(function() {
$('form').submit(function(){
// Catching the DOM element which trigger the event
var $form = $(this);
var orderCode = $form.find('input[name=order_code]');
var quantity = $form.find('input[name=quantity]');
var minOrder = $form.find('input[name=minorder]');
if (quantity.val() == '') {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Please Enter A Quantity!</font>');
return false;
} else quantity.removeClass('hightlight');
if (quantity.val() % minOrder.val()) {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Invalid Multiple!</font>');
return false;
} else quantity.removeClass('hightlight');
//organize the data properly
var data = 'order_code=' + orderCode.val() + '&quantity=' + quantity.val();
//disabled all the text fields
//$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "cart_action.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
}
});
//cancel the submit button default behaviours
return false;
e.preventDefault();
});
});
In your success handler, change the selectors to start from $form:
$form.fadeOut('slow');
$form.children('.added').fadeIn('slow');

Categories