{"id":246,"date":"2019-07-28T10:29:38","date_gmt":"2019-07-28T10:29:38","guid":{"rendered":"https:\/\/scriptut.com\/?p=246"},"modified":"2024-05-23T16:22:36","modified_gmt":"2024-05-23T16:22:36","slug":"jquery-file-upload","status":"publish","type":"post","link":"https:\/\/scriptut.com\/jquery\/jquery-file-upload\/","title":{"rendered":"How to Implement a Seamless jQuery File Upload with AJAX"},"content":{"rendered":"\n<p>jQuery file upload is a simple and efficient way to enhance user experience on your website. In this guide, I&#8217;ll walk you through how to upload a file using AJAX and jQuery, providing a modern and responsive approach to handling file uploads.<\/p>\n\n\n\n<p><strong>Step 1: Setting Up jQuery<\/strong><\/p>\n\n\n\n<p>First, ensure you have the latest jQuery library. You can download it from the official jQuery website or include it directly from Google&#8217;s CDN. While using a CDN is convenient, for production environments, it&#8217;s recommended to host the jQuery file locally on your server.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;head>\n  &lt;script src=\"https:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/3.4.1\/jquery.min.js\">&lt;\/script>\n&lt;\/head>\n<\/code><\/pre>\n\n\n\n<p><strong>Step 2: HTML Structure<\/strong><\/p>\n\n\n\n<p>Create a simple HTML structure with an input field for file selection and a button to trigger the upload process.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;body>\n  &lt;div>\n    &lt;label for=\"my_image\">Upload Image&lt;\/label>\n    &lt;input type=\"file\" name=\"my_image\" id=\"my_image\" onChange=\"onChangeHandler(event)\" \/>\n  &lt;\/div>\n  &lt;div>\n    &lt;input type=\"button\" value=\"Upload\" name=\"upload_file\" onClick=\"saveFile()\" \/>\n  &lt;\/div>\n  &lt;div id=\"results\">&lt;\/div>\n&lt;\/body><\/code><\/pre>\n\n\n\n<p>In this setup, the <code>onChangeHandler<\/code> function captures the selected file, and the <code>saveFile<\/code> function handles the file upload.<\/p>\n\n\n\n<p><strong>Step 3: JavaScript Functions for Handling File Upload<\/strong><\/p>\n\n\n\n<p>Define the necessary JavaScript functions to handle the file selection and upload using AJAX.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;script>\n  const data = new FormData();\n\n  function onChangeHandler(event) {\n    data.append('file', event.target.files&#91;0]);\n  }\n\n  function saveFile() {\n    $.ajax({\n      type: \"POST\",\n      url: 'uploadfile.php',\n      data: data,\n      contentType: false,\n      processData: false,\n      success: function(response) {\n        $(\"#results\").html(response);\n      },\n      error: function(jqXHR, textStatus, errorThrown) {\n        $(\"#results\").html(`&lt;p>Error: ${textStatus}&lt;\/p>`);\n      }\n    });\n  }\n&lt;\/script><\/code><\/pre>\n\n\n\n<p>Here, <strong><code>FormData<\/code> <\/strong>is used to construct a set of key\/value pairs representing form fields and their values, which can then be easily sent using the <code><strong>$.ajax<\/strong><\/code> method. The <strong><code>contentType<\/code> <\/strong>and <strong><code>processData<\/code> <\/strong>options must be set to <strong><code>false<\/code> <\/strong>to correctly send the file data.<\/p>\n\n\n\n<p><strong>Step 4: Server-Side File Handling with PHP<\/strong><\/p>\n\n\n\n<p>On the server side, you&#8217;ll need a PHP script to handle the incoming file upload request. This script will save the uploaded file and return a response.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;?php\nif ($_FILES) {\n    $allowedExts = array(\"gif\", \"jpeg\", \"jpg\", \"png\");\n    $temp = explode(\".\", $_FILES&#91;\"file\"]&#91;\"name\"]);\n    $extension = end($temp);\n\n    if ((($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/gif\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/jpeg\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/jpg\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/pjpeg\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/x-png\")\n    || ($_FILES&#91;\"file\"]&#91;\"type\"] == \"image\/png\"))\n    &amp;&amp; ($_FILES&#91;\"file\"]&#91;\"size\"] &lt; 2000000)\n    &amp;&amp; in_array($extension, $allowedExts)) {\n        if ($_FILES&#91;\"file\"]&#91;\"error\"] > 0) {\n            echo \"Return Code: \" . $_FILES&#91;\"file\"]&#91;\"error\"] . \"&lt;br>\";\n        } else {\n            $filename = \"upload\/\" . $_FILES&#91;\"file\"]&#91;\"name\"];\n            move_uploaded_file($_FILES&#91;\"file\"]&#91;\"tmp_name\"], $filename);\n            echo json_encode(array(\n                \"status\" => \"success\",\n                \"message\" => \"File uploaded successfully!\",\n                \"path\" => $filename\n            ));\n        }\n    } else {\n        echo json_encode(array(\n            \"status\" => \"error\",\n            \"message\" => \"Invalid file\"\n        ));\n    }\n}\n?>\n\n<\/code><\/pre>\n\n\n\n<p>In this script, we validate the file type and size before saving it to the server. If the file meets the criteria, it is saved in the &#8220;upload&#8221; directory, and a success message is returned. Otherwise, an error message is displayed.<\/p>\n\n\n\n<p><strong>Step 5: Testing the File Upload Feature<\/strong><\/p>\n\n\n\n<p>Create the HTML and PHP files as described and place them in your local server environment (e.g., XAMPP, WAMP). Open the HTML file in your browser and test the file upload functionality. Ensure your &#8220;upload&#8221; directory has appropriate permissions for file writing.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<p><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;Upgrade your web forms with jQuery and AJAX for seamless file uploads. This article provides detailed instructions and code examples to help you get started.&#8221;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-246","post","type-post","status-publish","format-standard","hentry","category-jquery"],"_links":{"self":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/246","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/comments?post=246"}],"version-history":[{"count":3,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/246\/revisions"}],"predecessor-version":[{"id":326,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/posts\/246\/revisions\/326"}],"wp:attachment":[{"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/media?parent=246"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/categories?post=246"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/scriptut.com\/wp-json\/wp\/v2\/tags?post=246"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}