uploading both data and files on MYSQL Server in one form using ajax

uploading both data and files on MYSQL Server in one form using ajax?

Last Updated by Pooja Chikara 07-May-20

0 446

With the help of Ajax, we can upload data and multiple files in one form and save it to MySQL Server.

Here is the full-length code for this:


Create an index file index.php which contains HTML form to upload data to server and JavaScript code to handle the form data.

We use the jQuery ajax() method to send our form data to the backend file.


<!DOCTYPE html>
<html lang="en">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <div class="container">
<div class="row" style="width:50%;margin:auto;">
<form class="forms-sample form-group" method="post" id="form_id" enctype="multipart/form-data" action="">
<label>Name : </label><input type="text" class="form-control" name="name" id="name" />
<input class="form-control" type="file" name="images[]" id="img" multiple />
  <button type="button" name="submit" class="btn btn-primary upload">Upload</button>
	<div class="row res">

	var t='#form_id';
	var f='img';

	var data = new FormData();

// Form data
var form_data = $(t).serializeArray();
$.each(form_data, function (key, input) {
  data.append(input.name, input.value);
// File data
var file_data = $('input[id="'+f+'"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("images[]", file_data[i]);
    url: "ajax.php",
    method: "post",
    processData: false,
    contentType: false,
    data: data,
    success: function (data) {
    error: function (e) {


Now create ajax.php file to accept the form data and upload it on server

  $countfiles = count($_FILES['images']['name']);
   name = time().$_FILES['images']['name'][$i];
   // Upload file
	// Now create a table into MYSQL Dtabase up_images and make connection to database
	$query="insert into up_images set name='$name'$up_img";
	// now retrieve data from database to show into index.php file
	$sql='select * from up_images order by id DESC';
	foreach($res as $row){
		echo '<h5>'.$row["name"].'</h5>';
		for($i=0;$i<count($a);$i++) {
		echo'<img height="100px" src="upload_images/'.$a[$i].'" >';}


Enter data into a form in index.php file and click on the submit button to see the result.


uploading both data and files on MYSQL Server in one form using ajax?


Leave a Reply

    Waiting for your comments