Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send post data from html FORM with Javascript?

I am trying to send post data from from with empty action and send the info with javascript to the file that must handle the post information.

Here is my code:

<HTML>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
            <script>    
    function post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");

        form._submit_function_ = form.submit;

        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for(var key in params) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);
        form._submit_function_();
    }
    post_to_url("./postinfo.php", { submit: "submit" } );
        </script>   
<form method="post" onsubmit="return post_to_url()">
<input type="text" name="ime">
<input type="submit" id="submit" name="submit" value="Send">
</form>

So how i can send the post data to postinfo.php with javascript with empty action in my html form?

Thanks in advance!

like image 854
Tonny Struck Avatar asked Oct 20 '13 10:10

Tonny Struck


2 Answers

You're quite lucky because there's a JQuery function called "Ajax" which handles this for you!

All you need to do is call JQuery, and use code like this:

$('#form_id').on('submit', function(e){
    e.preventDefault();
    $.ajax({
       type: "POST",
       url: "/postinfo.php",
       data: $(this).serialize(),
       success: function() {
         alert('success');
       }
    });
});
like image 79
Richard Peck Avatar answered Sep 28 '22 01:09

Richard Peck


function post_to_url(path, params, method) {
    method = method || "post";

    var form = document.createElement("form");


   _submit_function_ = form.submit;
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);
    form._submit_function_();
}
post_to_url("./postinfo.php", { submit: "submit" } );

change to

post_to_url("/postinfo.php", { submit: "submit" } );
like image 33
Ningappa Avatar answered Sep 28 '22 00:09

Ningappa