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.

			<title>Ajax Test</title>
			<script type="text/javascript" src="" 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>	
			<div id="container">
				<form action="AjaxCall.php" method="post" id="quizbuilder" enctype="multipart/form-data">
					<div id="quizBuilderDiv">
					<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 id="inputList">

						<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> 

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() {
		/*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 {
			noFormData = true;
		/* ask for email if user wants it sent */
		email = prompt(email_prompt);
		/*determine if images and files are allowed*/
		$('#addData').click( function() {
			/*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"); = 'padding-bottom:10px;';	
			var imageText = document.createTextNode(apend_image);
			var labelI = document.createElement("label"); = '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) {
							firstImage = false;
						if(len>1) {
						for ( ; i < len; i++ ) {  
							file = this.files[i];  
							if (!!file.type.match(/image.*/)) {  
						if ( window.FileReader ) { 
							reader = new FileReader();  
						if (formdata) {  
							formdata.append("images[]", file);
							fileIndex[numImages] = index;
						allowImage = false;
					} else {
			/*add text data*/
			textID = "text_"+index;
			var textDiv = document.createElement("div"); = '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"); = 'font-size: 115%;';
			var textInput = document.createElement("textarea");
			textInput.setAttribute("id", textID);
			textInput.setAttribute("rows", "2");
			textInput.setAttribute("cols", "73"); = 'margin-left: 50px; padding-bottom:20px; margin-top:10px; border:1px solid #004080;';			
			return false;
		/*only way to clear image text for all browsers*/
		$('#clickImage').click( function() {	
			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();	

			var r=confirm(add_more);
			if (r==true) {
			} else {
			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("exampleInfo", text);	
				formdata.append("fileIndex", fileIndex);

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

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

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

		$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];	
					} else { //there's no image for this info
						$imageName = "";
					$data = $info."\n";
			} else { //no images added to the submission
				foreach ($exampleInfo as $info) {
					//do something with the info
					$data = $info."\n";

			//mail the results if requested
			if($email != null) {
				$subject = "franksthinktank ajax howto response";
				$headers = "From:";