0

I need help to create array which to be passed via ajax to php page.

here is my html

$(document).ready(function() {
  $('.p_options').change(function() {
    if ($(this).is(":checked")) {
      $(this).next(".opts_qty").val(1).show();
    } else $(this).next(".opts_qty").val(0).hide();
  })
});
.optschecks {
  display: inline-block;
  margin: 3px 0;
  text-align: left;
  width: 100%;
}

.opts_qty {
  width: 50px;
}

.showerror,
.opts_qty {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function addtocart(id){
 arr = {};
 var error = 0;
 var checked = 0;
if ($('.p_options').length) {

  $('.p_options').each(function() {
    if ($(this).is(":checked")) {
      var num = $(this).next(".opts_qty").val();
      if (num !== '' && num > 0) {
        //info[id].push($(this).val());
        arr[id] = $(this).val();
        checked++;
        $(this).next(".opts_qty").css('background', '#fff');
      } else {
        $(this).next(".opts_qty").css('background', 'red');
        error++;
      }
      
    }
  });
  alert(JSON.stringify(arr));

}
if(error < 1){
$.ajax({
    type: "post",
    url: "./shop/basket.php",
	data: { "product": id ,  'product_options':arr},
    dataType: 'json',
    cache: false,
    success: function(data){
	alert('success');
    }
});


}

}
</script>
<div class="inprd">Please select from options for Size
  <label class="optschecks">
    <input type="checkbox" value="S - 16 mm" name="options[]" class="p_options" data="2617"> S - 16 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">    
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" M - 17mm" name="options[]" class="p_options" data="2617"> M - 17mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" L- 18 mm" name="options[]" class="p_options" data="2617"> L- 18 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
</div>
<span class="add_to_cart_container ib"><button onclick="addtocart(this.id);" name="ring" id="2617" class="add_to_cart" price="52.00" type="button">Add to basket</button></span>

If you run the snippet you will see its working but out of the loop the array consist only ID + 1 selected option. If the customer selects more than 1 option it is not saved. How to add all selected options? AND something else I can not manage - how to add the quantity for each product option which is selected to the array? Thank you for your help and time !

4 Answers 4

1

Instead of using an object to save your values you could use an array, like the example...

$(document).ready(function() {
  $('.p_options').change(function() {
    if ($(this).is(":checked")) {
      $(this).next(".opts_qty").val(1).show();
    } else $(this).next(".opts_qty").val(0).hide();
  })
});


function addtocart(id){
 arr = [];
 var error = 0;
 var checked = 0;
if ($('.p_options').length) {

  $('.p_options').each(function() {
    if ($(this).is(":checked")) {
      var num = $(this).next(".opts_qty").val();
      if (num !== '' && num > 0) {
        //info[id].push($(this).val());
        var object = {};
        object[''+$(this).val()] = num;
        arr.push(object);
        checked++;
        $(this).next(".opts_qty").css('background', '#fff');
      } else {
        $(this).next(".opts_qty").css('background', 'red');
        error++;
      }
      
    }
  });
  alert(JSON.stringify(arr));

}
if(error < 1){
$.ajax({
    type: "post",
    url: "./shop/basket.php",
	data: { "product": id ,  'product_options':arr},
    dataType: 'json',
    cache: false,
    success: function(data){
	alert('success');
    }
});


}

}
.optschecks {
  display: inline-block;
  margin: 3px 0;
  text-align: left;
  width: 100%;
}

.opts_qty {
  width: 50px;
}

.showerror,
.opts_qty {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>

</script>
<div class="inprd">Please select from options for Size
  <label class="optschecks">
    <input type="checkbox" value="S - 16 mm" name="options[]" class="p_options" data="2617"> S - 16 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">    
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" M - 17mm" name="options[]" class="p_options" data="2617"> M - 17mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" L- 18 mm" name="options[]" class="p_options" data="2617"> L- 18 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
</div>
<span class="add_to_cart_container ib"><button onclick="addtocart(this.id);" name="ring" id="2617" class="add_to_cart" price="52.00" type="button">Add to basket</button></span>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you RenzoCC, its working this way but how can I add quantity to this array, so finaly to have for example ["S - 16 mm":"1"," M - 17mm":2] ?
I have already corrected the script, you can push an object to the array in order to achieve that result.... thumbs up if it helped you..
Huge Thanks RenzoCC!
1

You can create columns for multidimensional array then stringify it as JSON

Working jsfiddle

$(".add_to_cart").click(function(){
    arr = [];
    var error = 0;
    var checked = 0;
    $('.p_options').each(function() {
         if ($(this).is(":checked")) {
         var num = $(this).next(".opts_qty").val();
            if (num !== '' && num > 0) {
              arr.push({
                Item : $(this).val(), 
                Quantity : num
              });
            }
         }
    });
    alert(JSON.stringify(arr));
});

Comments

1

You can avoid a lot of messing about by better exploiting jQuery collections and their methods.

function addtocart(id) {
    var $checked = $('.p_options').filter(':checked');
    $checked.next(".opts_qty").css('background', '#fff'));
    var $badns = $checked.filter(function() {
        return !(+$(this).next(".opts_qty").val()); // anything falsy is bad
    }).next(".opts_qty").css('background', 'red');
    if($badns.length === 0) {
        var product_options = $checked.get().map(function(opt) {
            var object = {};
            object[opt.value] = $(opt).next(".opts_qty").val(); // from RenzoCC's answer
            return object;
        });
        return $.ajax({ // don't forget to return the jqXHR (promise)
            type: 'post',
            url: './shop/basket.php',
            data: { 'product':id, 'product_options':product_options},
            dataType: 'json',
            cache: false
        });
    } else {
        return $.Deferred().reject(new Error('no options selected')).promise(); // and return a rejected promise if validation fails
    }
}

By returning a promise, addtocart's caller is kept informed of the outcome.

Comments

0

If you still need an object you can try this

$(document).ready(function() {
  $('.p_options').change(function() {
    if ($(this).is(":checked")) {
      $(this).next(".opts_qty").val(1).show();
    } else $(this).next(".opts_qty").val(0).hide();
  })
});
.optschecks {
  display: inline-block;
  margin: 3px 0;
  text-align: left;
  width: 100%;
}

.opts_qty {
  width: 50px;
}

.showerror,
.opts_qty {
  display: none;
}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
  function addtocart(id) {
    arr = {};
    var error = 0;
    var checked = 0;
    if ($('.p_options').length) {
      $('.p_options').each(function() {
        if ($(this).is(":checked")) {
          var num = $(this).next(".opts_qty").val();
          if (num !== '' && num > 0) {
            if (!arr[id])
              arr[id] = []
            arr[id].push({
              item: $(this).val(),
              qty: num
            });
            checked++;
            $(this).next(".opts_qty").css('background', '#fff');
          } else {
            $(this).next(".opts_qty").css('background', 'red');
            error++;
          }
        }
      });
      alert(JSON.stringify(arr));
    }
    if (error < 1) {
      $.ajax({
        type: "post",
        url: "./shop/basket.php",
        data: {
          "product": id,
          'product_options': arr
        },
        dataType: 'json',
        cache: false,
        success: function(data) {
          alert('success');
        }
      });
    }
  }
</script>
<div class="inprd">Please select from options for Size
  <label class="optschecks">
    <input type="checkbox" value="S - 16 mm" name="options[]" class="p_options" data="2617"> S - 16 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" M - 17mm" name="options[]" class="p_options" data="2617"> M - 17mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" L- 18 mm" name="options[]" class="p_options" data="2617"> L- 18 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
</div>
<span class="add_to_cart_container ib"><button onclick="addtocart(this.id);" name="ring" id="2617" class="add_to_cart" price="52.00" type="button">Add to basket</button></span>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.