How to: Use AJAX/FORMDATA/JSON with JQuery, then access it using PHP

In this example we will send data gathered from dynamically created elements in JSON and send them using FORMDATA and AJAX or simply JSON if FORMDATA is not allowed in the web browser. Then we will write the PHP script to proces the AJAX request and store the data in a MYSQL DB or use it however you would like. Try it HERE!

Create the HTML/PHP page to add the data to the form or array:

We'll call this file MyWebpage.html for example purposes.

	<!DOCTYPE HTML>
	<html>
		<head>
			<title>Ajax Test</title>
			<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" charset="utf-8"></script>
			<script type="text/javascript" src="Strings.js" charset="utf-8"></script>	
			<script type="text/javascript" src="MyJQ.js" charset="utf-8"></script>	
		</head>
		<body>
			<div id="container">
				<form action="AjaxCall.php" method="post" id="quizbuilder" enctype="multipart/form-data">
					<div id="quizBuilderDiv">
		
					</div>
					<div id="questionBuilderDiv">
						<p><h2>AJAX/JSON/JQuery/PHP FORMDATA:</h2></p>
						<div id="buildDiv" style="position:relative; width: 749px;">
							<p id="instruction">Add the data bellow, and click [Call Ajax] to send it to the script.</p>
						</div>
						<div id="inputList">

						</div>
						<p><input type="button" id="addData" value="Add Data" /></p>
						<p><input type="button" id="submitData" value="Submit Data" /></p>
						<p><input type="button" id="callAjax" name="callAjax" value="Ajax Call" /></p> 
					</div>
				</form>
			</div>
		</body>
	</html>			
			


Create the JQuery to send the data:

First externalize your strings in Strings.js

	//this is a strings file
	var image_alert = "Images/Files will not be available, since form data is not enabled on this browser!"
	var email_prompt = "Enter email if you would like example data sent:";
	var apend_image = "Append Image/File: ";
	var size_alert = "Images with width larger than 700px are allowed, but will be scaled down to fit size.";
	var sorry_size = "Sorry, only one image/file allowed!";
	var sorry_one_image = "Sorry, only one image/file allowed!";
	var add_more = "Would you like to add more data? Cancel to make AJAX call!";		
		

We'll call the jquery file MyJQ.js for example purposes.

	$(document).ready(function() {
		$('#submitData').hide();
		$('#callAjax').hide();
		/*global variables*/
		var myParagraph; //place holder for dynamically created elements	
		var formdata; //browser allows formdata
		var numImages = 0; //number of images for question
		var index = 0;
		var fileIndex = new Array(); //index for images of each question
		var allowImage = true; //allow only one image per question
		var noFormData = false; //formdata has been disabled
		var firstImage = true; //show message on first image
		var textID; //id to get text from
		var email; //email to send data
		text = new Array();
		
		/*determine how data will be sent through ajax call*/
		if (window.FormData) {  
			formdata = new FormData(); 
		} else {
			alert(image_alert);
			noFormData = true;
		}
		
		/* ask for email if user wants it sent */
		email = prompt(email_prompt);
		
		/*determine if images and files are allowed*/
		$('#addData').click( function() {
			$('#addData').hide();
			/*allow image to be appended*/
			if(!noFormData) {		
				allowImage = true;
			}
			
			/*add all elements to this paragraph*/
			myParagraph = document.createElement("p");		
			
			/*add image or file*/ 
			var imageDiv = document.createElement("div");	
			imageDiv.style.cssText = 'padding-bottom:10px;';	
			var imageText = document.createTextNode(apend_image);
			var labelI = document.createElement("label");
			labelI.style.cssText = 'padding-left:10px';
			var image = document.createElement("input");	
			image.setAttribute("type", "file");
			image.setAttribute("id", "images");
			image.setAttribute("name", "images[]");		
			image.setAttribute("multiple", "multiple");

			$(image).change(function() { 
				if(!noFormData) {
					if(allowImage) {
						var i = 0; 
						var len = this.files.length;
						var	img;
						var reader;
						var file;					
						if(firstImage) {
							alert(size_alert);
							firstImage = false;
						}
						if(len>1) {
							alert(sorry_size);
							return;
						}
						for ( ; i < len; i++ ) {  
							file = this.files[i];  
							if (!!file.type.match(/image.*/)) {  
							}  
						}
						if ( window.FileReader ) { 
							reader = new FileReader();  
							reader.readAsDataURL(file);  
						}
						if (formdata) {  
							formdata.append("images[]", file);
							fileIndex[numImages] = index;
							numImages++;
						}
						allowImage = false;
					} else {
						alert(sorry_one_image);
					}
				}	
			});
			labelI.appendChild(imageText);
			imageDiv.appendChild(labelI); 
			imageDiv.appendChild(image); 
			myParagraph.appendChild(imageDiv);		
			
			/*add text data*/
			textID = "text_"+index;
			var textDiv = document.createElement("div");
			textDiv.style.cssText = 'padding-top:10px; padding-bottom:20px;';			
			var textH = document.createElement("p");			
			var textForData = document.createTextNode("Text: "); 
			var spanH = document.createElement("span");	
			var spanPH = document.createElement("p");		
			spanH.style.cssText = 'font-size: 115%;';
			spanH.appendChild(textForData);
			var textInput = document.createElement("textarea");
			textInput.setAttribute("id", textID);
			textInput.setAttribute("rows", "2");
			textInput.setAttribute("cols", "73");		
			textInput.style.cssText = 'margin-left: 50px; padding-bottom:20px; margin-top:10px; border:1px solid #004080;';			
			spanPH.appendChild(spanH); 
			textH.appendChild(spanPH); 		
			textH.appendChild(textInput);
			textDiv.appendChild(textH);
			myParagraph.appendChild(textDiv); 		
			document.getElementById("inputList").appendChild(myParagraph);		
			$('#submitData').show();
			return false;
		});
		
		
		/*only way to clear image text for all browsers*/
		$('#clickImage').click( function() {	
			$('#images').trigger('click');
			document.getElementById('inputField').setAttribute('type', 'input');
			document.getElementById('inputField').setAttribute('type', 'file');		
		});	
		
	 
		/*determine whether to send data with ajax call to php script or continue to add data to FORMDATA*/
		$('#submitData').click(function() {		

			text[index] = $('#'+textID).val();	
			index++;
			
			document.getElementById("inputList").removeChild(myParagraph);

			var r=confirm(add_more);
			if (r==true) {
				$('#addData').show();
				$('#submitData').hide();
			} else {
				$('#submitData').hide();
				$('#callAjax').show();
			}		
			return false;
		});
		
		
		/*send the data to the delegate(my crazy ajax call)*/
		$('#callAjax').click( function() {			
			if(!noFormData) {
				/*use JSON's stringify*/
				text = JSON.stringify(text);
				email = JSON.stringify(email);
				fileIndex = JSON.stringify(fileIndex);
				
				/*append the data*/
				formdata.append("email",email);
				formdata.append("exampleInfo", text);	
				formdata.append("fileIndex", fileIndex);

				/*make the ajax call*/
				$.ajax({
					url: "AjaxCall.php",
					type: "POST",				
					data: formdata,
					contentType: false,
					processData: false,				
					success: function(msg){
						alert(text+"\n"+fileIndex+"\n"+msg);
						window.location.href = "../../../main/howto.php";						
					},
					error: function() {
						alert("failure");
					}
				});
			} else {
				/*no formdata so just send*/
				email = JSON.stringify(email);
				text = JSON.stringify(text);

				/*make the ajax call*/
				$.ajax({
					url: "AjaxCall.php",
					type: "POST",				
					data: 	{	
						email : email,
						exampleInfo : text 
					},		
					success: function(msg){
						alert(text+"\n"+msg);
						window.location.href = "../../../main/howto.php";						
					},
					error: function() {
						alert("failure");
					}
				});		
			}	
		}); 
		
	});
			

Create the PHP to handle the AJAX call in AjaxCall.php:

	<?php
		//variables
		$email = json_decode(stripslashes($_POST['email']), true);
		$exampleInfo = json_decode(stripslashes($_POST['exampleInfo']), true);    
		$fileIndex = json_decode(stripslashes($_POST['fileIndex']), true);  	
		$num = 0;
		$numfiles = 0;	
		$imageName = "";
		$data = "";
		
		//quiz table
		if($exampleInfo != null) {
			//insert them into the DB or use them how it best suits your needs
			
			if($_FILES) { //images/files were added
				foreach ($exampleInfo as $info) {		
					if($fileIndex[$numfiles] == $num) {	//there's an image/file with this info
						//move_uploaded_file( $_FILES["images"]["tmp_name"][$numfiles], "SOMEDIRECTORY/" . $_FILES['images']['name'][$numfiles]);
						$imageName =  $_FILES["images"]["name"][$numfiles];	
						$numfiles++;	
					} else { //there's no image for this info
						$imageName = "";
					}
					$data = $info."\n";
					$num++;					
				}
			} else { //no images added to the submission
				foreach ($exampleInfo as $info) {
					//do something with the info
					$data = $info."\n";
					$num++;	
				}
			}

			//mail the results if requested
			if($email != null) {
				$subject = "franksthinktank ajax howto response";
				$headers = "From: franksthinktank.com";
				mail($email,$subject,$data,$headers);
			}  		
		}
		
	?>