Tuesday, 15 July 2014

Post all form fields to PHP using jQuery

The example below simplifies the process of simply passing all HTML form data to a PHP script (or any other HTTP handler), obviously without a refresh. Below that are a couple of suggestions on how the jQuery and PHP could be improved beyond the simplified versions.
First the HTML and jQuery (in red).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Form test</title>
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
</head>
<body>
<form action="response.php" method="POST">
<input type="text" name="firstname" /><br />
<input type="text" name="lastname" /><br />
<button type="submit">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function()
{
$('form').submit(function()
{
$.post($(this).attr('action'),$(this).serialize(), function(data)
{
alert(data)
});
return false;
});
})();
</script>
</body>
</html>
Now the PHP script.
<?php
echo 'Received';
?>
We could improve the jQuery by clearing the form content thus.
$('form').submit(function()
{
thisform = $(this);
$.post($(this).attr('action'),$(this).serialize(), function(data)
{
thisform.trigger('reset'),
alert(data)
});
return false;
});
We could also use the PHP to create a MySQL call using the form array, thus.
<?php
$valueString = '';
$sqlString = '"INSERT INTO `tablename` (';
foreach($_POST as $key => $value)
{
$sqlString .= '`'.$key.'`,';
$valueString .= '\''.htmlspecialchars($value).'\',';
}
$sqlString = rtrim($sqlString,',');
$valueString = rtrim($valueString,',');
$sqlString .= ') VALUES ('.$valueString.')"';
echo 'Received';
?>
Have fun!

No comments:

Post a Comment