Add to cart adding first item - javascript

I have a simple cart where I can add items on the fly and it update via AJAX. Issue being I am pulling my items from the database but when I click 'add to cart' it populates the cart but with the first item only so no matter which one I click it adds item 1.
I am looping through a result and getting the row:
while ($row = mysqli_fetch_array($r)) {
echo '
<div class="items" id="item">
'.$row["prod_name"]. '';
echo "
<div class='product_display'>
<p><img src='../admin/uploads/".$row['file_upload']."'></p>";
echo"
<input type='button' value='Add To CART' onclick='cart(\"item\");' ";
echo'
<p>Price - '.$row["prod_price"]. '</p>
<input type="hidden" id="item_name" value="'.$row["prod_name"]. '">
<input type="hidden" id="item_price" value="'.$row["prod_price"]. '">';?>
<?php echo'
</div>
</div>
';
}
The echo's really need cleaning up but they confuse me so much!
I am using a little bit of JS to do the AJAX:
$(document).ready(function(){
$.ajax({
type:'post',
url:'store_items.php',
data:{
total_cart_items:"totalitems"
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
});
And my JS does the rest:
function cart(id)
{
var ele=document.getElementById(id);
var img_src=ele.getElementsByTagName("img")[0].src;
var name=document.getElementById(id+"_name").value;
var price=document.getElementById(id+"_price").value;
$.ajax({
type:'post',
url:'store_items.php',
data:{
item_src:img_src,
item_name:name,
item_price:price
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
}
function show_cart()
{
$.ajax({
type:'post',
url:'store_items.php',
data:{
showcart:"cart"
},
success:function(response) {
document.getElementById("mycart").innerHTML=response;
$("#mycart").slideToggle();
}
});
}
I thought I would share it all so you can see - but the main issue is the fact it just adds item 1 form the list no matter which one you click on - I am getting no errors and the console is giving me nothing?

It is because you are using the same id for all your items. IDs should only be used once per page, and in cases where you are using it multiple times, document.getElementById(id) will only get the first one that it finds which is why you keep on getting the first item in the list only.
You can give each item different ids and pass that id to the cart function. Or to make things simplier, use event delegation (since you're already using jQuery) to listen for clicks on the Add To Cart button so that you don't have to use the onclick attribute anymore. You can do it like this:
$(document).on('click', 'ADDTOCARTBUTTONSELECTOR', function() {
var element = $(this).closest('.items');
var image = element.find('img')[0].src;
var name = element.find('NAMESELECTOR').val();
var price=document.find('PRICESELECTOR').val();
// the ajax part follows here
});
The ADDTOCARTBUTTONSELECTOR, NAMESELECTOR, and PRICESELECTOR are just placeholders to the actual selectors to those elements, and just replace them appropriately to select the proper elements.

Related

Display value from checkbox in console.log

Well this is probably an easy question but I've been figure this one out. I would like to display the value of a checkbox in the console.log so I can use it to fire a AJAX call. But the values of every checkbox is the same (the first one).
I have spent some time on google and I for what I read there, I should put the checkbox in an array. But I can't seem to get it to work. Here is my code at the moment.
<!-- Custom taxonomy checkboxes -->
<?php
$taxonomy = 'locatie';
$queried_term = get_query_var($taxonomy);
$terms = get_terms($taxonomy, 'slug='.$queried_term);
if ($terms) {
foreach($terms as $term) {
$name = $term->name;
echo "<div class='col-xs-12 col-sm-12 col-md-2 col-lg-2'>
<form id='location'>
<input class='checkIt' type='checkbox' value='".$name."' name='location' id='".$name."_id'> ".$name."
</form>
</div>";
}
}
?>
<!-- /Custom taxonomy checkboxes -->
$('.checkIt').change(function(e) {
var value = $(this).val();
$.post('../wp-content/themes/mysite/includes/search-team-wp.php',{value:value}, function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value);
});
});
});
Everything works, even the AJAX call, except the console.log output so I can't sent different values trough the AJAX call. Any help would be really nice!
use
var value = $(this).val();
The issue is because you're selecting all .checkIt elements in the selector within the change event. When you call val() on a collection of elements jQuery will only return the value of the first one.
To fix this you only need to get the value of the element that raised the change event. To do that, use the this keyword within the handler:
var value = $(this).val();
Try ajax call as given below,
var value = $(this).val();
$.ajax({
type: "POST",
url:'../wp-content/themes/mysite/includes/search-team.php',
dataType: "json",
data: {
value:value
},
success:function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value)
}
})
You can use
$('.checkIt').is(':checked')
This will give you the checked box.
Jquery.val() for checkbox always return ... the value you defined, despite of the checked state.
If you want something like when check return value, else return undefined you should do: value = $('.checkIt:checked').val();

JS: get value of element in ajax updated div

I have a page with a div updated with Ajax request as needed; this div contains an input with dynamic name that I need to get data from. The button and the script that need this data are placed on the main page. When I try to get data with scripts placed in the updated div html itself, it works fine; but same code placed on the main page does not work. How do I find an element by id in Ajax updated div?
Main page:
/* ajax updated div */
<span id="i_descr_{{i.id}}" class="tooltiptext"></span>
/* button */
<div class="trade_move arrow_r" item_id="{{i.id}}" partner_id="{{data.partner_id}}"></div>
<script>
$(".trade_move").click(function() {
var item_id = $(this).attr("item_id");
var partner_id = $(this).attr("partner_id");
var quantity = 1;
var sliderElem = document.getElementById("slider_".concat($(this).attr("item_id")));
if (sliderElem) {
quantity = sliderElem.value;
}
}
</script>
Ajax template, input part:
<input class="slider" type="range" item_id="{{description.id}}" id="slider_{{description.id}}" min="0" max="{{description.slider}}" value="{{description.slider}}" step="1">
If I put the button and the script into the ajax template, they work just fine; is it possible to address the input by its id from main page, loaded before the ajax part?
edit:
I tried adding the button press script to ajax unction that updates the div as by suggestion from Arathi Sreekumar, but it behaves same as before. It also does not work unless you actually load the div with the slider now, meaning it comes from ajax function and not somewhere else. Could I get the syntax wrong or something?
$(".item_description").hover(function(){
var param = $(this).attr("d_id");
$.get('/sud/item_na/', {id: param}, function (data) {
$('#i_descr_'.concat(param)).html(data);
$(".trade_move").click(function() {
var item_id = $(this).attr("item_id");
var quantity = 1;
var sliderElem = document.getElementById("slider_".concat($(this).attr("item_id")));
if (sliderElem) {
quantity = sliderElem.value;
}
$.ajax({
...
});
});
});
edit2: I got it working, not exactly how I wanted it initially, but still.
I did not go into details about the general layout but to make things clear:
1) Layer 1: main page with empty div and a button
2) Layer 2: empty div on main page is populated with ajax html generated by button press. This html is a list of items, each coming with an empty tooltip div, that on hover triggers another ajax query and populates it with item info.
3) Layer 3: Item info window which has the slider control and the button to do something with the item, considering the slider value (and item id naturally).
I put the button and the script attached to it into the last layer 3 template. Here goes the code:
<div align="left">
<input class="slider_value" id="slider_value_{{description.id}}" type="number" value="{{description.slider}}" disabled>
<input class="slider" type="range" item_id="{{description.id}}" id="slider_{{description.id}}" min="0" max="{{description.slider}}" value="{{description.slider}}" step="1">
<div class="trade_move_slider arrow_r" id="trade_move_slider_button_{{description.id}}" item_id="{{description.id}}" partner_id="{{description.partner_id}}" quantity="{{description.slider}}" style="width: 30px;height: 20px;display: inline-block;">
</div>
<script>
$(document).ready(function() {
$(".slider").change(function() {
$("#slider_value_".concat($(this).attr("item_id"))).val($(this).val());
$("#trade_move_slider_button_".concat($(this).attr("item_id"))).attr("quantity", $(this).val());
});
$(".trade_move_slider").click(function() {
$('#output').html('<span class="dot"></span><span class="dot"></span><span class="dot"></span>');
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var item_id = $(this).attr("item_id");
var partner_id = $(this).attr("partner_id");
var quantity = $(this).attr("quantity");
$.ajax({
type:"POST",
url:"/sud/trade_action/",
data: {
'partner': "container",
'id': partner_id,
'goods_id': item_id,
'csrftoken': csrftoken,
'quantity': quantity
},
success: function(data){
$('#output').html(data);
}
});
});
});
</script>
Note how button attribute "quantity" is updated on slider change. For some reason I could not address the slider directly with $('#slider_'.concat(item_id)).val(); might me the problem that brought me here initially. For general purposes I would still like to know how to address elements of one ajax generated DOM (if I'm putting this correctly) with a script in another ajax generated DOM.
This is the code that updates item info on hover:
$(".item_description").hover(function(){
if ($(this).attr("data") == "empty")
{
$(this).attr("data", "loaded");
var param;
var partner_id = $(this).attr("partner_id");
param = $(this).attr("d_id");
$.get('/sud/item_na/', {id: param, list_type: 'char', 'partner_id': partner_id}, function (data) {
$('#i_descr_'.concat(param)).html(data);
});
}
});
You could add a pseudo-class, js-slider in your input element:
<input class="slider js-slider" type="range"
item_id="{{description.id}}"
id="slider_{{description.id}}"
min="0" max="{{description.slider}}"
value="{{description.slider}}" step="1">
and then you this class in order to grab your element.
$(".trade_move").click(function() {
var item_id = $(this).attr("item_id");
var partner_id = $(this).attr("partner_id");
var quantity = 1;
var sliderElem = $(".js-slider");
if (sliderElem) {
quantity = sliderElem.val();
}
}
In the above code, I think that it is evident that item_id and partner_id are not used. So you can eliminate them. Furthermore, I don't see where you use the quantity.

aJax update a specific row in sqlite and php using a button

I've got a table that lists values inputted by a user, with 2 buttons on the side to remove or to mark completed. On the page the table is visable, there are 3 tabs, we will call these Tab1, Tab2, and Tab3
Each tab has a table (As described above) with information about a specific type of entry.
These buttons are simple <a href> links, so when clicked they reload the page. This is a problem because the users view is refreshed and it takes the tabs back to the default tab, and is also an inconvenience when trying to mark several entries.
I would like to make these buttons send Ajax requests to another page to process the data. The only problem is, I am not really sure how to make the ajax call.
This is what I have right now
My buttons
echo "<td class='td-actions'>";
echo " <a href='?complete=".$row['uniqueID']."' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'> </i>
</a>
<a href='?remove=".$row['uniqueID']."' class='btn btn-danger btn-small'>
<i class='btn-fa fa-only fa fa-remove'> </i>
</a>";
echo "</td>";
There is one called Complete, and one called Remove.
When either of these are pressed, it currently reloads the page which triggers a few php if statements.
if(isSet($_GET['remove'])) {
$sql = "DELETE from rl_logged where uniqueID='".$_GET['remove']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
if(isSet($_GET['complete'])) {
$sql = "UPDATE rl_logged set complete=1 where uniqueID='".$_GET['complete']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
These are relatively simple functions. My problem is that I do not know javascript very well.
Any help would be much appreciated.
the javascript that I have come up with is this
$(document).ready(function() {
$('#markComplete').click(function() {
var input = input = $(this).text()
$.ajax({ // create an AJAX call...
data: {
onionID: input,
},
type: 'POST', // GET or POST from the form
url: 'pages/ajax/markCompleteRL.php', // the file to call from the form
success: function(response) { // on success..
refreshAllTabsWithFade();
}
});
});
});
using this button
<div name='markComplete' id='markComplete' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'></i>".$row['uniqueID']."
</div>
But, while inspecting with firebug, this seemed to work ONCE, but now the button doesn't do anything.
I tried again this morning, the button presses and the first time it sends this post, then the button doesn't do it again - even on page reload.
I was able to get it to work with the following:
javascript:
$('.markComplete').submit( function( event ) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // serialize the form
type: "POST", // GET or POST from the form
url: "pages/ajax/repairlogMarks.php", // the file to call from the form
success: function(response) { // on success..
refreshAllTabs();
}
});
return false;
});
button:
<form class="markComplete">
<input type="text" style="display:none;" class="form-control" name="uniqueid" value='<?=$row['uniqueID'];?>'>
<input type="text" style="display:none;" class="form-control" name="markcomp" value='1'>
<button type="submit" class="btn btn-success">
<i class="btn-fa fa-only fa fa-check"></i>
</button>
</form>
Basically, I made the button into a form which I knew how to create an ajax request for.
--
Update to make it work for multiple buttons that do the same function for different unique ID's.
Well for since you're sending the ajax call using "POST", it seems to me that if(isSet($_GET['complete'])) would evaluate to false. Also if your button is generated dynamically using php then change your click handler to the following:
$('document').on('click', '#markComplete', function (){
// Your code here
})
If you have more than one "Mark Complete" button; you need to use classes rather than ID to bind the event.
<button id="test">
Test 1
</button>
<button id="test">
Test 2
</button>
<script>
$('#test').click(function (e) {
console.log('test', e.target);
});
</script>
In this example, only the first button works. jQuery will only return the first element when you specify an ID.
If you use classes to bind the event; both buttons will work:
<button class="test">
Test 1
</button>
<button class="test">
Test 2
</button>
<script>
$('.test').click(function (e) {
console.log('test', e.target);
});
</script>
i think you have an error in your javascript at this line...
var input = input = $(this).text()
try to replace by this..
var input = $(this).text();

Ajax request stores old data

I have a litte problem with my ajax request and I haven't found a solution yet.
What I am trying to accomplish:
I have simple search form, when I submit I send the data to a PHP file which returns the result as json. Then I add the returned data in a clickable list and when I click on one list item I want to display the data in a new div. This actually works fine. Even if I start a new search I get the correct json objects and the list updates as expected but now I have following problem. If I start a new search without refreshing the whole page and again click on a list item, in the console log i see that the new but also the previous data is still kinda stored in the list or wherever and this is the problem because I then display the wrong data if I click on the list items.
I hope you understand my question and I am thankful for every hint. And btw, is my approach even possible or is there a better way to solve this?
Javascript code
$('#searchbar').submit(function(e){
e.preventDefault();
var query = $('#searchQuery').val();
if (query != ''){
loadData();
}else{
alert('Empty searchform!');
}
});
function loadData(){
var query = $('#searchQuery').val();
$.ajax({
type: "POST",
url: "search.php",
data: {'query': query},
dataType: 'json'
}).done(function(res) {
console.log(res);
resetInfos();
generateList(res);
$('.list-group').on('click', '.list-group-item', function(e){
var index = $(this).index();
console.log(res[index].Name);
$('#locationName').text(res[index].Name);
$('#locationAddress').text(res[index].Zip
+ ' '
+ res[index].State);
$('#locationContact').text(res[index].Internet);
init_map(res[index].Latitude, res[index].Longitude);
});
});
}
function resetInfos(){
$('.list-group').empty();
$('#listItems').remove();
$('#searchQuery').val('');
$('#locationName').text('');
$('#locationAddress').text('');
$('#locationContact').text('');
}
function generateList(result){
$.each(result, function(i){
$('.list-group').append('<li class="list-group-item" id="listItems">'
+ result[i].Name
+ ", "
+ result[i].Zip
+ " "
+ result[i].State);
});
}
HTML search form
<form id="searchbar">
<div class="input-group form-group-lg">
<input type="text" id="searchQuery" name="query" class="form-control" autocomplete="off" placeholder="Name, ZIP, State">
<span class="input-group-btn"><button class="btn btn-success btn-lg" id="searchButton" type="submit">Search</button></span>
</div>
<form>
Ok I solved it. I had to remove the click event handler with
$('.list-group').off('click');
in my resetInfos function.
You are using id selector to remove multiple elements.
$('#listItems').remove();
It will only remove the first matched reference. Please add some class to li element and then use class selector to remove.

How to pass multiple checkboxes using jQuery ajax post

How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){
$.post("ajax.php", {
selectedcheckboxes:user_ids,
confirm:"true"
},
function(data){
$("#lightbox").html(data);
});
}
and this is my form
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)
Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
This would be better and easy
var arr = $('input[name="user_ids[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
function hbsval(arg) {
// $.each($("input[name='Hobbies']:checked"), function (cobj) {
var hbs = new Array();
$('input[name="Hobbies"]:checked').each(function () {
debugger
hbs.push($(this).val())
});
alert("No. of selected hbs: " + hbs.length + "\n" + "And, they are: " + hbs[0] + hbs[1]);
}

Categories

Resources