skip to Main Content

I am unable to get the value of hidden input from ajax to PHP with the following code. Here the problem is I don’t know the id of input. I mean its dynamic.

<div id="comboproducts">
 foreach ($comboproducts as $product) {
<input type="hidden" id="comboproductsid<?php echo $product['product_id']; ?>" value="<?php echo $product['product_id']; ?>" /> 
}
</div>

ajax part

$.ajax({
    url: 'index.php?route=checkout/cart/addcombo',
    type: 'post',
    data: $('#comboproducts input[type='hidden']'),
    dataType: 'json',
    beforeSend: function() {
        $('#button-cart').button('loading');
    },
    complete: function() {
        $('#button-cart').button('reset');
    },
    success: function(json) {

   alert(json);
        }
    }
});

2

Answers


  1. It comes down to the data you are sending in your AJAX payload. It appears you are using both POST and GET in your script. The post data should be an Object.

    Now if there are multiple IDs of the same type of element, you will need to capture this in your click callback before you call the AJAX. If there is only one, you can use an attribute selector like $("[id^='comboproductsid']") See More: Attribute Starts With Selector.

    $.ajax({
      url: 'index.php?route=checkout/cart/addcombo',
      type: 'post',
      data: {
        "product_id": $("input[type='hidden'][id^='comboproductsid']").val()
      },
      dataType: 'json',
      beforeSend: function() {
        $('#button-cart').button('loading');
      },
      complete: function() {
        $('#button-cart').button('reset');
      },
      success: function(json) {
        alert(json);
      }
    });
    

    In your PHP, this can be reached from $_POST['product_id'].

    Login or Signup to reply.
  2. If I have keys that define the values, I simply add a name attribute to the hidden text field and place the key value as the name. Then iterate over the post values and if those are set, I get those values.

    EX array

    $comboproducts = array(
        'tv' => array(
            'product_id' => 23,
            'price' => 34.23,
            'stock' => 31,
            'shipable' => true
        ),
        'phone' => array(
            'product_id' => 3,
            'price' => 250.99,
            'stock' => 99,
            'shipable' => true
        )
    
    );
    $stmt = null;
    foreach ($comboproducts as $key => $product) {
        $stmt .= '<input type="hidden" name="'.$key.'" value="'.$product['product_id'].'">';
    }
    $value=null;
    foreach ($comboproducts as $key => $product) {
        if(isset($_POST[$key])){
            $value[$key] = $_POST[$key];
        } 
    }
    
    print_r($value);
    

    OUTPUT:

    Array ( 
      [tv] => 23 
      [phone] => 3 
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search