sach jot
sach jot

Reputation: 570

How to take an array of input fields values and pass it through an Ajax call

I have a web form in which look like this right now. The problem is I have a option which adds more dynamically rows below them which looks the same and have the same name attribute. I have a submit button which gets the value of all the input fields. The submitted values goes through an Ajax call to my PHP where I have to insert them in my database.

Access:
<tr>
  <td><input type"text" name="access[name]"></td>
  <td><input type"text" name="access[type]"></td>
  <td><input type"text" name="access[description]"></td>
</tr>

student:
<tr>
  <td><input type"text" name="student[name]"></td>
  <td><input type"text" name="student[type]"></td>
  <td><input type"text" name="student[description]"></td>
</tr>

So far I can't get all the values generated by the input field in an array so that I can properly sort and insert them in my database.

I was looking for my array structure to look like this or like a properly JSON formatted. But I don't know how to do this in Ajax call.

access[
         name:xyz,
         type:xyz,
         description
      ]
student[
         name:xyz,
         type:xyz,
         description
      ]

My Ajax function:

    $('.submit').on('click',function(){

    var access;
    $('input[name^="Access"]').each(function() {
        access= ($(this).val());
    });
    var student;
    $('input[name^="student"]').each(function() {
        student= ($(this).val());
    });

    $.ajax({
           url: '../php/Submission.php',
           type: 'post',
           data: {access:access,student:student}
       },
           function(data1)
            {
                console.log(data1);
            }
      );
}); 

I know my Ajax function is not write but I have tried so many code to make it work as the result it's all messed up and not sure what to do now.

Upvotes: 2

Views: 2350

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25351

Change your access and student variables to become arrays, and add the values to them (Note: you can simply use this.value instead of $(this).val()):

var access = [];
$('input[name^="Access"]').each(function() {
    access.push(this.value);
});
var student = [];
$('input[name^="student"]').each(function() {
    student.push(this.value);
});

EDIT If you want to name your values instead of using the index, you'll need to use objects instead of arrays, and manually extract the name:

var access = {};
$('input[name^="access"]').each(function() {
    var name = this.name.substr(7, this.name.length - 8);
    access[name] = this.value;
});
var student = {};
$('input[name^="student"]').each(function() {
    var name = this.name.substr(8, this.name.length - 9);
    student[name] = this.value;
});

Upvotes: 3

Related Questions