Jump to content

How do I send form input data to a PHP script via AJAX


drayarms

Recommended Posts

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:

 

<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.

 

 

		$(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.

 

 

 


<?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?

This line:

 

$.post("check_email_input.php",{data:data_string}, 

 

means that you are sending a $_POST value to the server with the key 'data'.

You are trying to use the key 'email' to grab this data, obviously this will not work.

You need to use $_POST['data'] instead.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.