Wednesday, June 21, 2017

JavaScript | jQuery: Manual Ajax Form Submit Using XMLHttpRequest | XMLHttpRequest to Post HTML Form | Upload File Ajax | Submit FormData

It's easy to submit an form using JavaScript ajax request. We also can upload files using ajax form submit. Below is a simple code snippet:


<form name="content_info">
    <input type="file" name="file"/>
    <button type="button" onclick="doPost()">Ajax Submit</button>
</form>

<script type="text/javascript">
    function doPost() {
        var form = document.forms.namedItem("content_info");
        var formData = new FormData(form);
        //or formData = new FormData();
        formData.append("custom_param", "custom_param_value");

        var request = new XMLHttpRequest();
        request.open("POST", "submit.php", true);
        request.responseType = "json";
        request.onload = function(oEvent) {
            console.log(request.status);
            console.log(request);
            console.log(request.response);
            alert(request.status);
        };
        request.onerror = function (error) {
            console.log(error);
        };
        request.setRequestHeader("Custom-Code", "EKKODJIU");
        request.send(formData);
    }
</script>




No comments:

Post a Comment