File can be uploaded to php server in various ways. The traditional way uses the form submit to send all the data to php server. In the server side we retrieve all the values via POST method. But apart from, form submit we can also use javascript, ajax and jquery to retrive form fields and send it to server for uploading.
Do the below steps:
- Create a form to upload a file
- Use javascript onclick() method to pass form filed values.
- Make an ajax call to send the data to server.
- Do some file checks and upload the file at the php server
Recommended read, How to upload file in php
Create a multipart/form-data form to upload a file.
<form id="the-form" class="form-control w-50 mx-auto" enctype="multipart/form-data" method="post"> <p class="text-danger pt-2"><strong>Upload product images</strong></p> <input type="file" name="fileToUpload" multiple="true" class="form-control" id="filetoupload"> <button type="button" class="btn btn-primary form-control" onclick="addproduct()" >Add product</button> <br><br> <div class="error"></div> <div class="success"></div> </form>
Use javascript onclick() method to pass form fieled values.
Enclosed the values of form field in a Formdata object and send it server via an ajax call. Set the type to POST and encryption type to multipart/form-data. Do not forget to set processData, contentType and cache to false.
Print the message to the screen depending upon the response from the server.
<script> function addproduct(){ event.preventDefault(); var form = $('#the-form')[0]; var data = new FormData(form); $('.hide').show(); $.ajax({ type: "POST", enctype: 'multipart/form-data', url: "product-upload.php", data: data, processData: false, contentType: false, cache: false, success: function (data) { if(data == 1){ $('.success').html("Product uploaded").show(); $('.error').hide(); } if(data == 0) { $('.error').html("Error uploading file. Pls try again.").show(); $('.success').hide(); } if(data == 2) { $('.error').html("File is not an image.").show(); $('.success').hide(); } if(data == 3) { $('.error').html("File already exist.").show(); $('.success').hide(); } if(data == 4) { $('.error').html("File too large. Keep file size below 200KB.").show(); $('.success').hide(); } if(data == 5) { $('.error').html("Uploaded file is not an image.").show(); $('.success').hide(); } if(data == 6) { $('.error').html("Uknown error occurs.").show(); $('.success').hide(); } }, complete: function(){ $('.hide').hide(); }, error: function (e) { $(".error").text(e.responseText); console.log("ERROR : ", e); } }); } </script>
Use javascript onclick() method to pass form fieled values.
<?php session_start(); error_reporting(E_ALL & ~ E_NOTICE); class Controller { function __construct() { $this->processMobileVerification(); } function processMobileVerification() { $sid = $_POST['subcategories']; $pid = rand(9999,1000); $productname = $_POST['pname']; $price = $_POST['price']; $target_dir = "products-images/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { $uploadOk = 2; } // Check if file already exists if (file_exists($target_file)) { $uploadOk = 3; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { $uploadOk = 4; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { $uploadOk = 5; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 5) { echo 5; } else if($uploadOk == 4){ echo 4; } else if($uploadOk == 3){ echo 3; } else if($uploadOk == 2){ echo 2; } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { $db = mysqli_connect('localhost', 'djtechbl', '(Sani@Vaar8)', 'djtechbl_projects'); $query= "INSERT INTO products (sid,pid,name,price,image1) VALUES('$sid','$pid','$productname','$price','$target_file')"; $result = mysqli_query($db,$query); if(!$result){ die(mysqli_error()); echo 0; exit(); } else echo 1; } else { echo 7; } } } } $controller = new Controller(); ?>
Published on July 9, 2021