here i want to passing the product_id value into addcart.php file through the jQuery Function.here 'Add Cart' button generated dynamically by php while loop. every button set as a invidual product id, there is fine until this..
what's my problem is All Button pass the same value to addcart.php file when i clicked each one...i want to pass the value of individual one(button)..
Please Give me a Solution... addcart.php just contain code like
"echo $_POST['pid']; only"
<?php
include('includes/db-config.php');
$shop_id=$_GET['sid'];
$get_product_q = mysql_query("select product from shops where sid = $shop_id");
$get_product_f = mysql_fetch_array($get_product_q);
$product_id = explode(',', $get_product_f['product']);
$count_product_id = count($product_id);
for($i=0;$i<$count_product_id;$i++){
$get_product_q = mysql_query("select * from products where pid = $i");
$get_product_f = mysql_fetch_array($get_product_q);
$product_id = $get_product_f['pid'];
?>
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : '<?php echo $product_id?>'},
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
<?php
$product_name = $get_product_f['name'];
$product_description = $get_product_f['description'];
$product_price = $get_product_f['price'];
echo $product_name;
echo '<br>';
echo $product_description;
echo '<br>';
echo $product_price;
echo '<br>';
echo '<input class="but" type="button" value="Add Cart" />';
echo '<br><br>';
}
?>
<div id="div1"></div>
You are repeating the entire Javascript for every product. Move the Javascript out of the loop and set the product ID as a data-productid attribute on the button:
echo '<input class="but" type="button" value="Add Cart" data-productid="' . htmlspecialchars($product_id) . '" />';
Then when you make the ajax call (on click), read the product ID and set it as the POST data:
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : $(this).data('productid') },
success:function(result){
$("#div1").html(result);
}
});
Try this :
replace : echo '<input class="but" type="button" value="Add Cart" />'; by this : echo '<input class="but" type="button" rel="'.htmlspecialchars($product_id).'" value="Add Cart" />';
and your script :
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : $(this).attr('rel'),
success:function(result){
$("#div1").html(result);
}});
});
});
</script>
The problem is that you're binding it to a click on all elements with the class ".but", if you on the other hand gave the button an id like
echo '<input data-pid="'. sha1($product_id) . '" class="but" type="button" value="Add Cart" />';
and then in your jquery function would do the following (outside the loop):
<script>
$(document).ready(function(){
$('.but').click(function(){
$.ajax({
type: 'POST',
url:"addcart.php",
data : $(this).data(),
success:function(result){
$("#div1").html(result);
}
});
});
});
</script>
Then you would get around the problem, as it then listens for the click event on each element, but the data is varying on each element.
I hope this helps.
in you loop ,.but was bind an function each time,so the last bind one works .try to give the .but elements an unique id such as "id=$product_id";
and you can bind the function once (outside the loop).this simply like:
$(document).ready(function(){
$('.but').click(function(){
var data = $(this).attr("id");
$.ajax({
type: 'POST',
url:"addcart.php",
data : { pid : data},
success:function(result){
$("#div1").html(result);
}});
});
});
be lucky.
Related
multi checkbox not working in ajax calling it will reset,my checkbox like
<form action="#">
<?php
foreach($rimdiameter as $rows) {
if($rows->rimdiameter!='') {
?>
<p>
<label>
<input type="checkbox" name="diametersearchs[]" value="<?php echo $rows->rimdiameter; ?>" class="ads_Checkbox_diameter" id="diametersearch" multiple>
<span><?php echo $rows->rimdiameter; ?></span>
</label>
</p>
<?php } }?>
</form>
click a check box it will run a query and view the result and click next checkbox first will be unchecked ,my ajax code
$('.ads_Checkbox_diameter').change(function(){
$('input[type="checkbox"]').not(this).prop("checked", false);
var final = '';
$('.ads_Checkbox_diameter:checked').each(function(){
var final = $(this).val();
var type = 'diameter';
$("#loadMore").hide();
var siteurl = '<?php echo $root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'; ?>';
$(".loadingimageproduct").show();
var serachfilterproductbyprice = 'serachfilterproductbyprice';
var centre_bore='<?php echo $centre_bore;?>';
var bolt_pattern='<?php echo $bolt_pattern;?>';
var widtz=sessionStorage.getItem('widthz');
sessionStorage.setItem('diameter',final);
$.ajax({
url:"{{url('/')}}/serachfilterproductbyprice",
method: 'POST',
data: {serachfilterproductbyprice:serachfilterproductbyprice ,width:widtz, siteurl:siteurl, type:type, final:final ,bore:centre_bore ,pattern:bolt_pattern , "_token": "{{ csrf_token() }}"},
success: function(data) {
$('#msgproductfilter').html(data);
$(".loadingimageproduct").hide();
$(".front_product_wheel_show").hide();
$.ajax({
// save another data
});
}
});
});
});
why the checkbox unchecked if another one is clicking time ,how to solve?i wand multi checking property . and it will sore in array
The very first thing you do in your change handler is explicitly un-check all other checkboxes:
$('input[type="checkbox"]').not(this).prop("checked", false);
If you don't want to do that, simply remove that line of code.
Input fields and delete buttons are produced by a php foreach loop!
To grab the value of an input and send it to php i use code below:
Html:
<input type="hidden" name="file_id" id="<?php echo $file_id; ?>" value="<?php echo $file_id; ?>" />
<button class="btn btn-sm btn-danger delete" type="submit" name="delete_file">Delete</button>
jquery:
$(document).on('click' , '.delete' , function() {
var file_id = $('#<?php echo $file_id; ?>').val();
$.ajax({
url: "admin.php",
method: "POST",
data: {
file_id : file_id
},
success: function(data) {
$('.result').html(data);
}
});
});
php:
if(isset($_POST["file_id"])) {
echo $_POST["file_id"];
}
Problem: When i submit (delete),it grabs always the value from the first input field.
How can i make this work, so when i choose the second delete, that it grabs the value from the second input field?
Instead of
var file_id = $('#<?php echo $file_id; ?>').val();
use
var file_id = $(this).prev().val(); // according to provided markup
This will select previous element to the <button> (which is the hidden <input>), and takes its value.
I have a button into a while loop on a PHP file.
The button is associated to a PHP value that is changing with mysqli_fetch_array.
I load only 3 values in my mysqli_fetch_array.
My ajax function has data in it, my problem is that it is only accepting first row's value, and not other rows value. In fact, the function is ok just at the first row of the mysqli_fetch_array, and it seems that my code is not working on the other rows, like if PHP loop stopped at first row.
Here is my javscript code (it is declared on the same page of my loop, after the while):
<script type="text/javascript">
$(document).ready(function() {
$("#up").click(function() {
var varno_commentaire = $("#no_commentaire").val();
$.ajax({
url: "upvoteCommentaire.php",
type: "POST",
data: {
no_commentaire: varno_commentaire
},
async: false,
success: function(result) {
alert(result);
}
});
});
});
</script>
And here is my PHP loop :
<?php
while($comm = mysqli_fetch_array($res2))
{
echo
'<label class="text-muted">'.$comm['desc_commentaire'].'</label>'.
'<p>'.
''.'#'.$comm['login'].''.
'<p>'.
'<label>'.$comm['vote_commentaire'].' points'.'</label>'.
'<p>'.
'<input type="text" value="'.$comm['no_commentaire'].'" id="no_commentaire"/>'.
'<button class="btn btn-default" name="up" id="up">+</button>'.
' '.
'<button class="btn btn-default" name="down" id="bold" onclick="downvote()">-</button>'.
'<p>'.
'<hr/>';
}
?>
I hope it will be easy to understand. Any help will be appreciated, I've been stuck on it for a moment. Thanks a lot.
First of all, you can't declare more than once an id. ID should be unique. You can pass the ID into a HTML attribute.
Your loop:
<?php
while($comm = mysqli_fetch_array($res2))
{
echo
'<label class="text-muted">'.$comm['desc_commentaire'].'</label>'.
'<p>'.
''.'#'.$comm['login'].''.
'<p>'.
'<label>'.$comm['vote_commentaire'].' points'.'</label>'.
'<p>'.
'<input type="text" value="'.$comm['no_commentaire'].'"/>'.
'<button class="btn btn-default btn-up" data-id="'.$comm['no_commentaire'].'">+</button>'.
' '.
'<button class="btn btn-default btn-down" data-id="'.$comm['no_commentaire'].'">-</button>'.
'<p>'.
'<hr/>';
}
?>
Your script:
<script type="text/javascript">
$(document).ready(function() {
$("button.btn-up").click(function() {
var varno_commentaire = $(this).data('id');
$.ajax({
url: "upvoteCommentaire.php",
type: "POST",
data: {
no_commentaire: varno_commentaire
},
async: false,
success: function(result) {
alert(result);
}
});
});
});
</script>
ID are meant to be used only once on the entire page. In your case every element in while loop of PHP has same ID. So when you take the value of element by $("#no_commentaire").val(), it takes the first element's value ignoring the rest of the elements on the page.
Solution to your problem is to have a class instead of ID of the elements and access the same by parent child releationship in the jQuery. So you only get the value of selected/clicked section.
Your PHP code would look something like this,
<?php
while($comm = mysqli_fetch_array($res2))
{
echo
'<div class="parent-class">'.
'<label class="text-muted">'.$comm['desc_commentaire'].'</label>'.
'<p>'.
''.'#'.$comm['login'].''.
'<p>'.
'<label>'.$comm['vote_commentaire'].' points'.'</label>'.
'<p>'.
'<input type="text" value="'.$comm['no_commentaire'].'" class="no_commentaire"/>'.
'<button class="btn btn-default up" name="up">+</button>'.
' '.
'<button class="btn btn-default" name="down" id="bold" onclick="downvote()">-</button>'.
'<p>'.
'</div>'.
'<hr/>';
}
?>
and jQuery code would look something like this,
<script type="text/javascript">
$(document).ready(function() {
$(".up").click(function() {
var varno_commentaire = $(this).parent().child(".no_commentaire").val();
$.ajax({
url: "upvoteCommentaire.php",
type: "POST",
data: {
no_commentaire: varno_commentaire
},
async: false,
success: function(result) {
alert(result);
}
});
});
});
</script>
I am trying to develop an add to cart function via ajax, the problem is that no matter which product I add to cart, it adds the last item on the list and then increments the same product upon clicking on any other product. Here is my code:-
<?php
$i = 1;
while($row = mysqli_fetch_array($run_products)){
$op_id = $row['option_id'];
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row['option_desc'] . "</td>";
echo "<td>
<form action='' method='post' class='p_form'>
<input type='text' name='product_id' value='$op_id' pid='$op_id'>
<input type='text' name='quantity' value='1' pid='$op_id'>
<input class='btn btn-primary add' type='submit' name='add_to_cart' value='Add to Cart' id='product' pid='$op_id'>
</form>
</td>";
echo "</tr>";
$i++;
}
?>
Here is jquery:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.p_form',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
//data: {id:id},
data:$('.p_form').serialize(),
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Here is action.php, the $product_id always returns as 4 (for example) if the last id in the last is 4
if (!empty($_POST)){
$product_id = $_POST['product_id'];
echo $product_id;
}
Need to do it like below:-
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {//instead of form click add event on form button click
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data:element.parent('.p_form').serialize(), //serialize clicked button parent form
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Trigger click event on button click not on the form click:
This will work for you for each product.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data: {id:id}, //send id of product you wish to add
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
And on server side:
if (!empty($_POST)){
$product_id = $_POST['id'];//get only that id posted in ajax call
echo $product_id;
}
I have list with several inputs
<input type="hidden" id="elevens_id_ea" value="<?php echo $_GET['elev_id']; ?>" />
<input type="hidden" id="arskursen_ea" value="<?php echo $arskursen; ?>" />
<?php
if ($extraanpassning_hamta['atgard'] == true){
?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-red btn-sm" value="Ja">
<?php } else { ?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-green btn-sm" value="Nej">
<?php } ?>
The main problem is how to "catch" the value in the two latest inputs with:
id="knapp[<?php echo $amnets_id['amne_id']; ?>]"
If knapp[4] -> how do I get the 4?
The code above is a part of a button that changes value when the user presses it (without refreshing the page).
The JS
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var extraanpassningVal = $(this).attr("value");
var amne_id_ea = $(this).attr("id");
var elevens_id_ea = $("#elevens_id_ea").val(); //värdet av elev_id
var arskursen_ea = $("#arskursen_ea").val(); //värdet av elev_id
$.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
});
});
</script>
EDIT:
The main problem is how to get the key from a input with an id like knapp[4].
How do get the key within knapp[]?
Update (thanks to user:SpYk3HH)
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajax) this.ajax.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajax = $.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
})
});
</script>
I think I get it? You want the key when calling the button in JS? So like say: key = this.id.replace(/knapp|\[|\]/g, '')
Update, I didn't see the brackets before
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajx) this.ajx.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajx = $.ajax({/* options */});
})
Does that help?
FYI, $(this).attr("id") and this.id are the same thing
$('[name=test]').each(function(i) { $('#bob').text(this.id.replace(/knapp|\[|\]/g, '')) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="knapp4" name="test" value='my id is "knapp[4]"' />
<hr />
key: <span id="bob"></span>
Try this.
var amne_id_ea = "knapp[4]",
value = amne_id_ea.substring(amne_id_ea.lastIndexOf("[")+1,amne_id_ea.lastIndexOf("]"));
alert(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Hope you are expecting this.