Multiple forms in while loop with ajax - javascript

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');

Related

Form Always submitting with Javascript Confirm

The form was working for a while but I moved some code around and can't revert (A lesson learned), now the code isn't working like it's supposed to. In a nutshell, User clicks delete button > Delete button sends specific Entry ID to function, Function gets form ID, "Confirms delete", then should send to my delete_entry.php code. Now, form is always submitting even when I hit "NO" and I added an alert to tell me which route it goes.
I've tried commenting out the form, and it still submits, so I don't think it's explicitly tied to the confirm function (Could be crazy though)
if ($entry['SubEntryID'] == "0") { ?>
<div id="post"><!-- This is the main post-->
<div id="main">
<div id="title">
<?php echo $entry['EntryID']; ?>
<?php echo $entry['Title']; ?>
</div><br />
<p><?php echo $entry['Body']; ?></p><br />
<div id="postinfo">
At: <?php echo $entry['CreateDate']; ?><br/>
Posted by - <?php echo $entry['UserName']; ?>
</div>
<!-- Start the form for the delete button -->
<form action="Delete_entry.php" method="post" id="Delete<?php echo $entry['EntryID'];?>">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type="hidden" readonly="true" name="UserID" value="<?php echo $entry['UserID']; ?>" />
<?php if ($userid == 1 || $userid == $entry['UserID']) { ?>
<input onclick="confirmdelete('Delete<?php echo $entry['EntryID'];?>')" type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post"/>
<?php } ?><br />
</form>
</div>
function confirmdelete(eid) {
var retval = confirm("Are you sure you want to delete?" + eid + "?");
if (retval == true) {
alert("You said Yes");
document.getElementById(eid).submit();
}
else
{
alert("You said No");
}
}
I want the delete button to call the function, the function to respond by submitting the form if it's true, and cancelling the form submission if false. The form page should only get called if confirm is true, and then submit()
Firstly the confirmdelete() is not returning any true/false back so there is no code that stops the form from submission. Secondly, a form will submit anyway even if the function returns false because you have 2 submits (the form and the onclick).
Move the function call to onsubmit() of the form. Remove the onclick because the input type image submits the form by default. Here is the code:
Form:
<form action="Delete_entry.php" method="post"
id="Delete<?php echo $entry['EntryID'];?>"
onsubmit="return confirmdelete(<?php echo $entry['EntryID'];?>)">
Then the button (onclick removed):
<input type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post" />
Finally the JavaScript (returns true/false):
function confirmdelete(eid) {
if (confirm("Are you sure you want to delete?" + eid + "?")) {
alert("You said Yes");
return true;
}
else
{
alert("You said No");
return false;
}
}

Ajax to insert multiple records from form inputs, add counter to hidden input

I've created a page that, based on an array from the database, creates multiple forms. Each form has an input with an 'add' button which dynamically adds new inputs (up to 10 inputs per form)
This works fine, but now I'm getting to where I want to submit andy input values added into the database. I have 2 main issues here:
The hidden input in my form <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>"> has a non unique ID, so no matter which form I submit from, it has the ticker value belonging to the first form only.
Once I have that value, and serialize with any filled inputs in that form, I call addticker.php to insert. I'm inserting the ticker id and the content from the form inputs, but I need to do this as a foreach I believe, because if 5 inputs were added and filled in, I need a record for each. All 5 would have the same ticker ID and the respective content from the input.
Any help is appreciated
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<script type="text/javascript">
$("#Items").submit(function(e) {
//variables?
//var tickerID coming from <input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
//var Items[]
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)

PHP update div after click submit

I am trying to do update "refresh" div after click Submit button and also every 5 seconds. I checked some questions, but I could not find what I was looking for.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
echo '<div id="refresh">';
while ($r = $q->fetch()):
echo 'Sender: ';
if($r['senderid'] == $a) {echo $query1['username'];}
elseif($r['senderid'] == $b) {echo $query2['username'];}
echo '</br>';
echo $r['message'];
echo '</br></br>';
endwhile;
echo '</div>';
?>
<form method="post">
<input type="hidden" name="a" value="<?php echo $a;?>">
<input type="hidden" name="b" value="<?php echo $b;?>">
<textarea name="message" rows="3" cols="30"></textarea><br><br>
<input id="submit" type="submit" value="Submit" />
</form>
<script>
$(document).ready( function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
$.post("submit.php", $("form").serialize()); // Post the data
$('textarea[name=message]').val('')
});
});
</script>
Please make some rudimentary investigation on $.post and setTimeout
Here is an example - there are a few questions you need to consider
var val = "";
function refreshDiv() {
var $text = $('textarea[name=message]');
val = $text.val() || val; // what to do if user clears the field?
if (val == "") return; // stop if nothing there
$.post("submit.php", $("form").serialize(),function(data) {
$("#refresh").html(data)); // show the data
setTimout(refreshDiv,5000); // call it again in 5 secs
// $text.val(''); // not sure about this...
});
}
$(function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
refreshDiv();
});
});

jQuery Ajax two identical functions working for one and not the other

I am making a comment system where a user can comment something to a post and then other users can reply to that comment. I have made a function to comment which works perfectly. I also wanted a similar function to work for that reply to comment part so I copied the same function and made some changes to the code like variable names etc. But its not working. When I write a reply and press enter it takes me to a new line rather than submitting. Please help me.
// COMMENT UPDATE (WORKING)
$(document).on('keydown', '.commentarea', function(event) {
var comtt = $(".commentarea").val();
if(comtt!=''){
if(event.keyCode == 13 && !event.shiftKey) {
var id = $(this).attr('id');
var status_id = id.replace("postcomment_", "");
createComment(status_id);
event.preventDefault();
}
}
});
function createComment(status_id){
var comment = $('#postcomment_'+status_id).val();
$.ajax({
url: "post-comment.php",type: "POST",
data: {comment : comment, statsid : status_id},
success: function (data) {
$("#showbox_"+status_id).append(data);
},
error: function () {
alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
},
complete: function(xhr) {
$('#postcomment_'+status_id).val('');
}
})
}
// REPLY TO COMMENT (SAME FUNCTION BUT NOT WORKING)
$(document).on('keydown', '.replyarea', function(event) {
var comtr = $(".replyarea").val();
if(comtr!=''){
if(event.keyCode == 13 && !event.shiftKey) {
var rid = $(this).attr('id');
var commentId = rid.replace("replycomment_", "");
createReply(commentId);
event.preventDefault();
}
}
});
function createReply(commentId){
var creply = $('#replycomment_'+status_id).val();
$.ajax({
url: "post-replies.php",type: "POST",
data: {creply : creply, cmtid : commentId},
success: function (data) {
$("#showreply_"+commentId).append(data);
},
error: function () {
alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
},
complete: function(xhr) {
$('#replycomment_'+commentId).val('');
}
})
}
PHP Part:
<?php while($get_stf = $get_stq->fetch()){ extract($get_stf); // fetch posts ?>
<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); // fetch comments?>
<!-- Reply to comments form -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width" id="cmt_form_id_<?php echo $cmt_id; ?>">
<input type="hidden" name="comment_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id; ?>" />
<textarea name="reply" placeholder="Give a reply..." class="reply-comment-field replyarea" id="replycomment_<?php echo $cmt_id; ?>"></textarea>
</form>
<!-- End Reply to comments form -->
<?php } ?>
<!-- Comment form -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width" id="cmt_form_id_<?php echo $cmt_id; ?>">
<input type="hidden" name="comment_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id; ?>" />
<textarea name="reply" placeholder="Give a reply..." class="reply-comment-field replyarea" id="replycomment_<?php echo $cmt_id; ?>"></textarea>
</form>
<!-- End Comment form -->
<?php } ?>
Both functions are same. But one being used for COMMENTS is working perfectly whereas the one used for REPLY TO COMMENTS is not working. It should submit the form and insert the data when I press enter in REPLY TO COMMENTS form after writing some text just like FACEBOOK. Please help.
your comment is broken the code:
Change this:
<!-- Reply to comments form -- >
for this:
<!-- Reply to comments form -->
and update.

Ajax to submit form generated dynamically by PHP do-while loop

I have an evaluation bar(progress bar generated by javascript), users can select a value and click to submit it. The issue is that I'm using PHP to generate the evaluation bars dynamically (using a do-while loop).
I can't figure out how to setup AJAX to recognized and submit any of the forms. Now it's submitting only the first one, even though I submit any of others.
My PHP code:
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form3")) {
$insertSQL = sprintf("INSERT INTO tblpersonalidad (idUser, idPost, intEvaluacion, dateFecha) VALUES (%s,%s,%s,%s)",
GetSQLValueString($_POST['idUser'], "int"),
GetSQLValueString($_POST['idPost'], "int"),
GetSQLValueString($_POST['intEvaluacion'], "int"),
GetSQLValueString($_POST['dateFecha'], "timestamp"),
);
mysql_select_db($database_conexionproject_poll, $conexionproject_poll);
$Result1 = mysql_query($insertSQL, $conexionproject_poll) or die(mysql_error());
$insertGoTo = "";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
do {
<form id="form3" name="form3">
<div class="progress-user">
<div class="progress-bar-user progress-bar-danger-user"></div>
<div class="progress-bar-user progress-bar-warning-user"></div>
<div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
</div>
<input class="mi-input" name="intEvaluacion" type="hidden" value="" />
<input type="hidden" name="MM_insert" value="form3" />
<input type="hidden" name="intActivo" value="1" />
<input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
<input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
</form>
} while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));
<script>
$('.progress-user').on('mousemove', function (e) {
var self = this;
var offset = $(self).offset();
var width = $(self).width();
var relX = Math.round(10 * (e.pageX - offset.left)/width) * 10;
setBarRating(self, relX);
$(self).siblings('.mi-input').val(relX);
});
$("#form3").submit(function(a) {
var url = "<?php echo $editFormAction; ?>"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $('#form3').serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
$('.progress-user').click(function() {
$("#form3").submit();
});
var setBarRating = function (self, percentage) {
$(self).find('.progress-bar-success-user span.rating').text(percentage + '%');
if (percentage <= 50) {
$(self).find('.progress-bar-danger-user').width(percentage + '%');
$(self).find('.progress-bar-warning-user').width(0);
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 50 && percentage <= 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width((percentage - 50) + '%');
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width('30%');
$(self).find('.progress-bar-success-user').width((percentage - 80) + '%');
}
};
</script>
I'll really appreciate any help. I haven't could realized what is the modification to the AJAX + PHP code. Many thanks for your time.
You’re generating several forms with id=”form3”. You’re also listening to $(“form3”).submit(). You’re submitting those forms by listening clicks to ‘.progress-user’:
$('.progress-user').click(function() { $("#form3").submit(); });
So, not matter wich .progress-user do you click on, the first #form3 will be the form submitted.
You should generate unique id’s to your forms and bars when creating them inside the loop. I.E;
$i = 0;
do {
<form id="<?php echo 'form' . $i ?>" name="<?php echo 'form' . $i ?>" class="progress-form">
<div class="progress-user" id="<?php 'progress-user' . $i; ?>" data-numer="<?php echo $i; ?>" >
<div class="progress-bar-user progress-bar-danger-user"></div>
<div class="progress-bar-user progress-bar-warning-user"></div>
<div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
</div>
<input class="mi-input" name="intEvaluacion" type="hidden" value="" />
<input type="hidden" name="MM_insert" value="form3" />
<input type="hidden" name="intActivo" value="1" />
<input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
<input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
</form>
$i++; //dont forget this :-)
} while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));
Now you have several forms with its own unique id and several progress bars with its unique id and a data-number attribute. Also, the dinamically generated form have that 'progress-form' class.
So now you can listen to clicks on progress bars like before, then caching the data-number of that element:
$('.progress-user').click(function() {
var formNumber = $(this).attr('data-number');
$("#form" + fromNumber).submit();
});
This way, you can be sure the form being submitted is the one whose progress-bar was clicked. Now you should also modify your submit listener:
$('.progress-form').submit(function(e){
var url = "<?php echo $editFormAction; ?>";
var data = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault();
});
So now you're serializing and sending only the form whose progress bar was clicked, and not the first '#form3' in the document.
Hope this helps.

Categories