3

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?

2 Answers 2

4

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);
            }

        });
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);
  }

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.