Submit the post data including file or image using Jquery ajax()


There are two ways to submit the post data using the jquery ajax function. 1- In first method we store the input form values one by one into variable and send it to the action page/url. 2- While in second method we can send all the form data without specifying each and every input fields (text/file fields). In this way we can also submit the image or some other files using jquery ajax() function.

1- Using the manual variable initializing method

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" name="username" id='username'> <button type="submit" class="submit">Submit</button> <script type="text/javascript"> var username = $("#username").val(); $.ajax({ url: "upload.php", // Url to which the request is send type: "POST", //Type of request to be send, called as method data: ,"username="+username, //Data sent to server(i.e. form fields and values) success: function(response_msg) { alert(response_msg); } }); </script>

2- Using all form fields submission in ajax() function to action page

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="my-form" method="post"> <input type="text" name="username"> <input type="file" name="file"> <button type="submit" class="submit">Submit</button> </form> <script type="text/javascript"> $("#my-form").on('submit',(function(e) { e.preventDefault(); //To prevent the form submission directly $.ajax({ url: "upload.php", // Url to which the request is send type: "POST", //Type of request to be send, called as method data: new FormData(this), //Data sent to server(i.e. form fields and values) ////----TO ovoid the contentType Change----///// contentType: false, // The content type used when sending data to the server. processData:false, // To send DOMDocument or non processed data file it is set to false success: function(response_msg) { alert(response_msg); } }); })); </script>

upload.php file and tested Ouput

<?php echo "Username:".$_POST['username']; echo "File Temp Path:".$_FILES['file']['tmp_name']; ?>

Tested Output by a username text and choosing an image file

Username:CodingPK File Temp Path:C:\wamp\tmp\phpA3B1.tmpmyimagefile.jpg
Chapter Next »