Friday 1 October 2010

Send Form information to PHP through jQuery

"Why would I do this?", I hear you ask. The answer is simple, by sending information through jQuery you open yourself up to losing browser refresh and a better UI. There are 2 files in this example:
The HTML file, which also contains the jQuery.
The PHP file which would do the processing.

See demo.

Let's start with the HTML file.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery and PHP Form</title>
<style type="text/css">
html, body
{
 font-family:sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$(document).ready(function()
{
    $('#sendTheData').click(function()
    {
        $.post("sendThedata.php",
        {
            myValue:$('#lname').val()
        }, function(data)
        {
    alert(data);
        });
        return false;
    });
});
</script>
</head>
<body>
<form>
  <input type="text" name="lname" id="lname" /><br />
  <input type="submit" value="Submit" id="sendTheData" />
</form>
</body>
</html>


Now for the PHP file:

<?php
  echo 'Got '.$_POST['myValue'];
?>

No comments:

Post a Comment