Friday, January 28, 2011

Php Ajax Mysql Example

<html>
<head>
   
<script src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript">
</script>

    <script type="text/javascript">
      function register(){
        alert("hi" +document.getElementById("username").value); 
        $.ajax({
            type: "POST",
            url: "/submit_data.php",
            data:     "username=" + document.getElementById("username").value + 
                    "&email=" + document.getElementById("email").value,
            success: function(html){
                $("#response").html(html);
            }
        });
    
        }
    </script>
  </head>



<body>
    <form action="" method="post">
            <p>
                <label for="name">Name:</label><br />
                <input type="text" name="username" id="username" size="25" />
            </p>
            <p>
                <label for="email">Email:</label><br />
                <input type="text" name="email" id="email" size="25" />
            </p>
            <p>
                <input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/>
            </p>
<div id="response">
        <!-- Our message will be echoed out here -->
    </div>
</form>
</body>
</html>


<?php
                $db_host = 'localhost';
                $db_user = 'root';
                $db_pass = 'root';
                $db_name = 'db';

        $Username = $_POST['username'];
        $Email    = $_POST['email'];
      
        $connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error());
        $connection = $connect;

        mysql_select_db( $db_name, $connect ) or die( mysql_error() );

     
        $qInsertUser = mysql_query(" INSERT INTO test
                                     VALUES ('$Username','$Email')
                                  ");

       if ($qInsertUser){
           echo "You are now subscribed to our newsletter. Thank you!";
        } else {
            echo "Error!";
        }

    ?>

No comments:

Post a Comment