Skip to content Skip to sidebar Skip to footer

How To Submit Individual Input Field Without Form

Recently, I've been writing some Javascript that interacts with a page. As a part of this, I need to be able to submit an HTML input field. From what I've seen, most of the time in

Solution 1:

You can make a post pretty easily with jquery.

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {

                $('#btnSubmit').click(function() {
                    var inputVal = $('#inputField').val();
                    $.ajax
                    ({
                        type: "POST",
                        url: 'your_url_for_handling_post',
                        contentType: "application/json",
                        data: JSON.stringify({"Username":inputVal})
                    })
                    .done(function(data) {
                        console.log(data);
                    });
                });
            });
        </script>

    </head>
    <body>
        <input type='text' id='inputField' name='username' />
        <input type='submit' id='btnSubmit' value='Submit' />

        <!-- you can use any element to trigger the submit
        <div id='btnSubmit'>Submit</div>
        -->
    </body>
</html>

EDIT: json is not a requirement. I just put that in there because that's how I normally do it. You can definitely just send the value by itself.


Solution 2:

You can submit the field by using javascript:

Then the java function can submit the value: function someJSFunction(var event) { var url='/saveValue.php'; var value="savethis="+this.value;

        var request = new XMLHttpRequest();
        request.open('POST', url, true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

        request.send(params);
}

Code untested so needs some work :)


Solution 3:

if you're sending only this input you can use XMLHttpRequest():

var input = document.getElementById('inpputId');
var parameters=input.name+"="+input.value;
var http=new XMLHttpRequest();
http.open('POST','yourfile.php',true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onload=function(){
  //write code after receiving the content
}
http.send(parameters);

Post a Comment for "How To Submit Individual Input Field Without Form"