Hi I am currently working on a project. When a user submits a form, it loads a response into a div rather than loading a new page. I have looked at other examples of an ajax form working along with PHP online but it didn't help me solving my problem. (I am rather new to this).
When I click submit, instead of posting the response onto the same page and sending an email to the chosen email address, it takes me to the php file and echo the response there, but does not send any email.
Can anyone see where this is going wrong?
Form code:
<form name="contactform" id="contact-form" action="mailer.php">
<input type="text" class="textbox" name="name" value="Name" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">
<input type="text" class="textbox" name="email" value="Email" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}">
<textarea name="message" value="Message:" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message</textarea>
<input type="submit" value="Send Now">
</form>
<div id="response"></div>
Javascript code:
<script>
$("#contactform").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
name_value = $form.find( 'input[name="name"]' ).val(),
email_value = $form.find( 'input[name="email"]' ).val(),
message_value = $form.find( 'textarea[name="message"]' ).val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post( url, {
name: name_value,
email: email_value,
message: message_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#response" ).html(data);
});
});
</script>
PHP code: (my php is stored in a seperate file called mailer.php) I am trying to get the PHP $response variable to be posted back and placed into the response div.
<?php
// Get the form fields and remove whitespace.
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$to = "[email protected]";
$subject = "New DPS Email from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
$mailed = (mail($to, $subject, $email_content, $email_headers));
if( isset($_POST['ajax']) )
$response = ($mailed) ? "1" : "0";
else
$response = ($mailed) ? "<h2>Thank You! Your message has been sent.</h2>" : "<h2>Oops! Something went wrong and we couldn't send your message.</h2>";
echo $response;
?>
Thanks in advance for any help!