If you want to upload a file using jQuery AJAX and PHP, then use the following code:
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here’s an example using PHP.
Your HTML is fine, but update your JS jQuery script to look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $('#upload').on('click', function() { var file_data = $('#sortpicture').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); alert(form_data); $.ajax({ url: 'upload.php', dataType: 'text', cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(php_script_response){ alert(php_script_response); } }); }); |
And now for the server-side script, using PHP in this case. upload.php: a PHP script that runs on the server and directs the file to the uploads directory:
1 2 3 4 5 6 7 8 9 10 | <?php if ( 0 < $_FILES['file']['error'] ) { echo 'Error: ' . $_FILES['file']['error'] . '<br>'; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']); } ?> |
Reference: https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.