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

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:

[php]

[/php]

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.

[php]
$(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);

						});


			});

[/php]

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]

<?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"Nothing is happening"; ?>

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?

[/php]

This line:

Must be inside a form to mean anything… I assume it is along with other items…
In the Java, you must POST the form to send it anywhere. You do that with a “post()”…
Do some research on posting forms and that will give you the answer…

Here is a page that might explain it for you: http://api.jquery.com/jQuery.post/

Good luck

Also need to have an event in the submit button, so that it knows what’s supposed to happen. something like onclick="ajaxFunction();

I kinda do the samething in a support script that i made.

and this is the script

[code][/code]

@erniealex, the line you pointed out is actually nested within a form. i just didn’t see any need to include the entire form. also, im not trying to submit the whole form, just validate one form input and i want this to be triggered by the blur event.

I don’t think you can nest forms, at least i’ve never gotten it to work.

@richei, i actually meant it is part of a form. maybe my choice of words wasn’t the best.
@erniealex, well it works now. $_POST[‘data’] works. I now know why I couldn’t get it to work before. It’s because I was using val instead of val()

Glad you figured it out! Sometimes it is hard to debug someone else’s code only seeing part of it…

Always a nice feeling to locate the buggy code...  CYA in the bitstream...
Sponsor our Newsletter | Privacy Policy | Terms of Service