Hi, I am currently working on a project. When a user submits a form, he loads the response in a div, rather than loading a new page. I looked at other examples of the ajax form working together with PHP online, but this did not help me solve my problem. (I'm new to this).
When I click the "Send" button, instead of sending a response to the same page and sending an email to the selected email address, it leads me to a php file and repeats the response, but does not send any messages.
Can anyone see where this is happening?
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)
{
event.preventDefault();
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');
var posting = $.post( url, {
name: name_value,
email: email_value,
message: message_value
});
posting.done(function( data )
{
$( "#response" ).html(data);
});
});
</script>
PHP code: (my php is stored in a separate file called mailer.php) I am trying to return the PHP $ response variable and return to the response div.
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$to = "your-emailaddresshere@email.com";
$subject = "New DPS Email from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$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 your help!