How do I send form input data to a PHP script via AJAX
Posted: Thu Mar 15, 2012 3:14 pm
What I thought was a very simple process turned out to be a nightmare. I'm trying to asynchronously display a message on an HTML page after a value has been entered into a form field on the same page. The form input field in question is as follows:
The script below is meant to collect the value of the form input and send to a PHP form, which would then display a message in a div with id "email_error" if the input is received.
In the PHP script, I do a check to see if the form input has been received and then echo it. I also print out a dummy message below it.
Code: Select all
<input id = "input_email" type="input" name ="email" value ="" size="16" maxlength="14"/>
The script below is meant to collect the value of the form input and send to a PHP form, which would then display a message in a div with id "email_error" if the input is received.
Code: Select all
$(document).ready(function() {
//Check if email is already in database.
$("#input_email").blur(function(){
var data_string = $("#input_email").val;
//Send input asynchronously to server
$.post("check_email_input.php",{data:data_string},
function(data){
$("#email_error").html(data);
});
});
In the PHP script, I do a check to see if the form input has been received and then echo it. I also print out a dummy message below it.
Code: Select all
<?php
//address error handling
ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);
//Check if data was posted
if(isset($_POST['email'])){
$email = $_POST['email'];
echo $email;
}
//Dummy message
echo"<span>Nothing is happening</span>";
?>
The dummy message gets printed everytime, but not the data from the form. I have tried other variations like $_POST['data'] instead of $_POST['email'], $("$input_email").serialize(); instead of $("input_email").val, all to no avail. What's to be done?