Jump to content
Larry Ullman's Book Forums

Chapter 11 Contact Form


Recommended Posts

I went through the exercise for creating a simple form which, in theory, would be handled using an Ajax script that submits the form to a PHP script for mailing, and that in turn would confirm the success of the submission and reply back to the Ajax script. The mail process on the PHP side was omitted for the exercise but I decided to try to get it to work. I'm having a difficult time establishing values in the PHP script. I'll try and provide just the pertinent code without losing the focus of my question;

 

 

// Add an event handler to the form's submission:

document.getElementById('theForm').onsubmit = function() {

 

// Create the data:

var fields = ['name', 'email', 'comments'];

var data = []; // Empty array.

for (var i = 0, count = fields.length; i < count; i++) {

data.push(encodeURIComponent(fields) + '=' + encodeURIComponent(document.getElementById(fields).value));

}

 

// Open the request:

ajax.open('POST', 'resources/contact.php', true);

ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

 

// Send the request:

ajax.send(data.join('&'));

 

return false;

 

}; // End of onsubmit function.

 

as you can see, the values are appended to a string as name=value pairs and sent to the PHP script. I'm trying to isolate these values on the PHP side and include them in a mail. Do I have to parse the string and obtain the values that way or does PHP perform that automatically?

 

 

<?php

$body= $_POST['Comments'];

echo 'the value of body is...' . $body;

$email= $_POST['email'];

mail($email, 'Contact Form Submission', $body);

echo 'The message has been sent.';

?>

Link to comment
Share on other sites

The mail does not get sent, I'm not receiving values for my PHP variables but the return message IS echoed back.

For instance, I tried to see if the $body variable was receiving a value:

echo 'the value of body is...' . $body;

 

but all I receive is

 

the value of body is...

 

so the PHP variables are not receiving values. When I remove the JS function and submit the form directly from the HTML page, the mail gets sent to it's destination.

Link to comment
Share on other sites

 Share

×
×
  • Create New...