2

I have a very simple form, containing a textbox and a submit button. When the user enters something into the form, then clicks submit, I would like to use PHP and Ajax (with jQuery) to insert the result of the form into a MySQL database. this result should be displayed on the same page in the form of a table which is updated after every insert.

Can anyone please help?

The code I have used that isn’t working:

ajax.html:

<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!

 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.value = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "&name=" +name+ "&age=" + age ;
 queryString +=  "&wpm=" + wpm + "&sex=" + sex;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='name' /><br/>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' 
                              value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

ajax-example.php:

<?php
$dbhost = "localhost";
$dbuser = "demo";
$dbpass = "demo";
$dbname = "test_db";
    //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
    //Select Database
mysql_select_db($test_db) or die(mysql_error());
    // Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
    // Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
    //build query
$query = "INSERT INTO form2 (name,age,sex,wpm) VALUES ('$name','$age','$sex','$wpm')";;


mysql_select_db('test_db');

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}

    //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
$result1=mysql_query("SELECT * FROM form2 WHERE name='$name'"); 
while($row = mysql_fetch_array($result1))
{
    $display_string .= "<tr>";
    $display_string .= "<td>$row[name]</td>";
    $display_string .= "<td>$row[age]</td>";
    $display_string .= "<td>$row[sex]</td>";
    $display_string .= "<td>$row[wpm]</td>";
    $display_string .= "</tr>";

}

$display_string .= "</table>";
echo $display_string;
?>
2
  • What have you tried? Jan 10, 2012 at 10:03
  • i have used php to accept and retrieve data from db. the data is displayed on the next page. i wanted data to be displayed on the same page
    – prit2192
    Jan 10, 2012 at 10:54

2 Answers 2

1
$("button_id").click(function () {
    $.ajax({
        url:"where you should post the data",
        type: "POST",  
        data: the string you should post,  
        success: function (result) {
            //display your result in some DOM element
        }
    });
});

When you receive the data in the php script make query to the database and get your result

hope this would help

0

There are many tutorials available on internet for ajax with PHP and Jquery. You can go through any of these and get the desired result.

See an example here http://www.tutorialspoint.com/ajax/ajax_database.htm

5
  • it retrieves the results from db. what changes are to be made if i want to insert into db and then retrieve?
    – prit2192
    Jan 10, 2012 at 10:50
  • Replace the 'select' query with 'Insert' query. See this example woork.blogspot.com/2007/10/… Jan 10, 2012 at 11:07
  • its not working. database isnt getting updated after submitting the from. infact nothing happens on pressing submit
    – prit2192
    Jan 10, 2012 at 11:48
  • code ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } We dont have a value attribute for a div. You need to use innerHTML attribute. Jan 11, 2012 at 8:58
  • And your query string is wrong. code var queryString = "?name=" +name+ "&age=" + age ; queryString += "&wpm=" + wpm + "&sex=" + sex; ajaxRequest.open("GET", "ajax-example.php" + queryString, true); you need to replace the first '&' with a '?'. Jan 11, 2012 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.