Code With Mark
Home
About
Resources
Contact

Easily Send JSON Data And Upload Multiple File

Learn how to use javascript fetch function to send json data to your server and upload multiple files via php.

Download Code

Learn more about fetch function.

HTML & Javascript Code: 

<!DOCTYPE html>
<html>
<head>
	 
	<title> Fetch JS - Code With Mark </title>

	<meta name="viewport" content="width=device-width, initial-scale=1">

 
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">


	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script> 

	<script type="text/javascript">
	$(document).ready(function($) 
	{ 
		//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
 

		$(document).on('click', '.btn_get_api_data', function(event) 
		{
			event.preventDefault();

			const url = 'https://randomuser.me/api/';

			const options = 
			{
			    method: 'GET', // *GET, POST, PUT, DELETE  
			};

			fetch(url, options)
			.then(response => response.json()) 
			.then(json => 
			{
				var str = JSON.stringify(json.results, null, 5);
				$(document).find('.post_msg').html('<pre class="bg-dark text-white">'+str+'</pre>');
			}
			).catch(err => 
				console.error(err)
			);
		});

		//--->load user screen > start
		$(document).on('click', '.btn_load_user_screen', function(event) 
		{
			event.preventDefault();

			var s1 = $(document).find('.container_user_screen').html();
			$(document).find('.post_msg').html(s1);
		});		
		//--->load user screen > end


		//--->upload file > start
		$(document).on('click', '.btn_upload_file_data', function(event) 
		{
			event.preventDefault();

			let e0  = $(document).find('.post_msg');

			//get file objects
			let f0 	= e0.find('#f0')[0].files;
			let f1 	= e0.find('#f1')[0].files;
			let f2 	= e0.find('#f2')[0].files;

			let fd 	= new FormData();

			fd.append('user_name', e0.find('.user_name').val());			
			fd.append('user_email', e0.find('.user_email').val());

			//single file
			fd.append('file_obj_0',f0[0]);

			//get all the files for group 1
			$.each(f1, function(i1, v1) 
			{ 
				fd.append('file_obj_1[]',v1);
			});


			//get all the files for group 2
			$.each(f2, function(i2, v2) 
			{ 
				fd.append('file_obj_2[]',v2);
			});

			const url = 'ajax.php';
			const options = 
			{
			    method: 'POST',
			    body: fd,
			};

			fetch(url, options)
			.then(response => response.json()) 
			.then(json => 
			{
				var s1 = $(document).find('.post_msg');
				var str = JSON.stringify(json, null, 5);
				s1.html('<pre class="bg-dark text-white">'+str+'</pre>');

				if(json.file_obj_1.length > 0)
				{
					$.each(json.file_obj_1, function(i1, v1) 
					{
						var t1 = ''
						+'<div class="1col-md-3">'
							+'<img src="'+v1.download_file_path+'" class="rounded-circle"   width="100" height="100">'
							+'<br>'
							+'<a href="'+v1.download_file_path+'" download class="btn btn-success">Download File</a>'
						+'</div>'
						;
						s1.append(t1);
					});
					s1.append('<br><br>');
				}
			}
			).catch(err => 
				console.error(err)
			);

		});		
		//--->upload file > end
 
	});
	</script>

</head>
<body>

<div style="padding-top:30px;">	

	<div class="container text-center">
		<h1 class="">Fetch - Upload Files </h1>
		<div class="btn btn-success btn_get_api_data">Get API Data</div> | <div class="btn btn-success btn_load_user_screen">Upload File</div>
		
		<br><br>

		<div class="post_msg text-left"></div>

	</div>

</div>

<div style="display:none;" class="container_user_screen">
	
	<div class="form-group">
      <label for="usr">Name:</label>
      <input type="text" class="form-control user_name">
    </div>
    <div class="form-group">
      <label >Email</label>
      <input type="text" class="form-control user_email">
    </div>

    <div class="card" style="padding:10px;">
	    <label >Single File</label>
	    <input type="file" id="f0">
	    <br>
	</div>
	<br> 

	<div class="card" style="padding:10px;">	
    	<label >Multiple Files</label>
		<input type="file" id="f1" multiple>
		<br>
	</div>
	<br> 

	<div class="card" style="padding:10px;">	
    	<label >Multiple Files</label>
		<input type="file" id="f2" multiple>
	</div>
	<br>

	<span class="btn btn-primary btn_upload_file_data">Upload</span>


</div>

</body>
</html>

PHP Code:

<?php 

define("ABSPATH", str_replace("\\", "/",  dirname(__FILE__) ));

if (isset($_SERVER['HTTPS']) &&
    ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $ssl = 'https';
}
else {
  $ssl = 'http';
}
 
$app_url = ($ssl  )
          . "://".$_SERVER['HTTP_HOST']
          //. $_SERVER["SERVER_NAME"]
          . (dirname($_SERVER["SCRIPT_NAME"]) == DIRECTORY_SEPARATOR ? "" : "/")
          . trim(str_replace("\\", "/", dirname($_SERVER["SCRIPT_NAME"])), "/");

if(isset($_POST['user_name']))
{
	$el = $_POST;

	$user_name = $el['user_name'];
	$user_email = $el['user_email'];


	$upload_folder_path = '/uploads/';

	$a0 = array();
	$a1 = array();
	$a2 = array();

	
	
	//--->upload > single file > start
	if(isset($_FILES['file_obj_0']))	
	{
		$file_obj_0 = $_FILES['file_obj_0'];
		$v1 		= $file_obj_0['name'];

		$file_name = $v1;
		$ext = pathinfo($file_name, PATHINFO_EXTENSION);
		$new_file_name = 'file_obj_0_'. hash('crc32',uniqid()).'.'.$ext;

		$fileDest = ABSPATH.$upload_folder_path.$new_file_name;

		move_uploaded_file($file_obj_0['tmp_name']  ,$fileDest);

		array_push($a0,  array(
			'old_file_name' => $v1,
			'new_file_name' => $new_file_name,
			'move_to_folder'=>$app_url.$upload_folder_path,
			'download_file_path'=>$app_url.$upload_folder_path.$new_file_name,
			
		));
	
	}	
	//--->upload > single file > end
	
	//--->upload group files > 1 > start
	if(isset($_FILES['file_obj_1']))	
	{
		$file_obj_1 = $_FILES['file_obj_1'];
	
		foreach ($file_obj_1['name'] as $k1 => $v1) 
		{
			$file_name = $v1;
			$ext = pathinfo($file_name, PATHINFO_EXTENSION);
			$new_file_name = 'file_obj_1_'. hash('crc32',uniqid()).'.'.$ext;

			$fileDest = ABSPATH.$upload_folder_path.$new_file_name;

			move_uploaded_file($file_obj_1['tmp_name'][$k1] ,$fileDest);

			array_push($a1,  array(
				'old_file_name' => $v1,
				'new_file_name' => $new_file_name,
				'move_to_folder'=>$app_url.$upload_folder_path,
				'download_file_path'=>$app_url.$upload_folder_path.$new_file_name,
				
			));
		}
	}	
	//--->upload group files > 1 > end
	 
	//--->upload group files > 2 > start
	if(isset($_FILES['file_obj_2']))	
	{	 
		$file_obj_2 = $_FILES['file_obj_2'];	
		foreach ($file_obj_2['name'] as $k1 => $v1) 
		{
			$file_name = $v1;
			$ext = pathinfo($file_name, PATHINFO_EXTENSION);
			$new_file_name = 'file_obj_2_'. hash('crc32',uniqid()).'.'.$ext;

			$fileDest = ABSPATH.$upload_folder_path.$new_file_name;

			move_uploaded_file($file_obj_2['tmp_name'][$k1] ,$fileDest);

			array_push($a2,  array(
				'old_file_name' => $v1,
				'new_file_name' => $new_file_name,
				'move_to_folder'=>$app_url.$upload_folder_path,				
				'download_file_path'=>$app_url.$upload_folder_path.$new_file_name,
			));
		}	
	}
	//--->upload group files > 2 > end
	 
	

	echo json_encode(array(
		'user_name'=>$user_name,
		'user_email'=>$user_email,
		'file_obj_0' => $a0,
		'file_obj_1' => $a1,
		'file_obj_2' => $a2,
	));
}
?>
For Web Developers

Stop Building Websites That Pay You Once.

Use Shiply CMS to launch websites faster, manage clients easier, and turn every project into recurring monthly income.

Start Building Faster 🚀 Download Shiply CMS
Best PHP Framework For Your Web ApplicationBest PHP Framework For Your Web Application←Previous
Javascript Cookies Vs Local StorageJavascript Cookies Vs Local StorageNext→

Related Posts

  • How Google Developers Think (And Why You Should Too)
  • Add Google Sign-In in 2 Minutes
  • Form Validation in 1 Line

Top Posts Viewed

Using JavaScript Window Onload Event Correctly
66 views
How Google Developers Think (And Why You Should Too)
56 views
Learn To Create YouTube Video Downloader
55 views

Categories

Courses
Excel
Google Script
Javascript
jQuery
Microsoft Access
MongoDB
Node JS
PHP
Quick Tip
Uncategorized
Wordpress