Chaosjosh
Chaosjosh

Reputation: 137

Send input array with jquery Post without submitting form

I need to Post data to an url without submitting a form and reloading the page but I'm not too good with JQuery. How would I execute something along the lines of this html:

<input type="text" name="name">
<input type="text" name="stuff[]">
<input type="text" name="stuff[]">
<input type="text" name="stuff[]">
<input type="text" name="stuff[]">
<button onclick="send()">send</button>

JQuery:

function send() {
params= {'name': $('#name').val(), 'stuff': $('#stuff[]').val()};
$.post( "url/test", params );
}

Upvotes: 0

Views: 2794

Answers (3)

DominicValenciana
DominicValenciana

Reputation: 1731

You could possibly use the a for loop to iterate through the elements and then put them all in an array.

Upvotes: 0

wrxsti
wrxsti

Reputation: 3504

Additionally you could treat it closer to a traditional form and use the .serialize() method.

HTML

<form name="myForm">
    <input type="text" name="name" />
    <input type="text" name="stuff[]" />
    <input type="text" name="stuff[]" />
    <input type="text" name="stuff[]" />
    <input type="text" name="stuff[]" />
    <input type="submit" value="Send" />
</form>

jQuery

$(function(){
    $('form[name="myForm"]').on('submit', function(e){
        e.preventDefault(); // This prevents the form from actually submitting like a traditional form.
        var formData = $(this).serialize(); // Gathers the form field values
        $.post('url/test', formData, function(data){
            alert(data); // This is the callback that will handle the response from the server.
        });
    });
});

Here is a DEMO. Hope this helps!

Upvotes: 3

Amit
Amit

Reputation: 46323

You can get all the values in all inputs named "stuff[]" like this:

$('#stuff[]').map(function() { return $(this).val(); }).get().join()

This will give you a string concatenating all values, separated by commas.

Use that inside your code like this:

function send() {
  params= {'name': $('#name').val(),
    'stuff': $('input[name="stuff[]"]').map(function() {
       return $(this).val(); }).get().join()};
  $.post( "url/test", params );
}

Upvotes: 2

Related Questions