I'm sorry if this question has already been asked but all the solutions I've tried haven't worked for me. What I want it to do is trigger some jQuery code when the form element is submitted.
Here's my code.
JS:
$(document).ready(function() {
$('form').bind('submit', function() {
alert('hi');
var word10 = <?php echo $word10; ?>;
var word20 = <?php echo $word20; ?>;
var word1Txt = <?php echo $word1Txt; ?>;
var word2Txt = <?php echo $word2Txt; ?>;
$('div.word1').prepend("<h3 class='header'>hi" + word1Txt + "</h3>");
$('div.word2').prepend("<h3 class='header'>hi" + word2Txt + "</h3>");
});
});
HTML:
<form class="form-inline" method="post">
<input class="form-control" type="text" placeholder="First Word" name="word1" autofocus>
<input class="form-control" type="text" placeholder="Second Word" name="word2" autofocus>
<input class="btn btn-primary form-submit" type="submit" value="Compare">
</form>
Use .on() or .submit() instead and if your vars are supposed to be strings, quote them:
$(document).ready(function() {
$('form').on('submit', function() {
alert('hi');
var word10 = '<?php echo $word10; ?>';
var word20 = '<?php echo $word20; ?>';
var word1Txt = '<?php echo $word1Txt; ?>';
var word2Txt = '<?php echo $word2Txt; ?>';
$('div.word1').prepend("<h3 class='header'>hi" + word1Txt + "</h3>");
$('div.word2').prepend("<h3 class='header'>hi" + word2Txt + "</h3>");
});
});
Related
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();
});
});
This is my Form
<form method="post" id="BargainForm">
<input type="hidden" name="pro_id" class="pro_id" id="pro_id" value="<?php echo $pro_id; ?>">
<input type="hidden" name="customer_id" class="customer_id" id="customer_id" value="<?php echo $customer_id; ?>">
<input type="text" name="bargain_qty" class="bargain_qty" id="bargain_qty" placeholder="Qty" required/></br></br>
<?php if($productType = 'Configurable'): ?>
<?php foreach($attributes as $attribute): ?>
<input type="text" name="<?php echo strtolower($attribute['store_label']); ?>"
class="<?php echo strtolower($attribute['store_label']); ?>"
id="<?php echo strtolower($attribute['store_label']); ?>"
placeholder="<?php echo $attribute['store_label'] ?>"></br></br>
<?php endforeach; ?>
<?php else: ?>
<?php endif; ?>
<input type="text" name="bargain_price" class="bargain_price" id="bargain_price" placeholder="Total Price" required/></br></br>
<input type="submit" name="bargain_btn" class="bargain_btn">
</form>
Here is my javascript code
<script type="text/javascript">
$(function () {
$('.bargain_btn').click(function(e) {
var qty = $( "#bargain_qty" ).val();
var price = $( "#bargain_price" ).val();
var pro_id = $( "#pro_id" ).val();
var customer_id = $( "#customer_id" ).val();
var att_lable = $( "#<?php echo strtolower($attribute['store_label']); ?>" ).val();
alert(att_lable);
e.preventDefault();
$.ajax({
url: "<?php echo Mage::getUrl('bargain/Ajax/index'); ?>",
type: "POST",
data: {qty,price,pro_id,customer_id},
success: function(data) {
if(data.success) {
}
}
});
});
});
In form i am using foreach. If i have 2 data so it will display 2 input tags, i just don't know how to save values of that 2 input and pass it to data: {qty,price,pro_id,customer_id},
Thank you in advance!
Provide a common class to all textbox that are generated using loop like:
foreach(...)
{
echo '<input class="myTxt" value="" id="" />';
}
Jquery:
var arr = [];
$('.myTxt').each(function(){
arr.push($(this).val());
});
pass this array i.e. arr to ajax call in data{} section using serialize or on an index.
Replace
data: {qty,price,pro_id,customer_id},
By
data: "qty="+qty+"&price="+price+"&pro_id="+pro_id+"&customer_id="+customer_id+"&att_lable="+att_lable,
Do not use:
data: { qty, price, pro_id, customer_id },
Instead use:
data: $("#BargainForm").serialize(),
It will work only if your $attribute['store_label'] name is unique.
Below is my HTML code. I can only get value returned by ajax request in that id="sss" field.
My Problems are listed below with images:-
<form id="dynamic2" action="<?= site_url('product/save') ?>" method="post">
<table class="table">
<tbody id="itemlist2" class="detailss">
<tr>
<td>
<select id="select-product" class="form-control" data-cell="B1" name="product_name[]">
<option value="">
</option>
<?php
foreach ($product as $key ):
?>
<option value="<?php echo $key['id'] ?>">
<?php echo $key['product_name'] ?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<input type="text" id="sss" data-cell="C1" name="price[]" class="form-control" value="">
</td>
<td>
<input type="text" data-cell="D1" name="quantity[]" class="form-control">
</td>
<td>
<input type="text" data-cell="E1" name="discount[]" class="form-control">
</td>
<td>
<input type="text" data-cell="F1" name="total[]"
disabled="true" data-formula="(D1*C1)-(D1*C1*E1/100)"
class="form-control">
</td>
</tr>
</tbody>
<input type="submit" value="Submit" class="btn btn-primary">
</table>
</form>
I am not getting value returned by ajax request in dynamically created input fields.
Here is my dynamically created input field jS code.
<script type="text/javascript">
$(function() {
$form = $('#dynamic2').calx();
$('.addrowss').click(function() {
$itemlist = $('#itemlist2');
$counter = 5;
var i = ++$counter;
var tr = '<tr>' +
'<td><select id="select-product" class="form-control" data-cell="B' + i + '" name="product_name[]"><option value=""></option><?php
foreach ($product as $key ):
?><option value="<?php echo $key['product_name'] ?>"><?php echo $key['product_name'] ?></option><?php endforeach; ?></select></td>'+
'<td><input id="sss" type="text" data-cell="C' + i + '" name="price[]" class="form-control" value=""></td>' +
'<td><input type="text" data-cell="D' + i + '" name="quantity[]" class="form-control"></td>' +
'<td><input type="text" data-cell="E' + i + '" name="discount[]" class="form-control"></td>' +
'<td><input type="text" class="form-control" data-cell="F' + i + '" name="total[]" data-formula="(D' + i + '*C' + i + ')-(D' + i + '*C' + i + '*E' + i + '/100)"></td>' +
'<td>Remove</td>' +
'</tr>';
$('.detailss').append(tr);
$form.calx('update');
$form.calx('getCell', 'G1').setFormula('SUM(F1:F' + i + ')');
});
$('body').delegate('.remove', 'click', function() {
var tr = $(this).parent().parent();
var c = confirm("Do you want to remove this ?");
if (c) {
tr.remove();
}
});
});
</script>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#select-product").change(function() {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {
"id": id
},
cache: false,
success: function(data) {
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
</script>
Product.php Controller
public function view_data()
{
if(isset($_GET['id'])){
$this->load->model('Product_model');
$id = $_GET['id'];
$param = $this->Product_model->get_ajax_value($id);
foreach($param as $a)
echo $a.",";
exit;
}
}
I am not exactly sure why it isn't returning all the correct data. But here might be a step to help you debug you problem.
Add a console.log(data); To see what is being returned from the ajax call. Use the console of your browser to see this.
Change your code to:
<script type="text/javascript">
$(document).ready(function () {
$("#select-product").change(function () {
var id = $(this).val();
// alert(id);
$.ajax({
type: "GET",
url: "<?php echo site_url('/product/view_data'); ?>",
data: {"id":id},
cache: false,
success: function(data){
console.log(data); //this will show what is returned.
var tmp = data.split(",");
$('#sss').val(tmp[6]);
}
});
});
});
I understand this isn't the complete answer to your code. But it might put you on the right track to seeing what the server is returning to your client side code.
So I've been struggling with this for a while, i have a div and a form in a for each loop and on submitting one of the forms in the loop, the content of its div is updated in the database and refreshed ("div only"). This is done using JavaScript and Ajax. My update query works fine, JavaScript handles the form and Ajax refreshes only the div in the page. My problem is, upon refreshing all the contents in the loop are put into one div but instead i want one content to one div as many times the loop is run, to better understand my problem please refer to the image below:
Before:
After first like button is clicked:
This is the result i expect to see:
info.php
<html>
<head>
.......
<script type="text/javascript">
$(document).ready(function(){
$('.ajaxform').submit(function(e) {
e.preventDefault(); // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'html',
url: "test.php", // the file to call
cache: false,
success: function(response) { // on success..
$('.ld').html(response);
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...........
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post">';
echo '<span style="font-weight:bold;">'.$username.'  said....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';//form to submit
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';//div to refresh
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
?>
</body>
</html>
test.php
<?php
$mysqli = new mysqli("localhost", "root", "", "Anonmy");
if( isset( $_POST['lkcv'] ) && is_array( $_POST['lkcv'] ) )
{
$idArray = array();
foreach( $_POST['lkcv'] as $value )
{
$idArray[] = intval( $value );
}
$mysqli->query( "UPDATE comment SET like1 = like1 + 1 WHERE id IN (".implode(
',', $idArray ).")" );
}
?>
<?php
$host = 'localhost';
$dbname = 'dbname';
$username = "root";
$password = "";
$conn = new PDO('mysql:host=localhost;dbname=Anonmy', $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_id = $_POST['pid'];
$like = $_POST['stk'];
$target_no = 3;
echo '<div class="wrap">';
// retrive comments with post id
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="">'.$likes.'</div>';
}
?>
</body>
</html>
How can i modify my code to achieve the result in image 3.
test.php[updated]
$host = 'localhost';
$dbname = 'dbname';
$username = "root";
$password = "";
$conn = new PDO('mysql:host=localhost;dbname=Anonmy', $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_id = $_POST['pid'];
$like = $_POST['stk'];
$target_no = 3;
echo '<div class="wrap">';
// retrive comments with post id
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
//updated
$result = array();
foreach ($stmt as $row) {
$result[] = array('id' => $row['id'], 'likes' => $row['like1'], 'dislikes' =>
$row['dislike']);
}
echo json_encode($result);
?>
info.php[updated]
<html>
<head>
.......
<script type="text/javascript">
$(document).ready(function(){
$('.ajaxform').submit(function(e) {
e.preventDefault(); // catch the form's submit event
//updated
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'json',
url: "test.php", // the file to call
cache: false, // Not needed for POST
success: function(response) { // on success..
$.each(response, function(i, el) {
var comment_post = $("#comment-post-" + el.id);
comment_post.find(".ld").text(el.likes);
comment_post.find(".ldks").text(el.dislikes);
});
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...........
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post" id="comment-post-' . $id .'">';//updated
echo '<span style="font-weight:bold;">'.$username.'  said....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';//form to submit
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';//div to refresh
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
?>
</body>
</html>
test.php[ajax response]
<html>
<head>
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2
/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"> </script>
<script language="JavaScript">
$(document).ready(function(){
$(".users").hide();
$(".SendCopy").click(function(){
$(this).next(".users").slideToggle("slow");
});
});
</script>
</head>
<body>
[{"id":"2","likes":"196","dislikes":"0"},
{"id":"5","likes":"80","dislikes":"0"},
{"id":"6","likes":"45","dislikes":"0"},
{"id":"7","likes":"31","dislikes":"0"}]
</body>
</html>
Change the HTML so that the post ID is included in the the ID of the DIV containing the like/dislike data.
echo '<div class="comment-post" id="comment-post-' . $id .'">';
Change test.php so it returns JSON instead of HTML:
$result = array();
foreach ($stmt as $row) {
$result[] = array('id' => $row['id'], 'likes' => $row['like1'], 'dislikes' => $row['dislike']);
}
echo json_encode($result);
Remove all other code in test.php that produces output, like this line:
echo '<div class="wrap">';
The only output should be the JSON.
Then in the AJAX call, extract the JSON data and update each corresponding element with its likes and dislikes.
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'json',
url: "test.php", // the file to call
cache: false, // Not needed for POST
success: function(response) { // on success..
$.each(response, function(i, el) {
var comment_post = $("#comment-post-" + el.id);
comment_post.find(".ld").text(el.likes);
comment_post.find(".ldks").text(el.dislikes);
});
}
});
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);
});
});