Adding multiple items to Shopify cart with one click - ajax

I have a Shopify site which, when viewing certain product I give the buyer the option of adding other related items at the same time. Each related product has it's own quantity input, with names "quantity1", "quantity2" etc.
What I would like to do is to count how many input names are on my page that contain the text "quantity", then create a loop over this quantity and add each item, via AJAX, that has a quantity greater than zero.
I am very new to this so not really sure what I'm doing, and have tried hours of looking into a solution but keep hitting a brick wall.
I have done the easy part, which is counting the number of "quantity" inputs using this code:
var len = $('input[id^=quantity]').length;
This is successful, but I am struggling on the loop within the AJAX call, I have tried lots of different code but none works. I would effectively like to do the following:
function addItemToCart(variant_id, qty) {
var len = $('input[id^=quantity]').length;
data = {"id": $('#quantity'+loopnumber).parent().attr('name'),
"quantity": parseFloat($("#quantity"+loopnumber).val()),
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function()
I understand I have not put the for loop code in here but that's because I don't know where to put it, and am hoping that someone could help me out please. The "loopnumber" text in the data fields would refer to the current iteration of the loop, so iteration 1 would look for the input name "quantity1" and look for it's respective value, post that to the AJAX cart, and on success loop over the next quantity values until it reaches the for loop limit. At which point it then redirects to the cart.
I know that I could simply do the following, without the loop, but this is wasteful in my opinion:
var quantity1 = parseFloat($("#quantity1").val());
var qty1 = $('#quantity1').parent().attr('name');
var quantity2 = parseFloat($("#quantity2").val());
var qty2 = $('#quantity2').parent().attr('name');
var quantity3 = parseFloat($("#quantity3").val());
var qty3 = $('#quantity3').parent().attr('name');
var quantity4 = parseFloat($("#quantity4").val());
var qty4 = $('#quantity4').parent().attr('name');
var quantity5 = parseFloat($("#quantity5").val());
var qty5 = $('#quantity5').parent().attr('name');
data = {
"id": prodid,
"quantity": mainquantity,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty1,
"quantity": quantity1,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty2,
"quantity": quantity2,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty3,
"quantity": quantity3,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty4,
"quantity": quantity4,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
data = {
"id": qty5,
"quantity": quantity5,
}
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() { window.location.href = '/cart'
;
}
});
;
}
});
}})}})}})}})};
Any help is greatly appreciated!
Thanks
Jon

I've sorted it, I was overly complicating things. All I had to do was create an array and that negates having to create an AJAX loop which I couldn't get working. It's also MUCH quicker to add all the items to the AJAX cart in one go too.

Related

How to show array result in ajax success using codeigniter?

I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]
assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})

How to include two URL in json ajax

Currently, the searchform hit, the form get submitted. Then it will fetch data from specified URL which is search/ajax2.php and return data here.
All I want to add is, to include another URL beside the above mentioned one, so that two actions can be performed at the same time.
Now, in the search/ajax2.php it runs a select query. Whereas in additional page that I want to include, which could be writedb.php it inserts data taken from this jason into database. It doesn't have to return anything back to ajax page though!
How to achieve this?
$("#searchform").on("submit", function () {
//$(this).find(':submit').attr('disabled','disabled');
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "search/ajax2.php",
data: data,
success: function (data) {
}
});
Try adding your second url in sucess function like this :
$.ajax({
type: 'POST',
url: 'some_url1',
data: 'some data',
success: function(data){
$.ajax ({
type: 'POST',
url: 'some_url2',
data: 'some data',
success: function(data){}
});
}
});

kendo grid custom delete not persisting to datasource

I simply want to use my own workflow for deleting a record from my grid. Is this not the proper way to do it via Javascript? The function below removes the row but refreshing the page shows the row was not actually deleted from the datasource and I do not see any requests sent in the network tab of Chrome. I should add that I am able to obtain a reference to the grid and the dataItem perfectly.
function delete(e) {
var $tr = $(e.currentTarget).closest("tr"),
grid = this,
dataItem = grid.dataItem($tr),
id = $tr.attr(kendo.attr("uid")),
model = grid.dataSource.getByUid(id);
e.preventDefault();
grid.dataSource.remove(model);
grid.dataSource.sync();
}
Edit - Here is how my datasource is defined:
$scope.contacts = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl,
dataType: "json",
type: "GET"
},
update: {
url: apiUrl,
dataType: "json",
type: "POST"
},
destroy: {
url: apiUrl,
type: "DELETE"
},
create: {
url: apiUrl,
dataType: "json",
type: "POST"
}
},
pageSize: 10
});
I found something and I dont know if it works in your side.
I needed to add this line in my kendo.datasource
schema: {
model:{id:"id"}
}
and trigger like this
data_source_inspection.remove(selected.data);
data_source_inspection.sync();
this works for me.

Ajax Success Function not working

I am using Ajax to add contents on my database. And here's the code:
function addToFavorites(){
var recipe_id = $("#recipe_id").val();
var url = connect_url+'addFavorite.php?user_id='+user_id+'&recipe_id='+recipe_id;
$.ajax({
type: 'POST',
data: [{
user_id: user_id,
recipe_id: recipe_id
}],
url: url,
async: true,
jsonpCallback: 'userCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
alert("HELLO!!!");
},
error: function (e) {
alert("ERROR!");
}
});
}
The Ajax call was successful and I was able to add records on the database but I'm just wondering why is it not displaying the alert message if the calling was successful? Is there something wrong with my code? Or is there something wrong with my understanding? Thanks!
you must give a response with some info to the ajax or it won't know the response succeeded

How do I get data out of the "data" variable in jQuery and Django

I think it goes a little something like this:
In my view:
from django.core import serializers
And later....
data = serializers.serialize('json', MODEL.objects.filter(id=id), fields=('points'))
return HttpResponse(data)
In my jQuery:
$.ajaxSetup({
dataType: "json"
});
$('#selector .selector_detail a').click(function() {
var call_to = $(this).attr('href');
$.ajax({
url: call_to,
type: "POST",
complete: function() {
console.log('Ajax Complete')
},
success: function(data) {
points = data(fields.points)
console.log('Ajax Successful')
console.log(data);
},
error: function(xhr) {
console.log('Whoops, something went wrong. XHR Response:' + JSON.stringify(xhr));
},
});
return false;
});
I want the value of points, but I have no idea how to get it out. I can see it in the console.log when I look at the data Objects. What am I missing?
if data is a json object and the correct headers are set, you can access it's properties using a dot:
data.points
data[0].points //if points is an array
//this is not correct
data(fields.points);
I don't know what's the exact structure of 'data' but you can derive it from your console.log(data);
EDIt - if data has the structure you outlined in the comment you can access points like this:
alert(data[0].fields.points);
add dataType: 'json' to your .ajax call.
$.ajax({
url: call_to,
dataType: 'json',
type: "POST",
then its jut data.points in your success function, or perhaps data.field.points. I can't tell from your post.

Resources