4

I am using the following to submit a form on button click. I need to attach an array named 'selected' to this post as well. I cannot use ajax for this because there will be a download happening on the posting page. I need this array to process the file to be downloaded.

I did some searching and came upon this, but was not able to get it working either :

var input = $("<input>").attr({"type":"hidden","name":"selected"}).val(selected);
$('#test').append(input);

Current :

var selected = [1,2,54,56,23]; // could be anything

$('#test').submit(function(event) {
    if (selected.length > 0)
    {
        $('#test').attr('action','/process/p_screenshots_download2.php');
        $('#test').attr('type','post');
        return;
    }
    event.preventDefault();
});

1 Answer 1

3

Try

$('#test').submit(function(event) {
    $.each(selected, function(i, v){
        var input = $("<input>").attr({"type":"hidden","name":"selected[]"}).val(v);
        $('#test').append(input);    
    });
    if (selected.length > 0)
    {
        $('#test').prop('action','/process/p_screenshots_download2.php');
        $('#test').prop('method','POST');
        return;
    }
    event.preventDefault();
});

this will add a set of hidden inputs with the values in the array to the form before it submits.

Sign up to request clarification or add additional context in comments.

8 Comments

Doesn't seem to work either... I get something along the lines of ...php?selected[]=1609449&selected[]=4697 and doing a var_dump( $_POST['selected']); returns NULL.
@user756659 What's the action of your form? is it GET or POST
$('#test').attr('type','post');
Just realized that was the problem - $('#test').attr('method','post'); Seems to be working properly now.
@user756659 use prop instead of attr $('#test').prop('method','POST'); or just set it to post in the html.
|

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.