1

The form on my website is a simple contact form. I would like the form to show a "success & failed" message on the same page when the form is sent/failed without reloading the page. I understand that I should use Ajax to do this but I can't get it to work because my knowledge about it is very little.

Here is the code I'm working with.

Html (single page design):

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>

<form class="form" id="contactus" action="" method="post" accept-charset="UTF-8">




                        <label for="nametag">Namn<FONT COLOR="#FF0060">*</FONT></label>

                        <input name="name" type="text" id="name"  value="" />




                        <label for="emailtag">Email<FONT COLOR="#FF0060">*</FONT></label>

                        <input name="email" type="text" id="email"  value="" />


                        <label for="phonetag">Telefon</label>

                        <input name="phone" type="text" id="phone"  value="" />


                        <label for="messagetag">Meddelande<FONT COLOR="#FF0060">*</FONT></label></br>

                        <textarea name="message" id="message" style="width: 87%; height: 200px;"></textarea>






<label class="placeholder">&nbsp;</label>

                        <button class="submit" name="submit">Skicka</button>



                </form> 



<script>        
    $(function() {
            $('#contactus').submit(function (event) {
                event.preventDefault();
                event.returnValue = false;
                $.ajax({
                    type: 'POST',
                    url: 'php/mail.php',
                    data: $('#contactus').serialize(),
                    success: function(res) {alert(res);
                        if (res == 'successful') {
                            $('#status').html('Sent').slideDown();
                        }
                        else {
                            $('#status').html('Failed').slideDown();
                        } 
                    },
                    error: function () {
                        $('#status').html('Failed').slideDown();
                    }
                });
            });
        });
    </script>   

Php:

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient = "info@mydomain.com";
    $subject = "Webbkontakt";
    $formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";

    $headers = "From: " ."CAMAXON<info@mydomain.com>" . "\r\n";
    $headers .= "Reply-To: ". "no-reply@mydomain.com" . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=utf-8\r\n";

    if(mail($recipient, $subject, $formcontent, $headers))
    {
        echo "successful";
    }
    else
    {
        echo "error";
    }
?>
user2566091
  • 13
  • 1
  • 1
  • 7
  • ajaax uses http status codes to determine success/failure. If you want to trigger the 'error:' path in your ajax code, you'll have to return a 4xx or 5xx http status code. Right now you're outputting a `200 OK` with no body, or (still) a 200 OK, with body "Ett fell uppstod". neither of those look like a failure to the ajax system. – Marc B Jul 11 '13 at 15:41
  • in the php script `echo 'successful';` to satisfy `if (data == 'successful')` – Waygood Jul 11 '13 at 15:42
  • Could you give me a code back? I understand that I'm doing it wrong but I don't know how to fix it and my knowledge about php & ajax is very poor, so I don't really understand :( – user2566091 Jul 11 '13 at 15:46
  • 2
    note: you are only sending 1 value - `data: {email: $('form input[type=email]').val()},`, but expecting 4 -`$name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message'];` – Sean Jul 11 '13 at 15:47
  • yes Sean is right, you are sending only email. Send all data for successful execution. And also echo success or failure for getting response. – Nitesh Mishra Jul 11 '13 at 15:52

5 Answers5

3

Your Ajax call is not working properly. Try this

$(function() {
            $('#contactus').submit(function (event) {
                event.preventDefault();
                event.returnValue = false;
                $.ajax({
                    type: 'POST',
                    url: 'php/mail.php',
                    data: $('#contactus').serialize(),
                    success: function(res) {
                        if (res == 'successful') {
                            $('#status').html('Sent').slideDown();
                        }
                        else {
                            $('#status').html('Failed').slideDown();
                        } 
                    },
                    error: function () {
                        $('#status').html('Failed').slideDown();
                    }
                });
            });
        });

Also as you can see i have used $('#contactus').serialize() this way you dont need to pass the form elements one by one instead serialize() will pass the whole form elements to your php page

Than in your php file echo successful if everything went well else echo error if the response is an error than show the error div

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient = "info@mydomain.com";
    $subject = "Webbkontakt";
    $formcontent = "Från: $name <br/> Email: $email <br/> Telefon: $phone <br/> Meddelande: $message";

    $headers = "From: " ."CAMAXON<info@mydomain.com>" . "\r\n";
    $headers .= "Reply-To: ". "no-reply@mydomain.com" . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    if(mail($recipient, $subject, $formcontent, $headers))
    {
        echo "successful";
    }
    else
    {
        echo "error";
    }
?>
Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63
1

Change your PHP script like this:

<?php
if( isset( $_POST['submit'] )){ //checking if form was submitted
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$formcontent="Meddelande: \n\n $message";
$recipient = "info@mydomain.com";
$subject = "Webbkontakt";
$mailheader = "Från: $name \n Email: $email \n Telefon: $phone \r\n";

$mailsent = mail($recipient, $subject, $formcontent, $mailheader);

if($mailsent) echo "Success"; //success if mail was sent
else echo "Ett fel uppstod!";
}
?>
1

Below your mail() function, simply do echo "successful";

Rob W
  • 9,134
  • 1
  • 30
  • 50
1

2020 Edit

In REST API response should be always accompanied by the correct HTTP status code, with 200+ telling client that request ended up correctly processed or was otherwise good, 400+ telling client there was an error in request, and 500+ that there was a problem with the server itself. Do not use statuses inside responses, it is unnecessary duplication of the existing feature:

http_response_code(200);
echo json_encode(['message' => 'Email was sent']);

exit;

Then you can handle request and response with jQuery(assuming that you still use jQuery):

$.ajax({
  url: url,
  data: data,
  dataType: 'json'
})
  .then(function (data, textStatus, jqXHR) {
    // Your 200+ responses will land here
  })
  .fail(function (jqXHR, textStatus, errorThrown) {
    // Your 400+ responses will be caught by this handler
  });
;

If you need specific status, you can get it from jqXHR parameter using jqXHR.status field.

Original answer

You can use dataType: 'json' in your ajax call.

Then you'll be able to pass status code as response key:

// form response array, consider it was success
$response = array( 'success'=> 'ok', 'message' => 'Email was sent');

echo json_encode($response);

In js then you can check data.success === 'ok' to know what's your status.

baldrs
  • 2,132
  • 25
  • 34
0

In your php script you could try this

if(mail($recipient, $subject, $formcontent, $mailheaders))
{
  echo("Mail Sent Successfully"); // or echo(successful) in your case
}else{
  echo("Mail Not Sent"); // or die("Ett fel uppstod!");

}
curious_coder
  • 2,392
  • 4
  • 25
  • 44