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

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.

Related

Print window of submitted form without redirection on Laravel

I have one issue, how open print window of submitted form without redirection. Now, when I submit form, redirects to submitted form results as well.
Controller. If is neccessary I can create blade file for submited form results to sove this issue.
public function printBarcode(BarcodeRequest $request)
{
$bar = new DNS1D();
$user = User::find(Auth::id());
$barcodes = $request->input('prints');
for ($i = 0; $i <= count($barcodes) - 1; $i++) {
echo '<body onload="window.print();">';
echo '<div style="text-align: center; height: 100%">';
echo '<img src="data:image/png;base64,' . $bar->getBarcodePNG($barcodes[$i], 'C128', $user->barcode_width, $user->barcode_height) . '" alt="barcode" style="width: 50%;"/>';
echo '<br>';
echo '<br>';
echo '<p style="text-align: center; margin-top: 5px;">' . $barcodes[$i] . '</p>';
echo '</div>';
echo '</body>';
}
}
Form
Locations:
#for($i=0; $i<=count($warehouses)-1; $i++)
<input type="checkbox" name="all" id="all" onclick="toggle(this);">Select/remove all<br>
<form method="get" action="{{route('print.barcode')}}">
#csrf
<br>
#for($j=0; $j<=count($locations[$i])-1; $j++)
<input type="checkbox" name="prints[]" value="{{ $locations[$i][$j]['node']['name'] }}"> {{ $locations[$i][$j]['node']['name'] }}
<br>
<br>
#endfor
<button type="submit" valu="submit" class="btn btn-danger btn-sm" onclick="printBarcode({{route('print.barcode')}});">Print Selected</button>
</form>
<input type="checkbox" name="all" id="all" onclick="toggle(this);">Select/remove all<br>
#endfor
Javascript part which should handle redirection
function printBarcode(url){
window.location.replace('localhost/home');
$('body').append('<iframe src="url" id="printIFrame" name="printIFrame"></iframe>');
$('#printIFrame').bind('load',
function() {
window.frames['printIFrame'].focus();
window.frames['printIFrame'].print();
window.location.href = 'localhost/home';
}
);
}
Send query via ajax
function printBarcode(url) {
var form = $("#myFormId");
var url = form.attr('action'); //get submit url [replace url here if desired]
$.ajax({
type: "POST",
dataType: "html",
url: url,
data: form.serialize(), //serializes form input
success: function(data){
//Past to DIV
$("#printArea").html(data);
$("#printArea").print();
}
});
};
or use
window.open(url + '?' + queryString );
and open page in new window
...

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 calculating price if many elements on same page using same IDs?

I have 12 of these forms on a page on each product. It allows someone to enter a quantity and have it calculate the price, but doesn't yet work. The new price should replace what's in the orderprice class div.
<form action="" method="post">
<input type="number" id="amount-<?php echo $productId; ?>" class="orderamount" name="amount" value="1" min="1" max="2000" maxlength="4" />
<input type="hidden" name="product" value="<?php echo $productId; ?>" readonly="readonly" disabled="disabled" />
<div id="price-<?php echo $productId; ?>" class="orderprice">
<?php
echo html_entity_decode($currencyAlignCode) . round($productPrice * $currencyMultiplier, 2);
?>
</div>
<input type="submit" class="addcart" value="" name="order" />
</form>
I want to take the value of amount-<?php echo $productId; ?>, and automatically calculate the price by multiplying that value by $productPrice and again by $currencyMultiplier, and then add html_entity_decode($currencyAlignCode) in front of it.
I know how to do that if there were only 1 form on the page and I didn't need to account for <?php echo $productId; ?>. This is how I would do it for an individual form, but how can I do it for several? And each price would only grab the quantity from the associated input box?
$(document).ready(function() {
$("#amount").bind('click keyup', function(event) {
var amount = $("#amount").val();
var productPrice = <?php echo $productPrice; ?>;
var currencyMultiplier = <?php echo $currencyMultiplier; ?>;
var currencyCode = <?php echo html_entity_decode($currencyAlignCode); ?>;
var totalPrice = amount * productPrice * currencyMultiplier;
$("#price").html('currencyCode' + totalPrice);
});
});
This code will only do it for 1 product. I want the input from each to show in the respective price box.
Sorry if it's not clear, it was kind of hard to explain.
Maybe something like this? Use multiple selectors or grab the selectors that start with something.
<input type="number" id="amount-<?php echo $productId; ?>" productPrice="<?php echo $productPrice; ?>" ...
$("[id^=amount]").each(function(index){
$(this).bind("click key up", function(){
var amount = $(this).val();
var productPrice = $(this).attr('productPrice');
...
});
});
https://api.jquery.com/each/
http://api.jquery.com/attribute-starts-with-selector/
I ended up doing some extensive Googling and coming up with the solution.
I use attr to grab the id based on the changed class.
$(document).ready(function() {
$(".orderamount").bind('click keyup', function(event) {
var productId = $(this).attr('id');
var setId = productId.substring(7);
var amount = $('#amount-' + setId).val();
var productPrice = <?php echo $productPrice; ?>;
var currencyMultiplier = <?php echo $currencyMultiplier; ?>;
var currencyCode = <?php echo html_entity_decode($currencyAlignCode); ?>;
var totalPrice = round(amount * productPrice * currencyMultiplier, 2);
$('#price-' + setId).html('currencyCode' + totalPrice);
});
});

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