Previous Page

Insert into, Update, and Retrieve data from a database without refreshing the page.

Check out an example of this here


Below is the css and html on the the main page (call it whatever you want). This page contains 3 javascript functions that use ajax to request information from 3 different pages depending on which button is clicked. I'm just going to post the entire page here. I called it ajax_post_data.php

NOTE: The table(named "data") in the database only contains 2 fields. The "id" and "data_field".

<!DOCTYPE html>
<head>
<title>Post with Ajax</title>

<style type="text/css">
body{
	text-align:center;	
}
#form {
	position:relative;
	margin-left:auto;
	margin-right:auto;
	margin-top:25px;
	height: auto;
	width: 325px;
	padding:40px;
	text-align:left;
	color:#069;
		
	 box-shadow: 2px 1px 25px #000000;
    -moz-box-shadow: 2px 1px 25px #000000;
    -webkit-box-shadow: 2px 1px 25px #000000;
	
	 border-radius: 15px;
     -moz-border-radius: 15px;
     -webkit-border-radius: 15px;
     o-border-radius: 15px;
}
h1{
	color:#333;	
}
h3{
	margin-top:50px;	
}
label{
		font-size:1.5em;
		font-weight:bold;
		margin-top:10px;	
}
input{
	background-color:#CCC;
	color:#006;
	width:250px;
    height:40px;
	font-size:1.4em;
   
}

#messageInsert {
   
	margin:auto;
	height: auto;
	background:#FFC;
	width: auto;
	font-size:1.4em;
	text-align:left;
	margin-top:25px;
 
     box-shadow: 2px 1px 25px #000000;
    -moz-box-shadow: 2px 1px 25px #000000;
    -webkit-box-shadow: 2px 1px 25px #000000;
}
#message {
   
	margin:auto;
	height: auto;
	background:#FFC;
	width: auto;
	font-size:1.4em;
	text-align:left;
	margin-top:25px;
 
     box-shadow: 2px 1px 25px #000000;
    -moz-box-shadow: 2px 1px 25px #000000;
    -webkit-box-shadow: 2px 1px 25px #000000;
}

#results {
   
	margin:auto;
	height: auto;
	background:#FFC;
	width: auto;
	font-size:1.4em;
	text-align:left;
	margin-top:25px;
 
     box-shadow: 2px 1px 25px #000000;
    -moz-box-shadow: 2px 1px 25px #000000;
    -webkit-box-shadow: 2px 1px 25px #000000;
}
</style>


<!--FUNCTION TO INSERT. Request for insert.inc.php page -->
<script type="text/javascript">
function insert()
{ 
		if (window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();	
	}
	else
	{
		xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');	
	}
	
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			document.getElementById('messageInsert').innerHTML = xmlhttp.responseText;	
		}
	}	

	parameters = 'text='+document.getElementById('text').value;

	xmlhttp.open('POST', 'insert.inc.php', true);
	xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	xmlhttp.send(parameters);
}
</script>


<!--FUNCTION TO UPDATE. Request for update.inc.php page -->
<script type="text/javascript">
function update()
{ 
		if (window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();	
	}
	else
	{
		xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');	
	}
	
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			document.getElementById('message').innerHTML = xmlhttp.responseText;	
		}
	}	

	parameter1 = 'update='+document.getElementById('update').value ; // set = to the `data` you want to update the database with. - FROM THE FORM
	parameter2 = 'id='+document.getElementById('id').value;// set = to the `id` WHERE you want to replace the data - FROM THE FORM
	
	var postArray = new Array(2); // array to hold two parameters from the form. Adjust as needed
	postArray[0] = parameter1; // add first parameter to the array
	postArray[1] = parameter2; // add second parameter to the array	 

	xmlhttp.open('POST', 'update.inc.php', true);
	xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	xmlhttp.send(postArray.join("&") ); // send all parameters from the array

}
</script>


<!--FUNCTION TO GET DATA FROM DATABASE. Request for data.inc.php page -->
<script>
function getData() 
{	
	if (window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();	
	}
	else
	{
		xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');	
	}
	
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			document.getElementById('results').innerHTML = xmlhttp.responseText;	
		}
	}	
	
    parameter = 'data_id='+document.getElementById('data_id').value ;
	xmlhttp.open('POST', 'data.inc.php', true);
	xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	xmlhttp.send(parameter);
		
}	
</script>


</head>

<body>

<h3>First, insert data into the database. Keep a note of the ID so you can try it out below.</h3>
<div id="form">
<label>Insert data:</label><br />
<input type="text"  id = "text"/><br />
               <!-- id = "text" -->
<input type="button" name="insert" value="Insert" onClick="insert();" style="width:170px; height:35px;margin-top:10px;"/>
                                             <!-- call the insert() function on click -->                                       

    <div id="messageInsert"><!-- YOUR MESSAGE WILL APPEAR INSIDE HERE --></div> 

</div> 

<!----------------------------------------------------------------------------------------------------------------------->

<h3>After you see the data you entered by using entering it's id below, try to update your data.</h3>
<div id="form">                                           
<label>Updated Data: </label><br />
<input type="text" id = "update"/><br /> 
              <!-- id = "update" -->
            
<label>WHERE id = </label><br />
<input type="text" id = "id"/><br /> 
              <!-- id = "id" -->
            
<input type="button" name="update" value="Update" onClick="update();" style="width:170px; height:35px;margin-top:10px;"/>
                                             <!-- call the update() function on click -->
                                             
    <div id="message"><!-- YOUR MESSAGE WILL APPEAR INSIDE HERE --></div>
    
</div>

<h3>Type your ID in below to see what data is stored for that record.</h3>
<!----------------------------------------------------------------------------------------------------------------------->

<div id="form">        
<label>Enter the id:</label><br />
<input type="text" id="data_id" /><br />

<input type="button" name="data_id" value="Get Data" onClick="getData();" style="width:170px; height:35px;margin-top:10px;"/>
                                                <!-- call the getData() function on click -->
			

    <div id="results"><!-- YOUR MESSAGE WILL APPEAR INSIDE HERE --></div>
 
</div>	

</body>

</html>

Below is the contents of update.inc.php

<?php

//=================================================================================================
//
//	*****************ENTER THE INFORMATION HERE TO CONNECT TO YOUR DATABASE*******************
//
//=================================================================================================

	if (isset($_POST['update']) && isset($_POST['id']))
	{
		$text = $_POST['update'];
		$id = $_POST['id'];
	
		if(!empty($text) && !empty($id))
		{
			    $queryCheck = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `data` WHERE `id` = '".$id."'"));

				if($queryCheck['id']) // As long as a record exists with the id entered
				{	
                        $insertRepeat = mysql_fetch_assoc(mysql_query("SELECT `data_field` FROM `data`  WHERE `data_field` = '".$text."' "));
                    
                        if(!$insertRepeat['data_field']) // if the data entered does NOT exist already in the database. Notice the "!" before the variable.
                        {
                                $query = mysql_query("UPDATE `data`  SET `data_field` =  '".$text."' WHERE `id` = '".$id."' ");
                                
                                if($query) // As long as the database updated correctly
                                {
                                    echo '<div  style="color:green; border: 1px solid #04ef14; padding:15px;">'.'Success! Data field updated for the record with an id of '.$id.'.'.'</div>';			
                                }
                                else
                                {
                                    echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'Failed to update database'.'</div>';	
                                }
                        }
                        else
                        {
                          	    echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'Sorry! That is duplicate data. Please try again'.'</div>';	
                        }
				}
				else
				{
						echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'There is no record with that id!'.'</div>';
				}
		}
		else
		{
			echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'Please enter DATA and an ID to update the database.'.'</div>';	
		}
	}
?>

Below is the contents of insert.inc.php

<?php

//=================================================================================================
//
//	*****************ENTER THE INFORMATION HERE TO CONNECT TO YOUR DATABASE*******************
//
//=================================================================================================

	if (isset($_POST['text']))
	{
		$text = $_POST['text'];		
		
		if(!empty($text))
		{       
		        $insertRepeat = mysql_fetch_assoc(mysql_query("SELECT `data_field` FROM `data`  WHERE `data_field` = '".$text."' "));
					if(!$insertRepeat['data_field'])
					{
						$query = mysql_query("INSERT INTO `data`  VALUES ('', '".$text."')");
						$query_id = mysql_fetch_assoc(mysql_query("SELECT `id` FROM `data`  WHERE `data_field` = '".$text."' "));
									
					
						if($query)
						{
							echo '<div  style="color:green; border: 1px solid #04ef14; padding:15px;">'.'Data inserted successfully'.'</div>';
							echo 'The ID for the new data is '.$query_id['id'];	
						}
						else
						{
							echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'Failed to insert into database'.'</div>';	
						}
					}
					else
					{
						echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'Sorry! That is duplicate data. Please try again'.'</div>';	
					}
		}
		else
		{
			echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'Please enter the text you want to insert into the database.'.'</div>';	
		}
	}

?>

Below is the contents of data.inc.php

<?php

//=================================================================================================
//
//	*****************ENTER THE INFORMATION HERE TO CONNECT TO YOUR DATABASE*******************
//
//=================================================================================================

if (isset($_POST['data_id']))
{
	$data_id = $_POST['data_id'];
	
	
	if(!empty($data_id))
    {
		$query = mysql_fetch_assoc(mysql_query("SELECT `data_field` FROM `data` WHERE `id` = '".$data_id."'"));

		if($query['data_field'])
		{			
			echo '<div style="padding:15px; ;">'.$query['data_field'].'</div>';		
		}
		else
		{
			echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'There is no record with that id!'.'</div>';	
		}
	
    }
	else
	{
		echo '<div  style="color:red;  border: 1px solid #ff0000; padding:15px; background:#FFC;">'.'Please enter an id!'.'</div>';	
	}
}

?>