0

I am trying to post multiple variables from the already dynamically create-able "username" id's such as "username1", "username2", etc. I'm looking for a way to dynamically send these into ONE ajax post request. My problem is mainly with the data parameter.

  var numOfInputs = $('input').length;

  $.ajax({
     type: "POST",
     url: "ajax.php",
     // need way to dynamically pass more of these via numOfInputs.
     data: ({username1 : $('#username1').val()}),
     success: function(msg){
       $('#statuses').html(msg);
     }
   });

requested html:

<input type="text" id="username1"></input><button id="add">+</button><button id="check">Check</button>

<div id="added-fields">
</div>

<div id="statuses">
</div>

2 Answers 2

2
var data = {};
for (var i = 1; i <= numOfInputs; i++) {
   data["username" + i] = $("#username" + i).val();
}
$.ajax(
   ...
   data: data,
   ....
)
Sign up to request clarification or add additional context in comments.

Comments

1

Well you can say:

  $.ajax({
     type: "POST",
     url: "ajax.php",
     data: $('input').map(function() {
                          var o = {};
                          o[this.id] = this.value;
                          return o;
            });
   ...

4 Comments

Throws an error in console: Uncaught SyntaxError: Unexpected token .
Correct me if I'm wrong, but in the map function wouldn't the key word "this" refer to the global object? Shouldn't the map function be written as function(v, i){ return { v.id: v.value; } }
@fsong: this would refer to current element being iterated over. You cannot have v.id : v.value as the key cannot be dynamic. so this is legal "id": v.value" but then, that is not waht the OP wanted.
Hmm.. according to the api, this in the map function is the global object. I will go and test this. You're absolutely right about the not being able to have dynamic key part though.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.