How to include submit button name and values on form Serialize() ajax

I have trouble, my code doesn't work, because my server script side need a name from the submit button. I'm using Ajax method, and I'm using data: serialize, when I have Click on Submit, it doesn't work. Here is my JavaScript code:

$(function(){
    $('#buy_product').submit(function(e){
        e.preventDefault();
        var submitData = $('#buy_product').serialize();
            submitData.push({ name: this.name, value: this.value });
        $('.loading').html('{{HTML::image('img/ajax-loader.gif')}}');
        $.ajax({
            type: "POST",
            data: submitData,
            url: "{{URL::base()}}/products/view/{{$products->id}}/{{Str::slug($products->name_product, '_')}}",
            success: function(msg){
                $('#qty').val(''); 
                $('.loading').html(msg);
            }
        });
    }); 
}); 

If you have clue, please tell me, I'll be glad.


My button is like this:

<input name="update" id="update" type="submit" value="update">

<input name="empty" id="empty" type="submit" value="empty">

Upvotes: 2

Views: 6131

Answers (2)

Nono
Nono

Reputation: 7302

Try this:

Java Script Code:

<script type='text/javascript'>
        $(function(){
            $('#form').submit(function(e){
                e.preventDefault();
                var submitData = $('#form').serialize();
                var btnName = $('#submit').attr('name');
                var btnVal = $('#submit').val();
                var btn = '&'+btnName+'='+btnVal;
                submitData += btn;
                alert(submitData);                

            }); 
        }); 
</script>

HTML Code:

<form action="" id="form" type='post'>
    <input type="text" name="name" id="name" value='Scott'/>
    <input type="submit" name="submit" id="submit" value='POST'/>
</form>

or use:

var submitData = $('#buy_product').serialize();
submitData += '&btnName=' +  $('#your_submitbtn_id').attr('name') + '&btnValue='+ $('##your_submitbtn_id').attr('value'); 

Upvotes: 0

dcodesmith
dcodesmith

Reputation: 9614

I believe you can't do that but you can use a hidden field

<input type="hidden" name="any_name" value="any_value" />

Upvotes: 1

Related Questions