IceTimux
IceTimux

Reputation: 237

Take input from html field and store it in JSON object (lots of input fields)

I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code

Javascript/jQuery:

$(document).ready(function() {
    $('.add-to-cart').click(function() {
        var id = $(this).attr('id');
        //var qty = $(this).attr('qty'); <- need the quantity from the field 
        console.log(id);
        //console.log(qty);
        $.ajax({
            url: 'addproduct',
            type: 'POST',
            datazType: 'JSON',
            data: {
                "id": id
                //"qty": qty
            },
            success: function(addedproduct) {
                console.log(addedproduct.name);
                $('#cart').append('<li>'+ addedproduct.name +'</li>');
            },
            error: function() {
                console.log('failed to add product');
            }
        })
    });
});

HTML:

<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>

Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.

Upvotes: 1

Views: 1507

Answers (1)

Ozan
Ozan

Reputation: 3739

jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.

Helpful example: https://stackoverflow.com/a/6960586/4180481

Upvotes: 2

Related Questions