2

In one of my HTML page, there are a few input fields with the same name attributes since I want to send them as an array to another PHP for back-end transactions.

Suppose the input field like below :

<input type="text" name="language_names[]" value="english">
<input type="text" name="language_names[]" value="french">
<input type="text" name="language_names[]" value="spanish">

Now I want to use Jquery to send this array? I am using the .post() method for this, I know for single value it could be send as {key1: value1, key2:value2...}, but for array How can I do it like this ? I guess it should be close to

{'language_names[]' : $('#input[name="language_names[]"]').val()}

But it doesn't work (I check the request body). Anyone can help ?

1

3 Answers 3

5

Use serialize function of jquery like this

// This returns a json representation of your form values
$('#formid').serialize();
Sign up to request clarification or add additional context in comments.

1 Comment

If I just want to send this array, not the whole form, how can I can this ?
0

Since you need a simple array with the values of those specific input elements, you could use something like:

function getLanguageValues() {
    var language_names = [];
    $.each($("input[name=language_names\\[\\]]"), function (indexInArray, valueOfElement) {
        language_names.push($(valueOfElement).val());
    });
    return language_names;
}

Here is the jsfiddle.

Comments

0

Or you can also do this :

{'language_names[]' : $('input[name=language_names\\[\\]]').serialize()}

1 Comment

I am expecting the serialize method will return an array of values in the value attribute. In my case, the array should contain "english", "french", "spanish", etc. However, with your proposed method, it's empty.

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.