1

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.

talemyn
  • 7,110
  • 4
  • 25
  • 45
IceTimux
  • 217
  • 2
  • 9
  • You could use the the attribute selector to get all input of type number and then use a loop and build up a javascript object. – localghost Feb 02 '15 at 19:42
  • What format do you want the JSON to be in? Also, you say `"as you can see below, there are a lot of fields"`, but I only see one `` . . . are you missing some code? – talemyn Feb 02 '15 at 19:44

1 Answers1

2

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

Community
  • 1
  • 1
Ozan
  • 3,449
  • 2
  • 15
  • 22
  • I actually ended up using your method, it was cleaner and the project escalated quickly and yours scales better. – IceTimux Feb 03 '15 at 23:37