skip to Main Content

I am sending an ajax request to a php file:

php file

$html .= '
<div class="col-md-4 select_icon_fa"> 
    <i id="id'. $result->id .'" class="fas fa-cart-plus cart_icon select_cart_plus" onClick="add_to_cart('' . $result->id . '', 'add')"></i>
  <select class="select" id="qty' . $result->id . ' ">
    <option value="1">value</option>
    ';  
    for($i=1; $i<=20; $i++) {
        $html .= '              
        <option>' . $i . '</option>
        ';
    }
    $html .= '  
  </select>
</div>

JS

function add_to_cart(id,type) {
    alert(id);
    var qty = jQuery('#qty' + id).val();
    if (qty > 0 ) {
        alert(qty);
        jQuery.ajax({
            url:"<?php echo AJAX_FETCH_DATA ?>",
            type: 'post',
            data:'id='+id+'&qty='+qty+'&type='+type,
            success: function(result) {
                swal("success");
            }
        });
    } else {
        swal("Error", "error");
    }
}

console

id=17254&qty=undefined&type=add

html edit – output

<select class="select" id="qty17256 ">
                <option value="1">value</option> 

The problem is that second value qty is undefined (alert(qty);), if is undefined – cannot send to php file. I don’t know why this is happening.

3

Answers


  1. Try with this line :

    <select class="select" id="qty' . $result->id . '">
    

    It removes the whitespace at the end of the id attribute.

    It seems that whitespaces are not allowed here

    Login or Signup to reply.
  2. It seems your have an extra space for the id attribute (in the end) please remove that space from php.

    Login or Signup to reply.
  3. @Ajith Gopi and aloha solved this problem.

    This combine two problem to cause this issue.

    First one is due to option doesn’t have value attribute, so it won’t able to return any value not matter which option be selected.

    Second one is because select’s id attribute has a extra space. So in fact, this element should call by $('#qty17256 '). (Please noticed that space.)

    enter image description here

    Those two nice user has solved this post together, and I just wanna help you to understand how it work.

    Cheers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search