mattchambers
mattchambers

Reputation: 185

jQuery ajax, name of data field attached with var

How is it possible to add a variable to the name of the data field I want to send information to through ajax.

Here's an example of my code.

              var qty = $('#qty_'+value).val();

            $.ajax({

                url: 'ajax/save_order-2.php?id='+value,
                type: 'POST',
                data: {

                    qty_'+value': qty

                },
                dataType: 'HTML',
                success: function(order_info_response){

                    console.log(order_info_response);
                }

            });

How do I attach the variable "value" to the data name "qty" just like I did with the var qty.

What is the proper format for doing this without getting Syntax Error?

Upvotes: 3

Views: 1165

Answers (2)

guest271314
guest271314

Reputation: 1

Try creating object outside of $.ajax() , adjusting + operator to before string "value"

var data = {};

var qty = $('#qty_' + value).val();

data[qty_ + "value"] = qty;

$.ajax({

  url: 'ajax/save_order-2.php?id=' + value,
  type: 'POST',
  data: data,
  dataType: 'HTML',
  success: function(order_info_response) {
    console.log(order_info_response);
  }

});

Upvotes: 1

LTasty
LTasty

Reputation: 2008

You need to creare array and pass it

        var qty = $('#qty_'+value).val();
        var data = {};
        data["qty_"+value] = qty;
        $.ajax({

            url: 'ajax/save_order-2.php?id='+value,
            type: 'POST',
            data,
            dataType: 'HTML',
            success: function(order_info_response){

                console.log(order_info_response);
            }

        });

Upvotes: 4

Related Questions