8

Is it possible to send post-variables with javascript? I want id to be sent with post, not get.

window.location.href="hanteraTaBortAnvandare.php?id=10";

5 Answers 5

16

The simplest way is to just have a form in your page:

<form method="POST" action="hanteraTaBortAnvandare.php" id="DeleteUserForm">
<input type="hidden" name="id" value="10" />
</form>

Then you just post the form:

document.getElementById("DeleteUserForm").submit();
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but before sending the form, I want alert() the user to conform (yes or no) sending the form.
That's easy, just use a confirmation in an if statement: if (window.confirm('Vill du verkligen radera användaren?')) { post form... }
Please accept the answer if it solved your issue.
15

You can use a form and then document.getElementById('id_of_the_form').submit();

The form doesn't need to be wrote as plain HTML: you can create it dinamically:

     function postIt()   {
        form = document.createElement('form');
        form.setAttribute('method', 'POST');
        form.setAttribute('action', 'someURL');
        myvar = document.createElement('input');
        myvar.setAttribute('name', 'somename');
        myvar.setAttribute('type', 'hidden');
        myvar.setAttribute('value', 'somevalue');
        form.appendChild(myvar);
        document.body.appendChild(form);
        form.submit();   
}

Comments

10

You can do it with an Ajax-request (or use hidden forms) - in that case;

MooTools example:

new Request({
    url: 'hanteraTaBortAnvandare.php',
    method: 'post',
    data: {
        'id': '10'
    },
    onComplete: function(response) {
        alert(response);
    }
});

jQuery example:

$.ajax({
    type: 'post',
    url: 'hanteraTaBortAnvandare.php',
    data: 'id=10',
    success: function(response) {
        alert(response);
    }
});

Of course you could do this without external libraries, but they simplify alot!

1 Comment

+1 for code examples. You might consider including a link to MooTools.
1

You can submit form data via JavaScript but not using window.location.href. Changing the URL location is always going to issue a GET.

You'll need to get a reference to your form from the DOM and then issue a submit() call to it.

Comments

1

You can use the XMLHTTPRequest() object.

2 Comments

Please do not provide "w3fools" (please google it) references, their closed (non wiki type) form doesn't provide quality knowledge.

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.