views:

61

answers:

2

Bare with me here. New to ajax.

What I would like to do is have a basic html form the input fields be inside php so that you can fill those fields with data and submit them to a database. Once that data exists in the database I want that data to fill the input fields. I want all this to be done in java/ajax/php so my page never refreshes. But I can submit data to a MYSQL database and retrieve from it.

Example code of this would be best so I can see it and learn it.

Right now I have seen how to pull from a database and fill input with the data without page refresh. Also I have seen how to enter data into a database without the page refresh.

I can't find and example of both combined.

+1  A: 
<form onsubmit="retrieve_data(...); return false;">
 <input type="text" name="foo" id="foo"/>
 <input type="submit"/>
</form>
<div id="ajax"></div>
<script>
 function retrieve_data(...) { ... }
 function update_form(...) { ... }
</script>

retrieve_data should call php script which stores data into DB and can output some content into div id="ajax". But if you add some script, it is not executed: it needs some event to run. Therefore I suggest that your php script fills div id="ajax" with this:

<img src="..." width="0" onload="update_form()"/>

The only thing you need is to write functions retrieve_data (call php script which returns content into ajax div) and update_form, which updates your form fields. Your page should be updated without refresh. I hope it helps.

Jan Turoň
+1  A: 

Well, you're sort of asking for everything at once!

First, you'll probably be best off using jQuery to simplify the Ajax requests.

Let's set up an example database. Open the mysql command line client, and enter

mysql# create database test;
mysql# use test;
mysql# create table testpage(id int auto_increment,someval int,otherval varchar(16),primary key(id));

Here's an example HTML page. Save this in your web root as test.php:

 <html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"&gt;&lt;/script&gt;
    <script>
      $(document).ready(function(){
        $('#senddata').click(function(){
            var an_int=parseInt($('#an_int').val(),10); //reads the content of the form inputs
            var a_string=$('#a_string').val();
            $.post('process.php',{"an_int":an_int,"a_string":a_string},function(data){
              if(data.result=='error'){ $('#status').text('An error occurred sending the data'); return false; }
              $('#show_int').text(data.stored_int);
              $('#show_string').text(data.stored_string);
              $('#status').text('Stored and displayed data successfully');
              })
            });
        });
    </script>
  </head>
  </body>
    <form>
      An integer: <input type='text' length='40' id='an_int'><br>
      A word: <input type='text' length='40' id='a_string'><br>
      <div id='senddata'>Send Data</div>
    </form>
    <br>
    <div id='status'>Enter data and click send to store and update.</div>
    <br>
    The Int: <div id='show_int'></div>
    The String: <div id='show_string'></div>
  </body>
</html>

Okay, so then the PHP. Save this as process.php

<?php

$sent_string=preg_replace('#[^\w\d]#','',$_POST['a_string']); //will remove anything other than letters, _ and digits
$sent_int=(int)$_POST['an_int']; //will strip out any non digits, or set to 0 if not numeric at all

function pdo_connect($dbn='test')
{//connect, return a pdo connection object thing handle
try
  {
  $host='localhost';
  $user='root';
  $passw='yourpassword';
  $driver_opts = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8' );

  $db=new PDO("mysql:host=$host;dbname=$dbn",$user, $passw, $driver_opts);
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
catch(PDOException $err)
  {echo('Could not connect to database '.$dbn.' due to error: '.$err);return false;}

return $db;
}
$db=pdo_connect();
if(!$db){ exit; }

$sql='insert into testpage values(null,?,?)';
$insert_statement=$db->prepare($sql);

$data=array($sent_int,$sent_string);
$success=$insert_statement->execute($data);

$result=$success ? 'success' : 'error';

$result_array=array('result'=>$result,'stored_int'=>$sent_int,'stored_string'=>$sent_string);

header('Content-Type: application/json');
echo json_encode($result_array);
exit;

It's not really reading the info from the database, it's just returning what it just entered. Making a page that displays a list of the data entered so far is left as an exercise for the reader! Hope this helps.

Alex JL