C
C
copenhagen722015-11-13 17:16:47
JavaScript
copenhagen72, 2015-11-13 17:16:47

How to implement adding POST variables on button click?

There is a form, in it different buttons. On clicking the submit button, one variable is created, the name and value are taken from the button's attributes. There is a need to send multiple variables when a button is clicked. How to do it?
I figured out the following button code:

<button type="button" onclick="addPOSTvar([ ['name1' , 'value1'] , ['name2' , 'value2'], ['name3','value3'] ])">Кнопка для 3 переменных</button>

and javascript code:
function addPOSTvar( params ) {  
    var form = $(this).closest('form');   
    form.append($.map(params, function (param) {
        return   $('<input>', {
            type: 'hidden',
            name: param[0],
            value: param[1]
        })
    }));  
   form.submit();


I am not strong in jquery, I made the code according to examples from the Internet and it does not work. What needs to be fixed?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
C
copenhagen72, 2015-11-13
@copenhagen72

The solution is: ru.stackoverflow.com/questions/466138/%D0%94%D0%BE...

function addPOSTvar(context, params ) {  
var form = $(context).closest('form');   
form.append($.map(params, function (param) {
    return   $('<input>', {
        type: 'hidden',
        name: param[0],
        value: param[1]
    })
}));  
form.submit();
}

V
Viktor, 2015-11-13
@master2016

You don't need to add anything to $_POST. It serves other purposes.
Add all the necessary data to the form.

E
elailasou, 2015-11-13
@junk1114

It looks like a creepy crutch =)

D
Dmitry Pavlov, 2015-11-13
@dmitry_pavlov

On click - send AJAX post - api.jquery.com/jquery.post
To do this, serialize the form data into an array - for example, $( "#testform" ).serialize()
Then add additional data to this array - key / value - any in the usual way for you in JS
Well, you actually send an AJAX post to the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question