4

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!

8
  • Have you looked in the broswer's console for errors? Commented Dec 16, 2015 at 15:44
  • You have the var url in you $.post. Silly question but I guess elsewhere in your code that is set to the url of your php script Commented Dec 16, 2015 at 15:48
  • @Y.Hermes I have tried that and unfortunately it doesn't seem to change the outcome Commented Dec 16, 2015 at 15:52
  • @IWebb I'm not sure if it is actually working correctly, but it should be taking the url of the php script from the action variable on the form. I have just realised that hasn't been included in my post, will update it now Commented Dec 16, 2015 at 15:53
  • I know this site is about a JQuery plugin but there is a good section on how to debug ajax requests in chrome. datatables.net/manual/tech-notes/7 the Diagnosis bit is the interesting bit works for all ajax requests Commented Dec 16, 2015 at 16:04

4 Answers 4

2

correct this and report what happened,

your form ID is "contact-form" and your JQ selector have been set for "contactform".

$("#contactform")

to

$("#contact-form")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, that seems to have been the answer for getting it to post to the div! It's always a typo! For some reason it still isn't sending the email though :S
1

Here is what you can do: The Form Code

<form name="contactform" id="contact-form">
    <!--Your form elements here -->
</form>

The javascript code (Use #contact-form and not #contactform)

<script>
$("#contact-form").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 = 'your_url_here';

 /* Send the data using post */
 var posting = $.post( url, { 
                   name: name_value, 
                   email: email_value, 
                   message: message_value 
               });

 posting.done(function( data )
 {
     /* Parse JSON */
     var response = JSON.parse(data);
     $("#response").html(response.msg);

    });
 });
</script>

Your PHP Code :

<?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( $mailed )
$response = json_encode(array("status"=>true,"msg"=>"<h2>Thank You! Your message has been sent.</h2>"));
else
$response = json_encode(array("status"=>false,"msg"=>"<h2>Oops! Something went wrong and we couldn't send your message.</h2>"));

echo $response; 

?>

2 Comments

Thanks so much! This is laid better than my original code and it encodes and decodes the message then posts it to the array. Only issue I'm still having is, getting the email to actually send. Although I am wondering whether this is due to me using cloud 9 ide
Welcome @HipHipArray . For the mail issue, you can check that with your hosting provider
0

It is because you're calling post function, not ajax.

try this:

$.ajax({
   url: <your_url>,
   type:'GET',
   data: {'name': name_value, 'email' : email_value, 'message': message_value},
   success: function(data){
        yourdivcontent =  eval(data)
        $( "#response" ).html(yourdivcontent);
   }, 
   error: function(){
        console.log("error");
   }
})

In your php function, just encode your response in json

return json_encode(response);

4 Comments

Thanks for your comment, for whatever reason I am getting an error saying "unexpected token :" on this line "data: {'name': name_value, 'email' : email_value, 'message': message_value}," Also I'm assuming the part where you have put yourdivcontent, this needs to be replaced by the variable which I am passing back from the php mailer script? Finally, if am I am JSON_encoding, do I need to decode? Sorry about all the questions, I am just quite new to this and trying to understand what each part is doing
I forgot to add the 'type' value on the ajax call.. I edited my answer. And yes, you have to put your variable into your div. the data is going to return you an json string
For some reason it keeps giving me that unexpected token error. Any ideas as to what may be causing that? Thanks in advance
try to unquote the data line, like this data: { name: name_value, and so on }
0

echo json_encode($response) at end of php function

1 Comment

unfortunately this just echos it on the php page still

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.