Sharivari
Sharivari

Reputation: 103

Submitting Contact Form with AJAX

I have a contact form, which I want to submit with AJAX, because I want the echo Messages from the PHP file to show directly under my contact form.

Thats what i got:

form.php

<form id="ContactForm" action="contact.php" method="POST" enctype="text">
    <table class="contact-form">
        <tr>
            <td>Name<font color="#d25911">*</font></td>
            <td>
                <input type="text" id="betreff" name="betreff" placeholder="Betreff" size="45"/>
                <input type="text" id="name" name="name" placeholder="Max Mustermann" size="45"/>                            
            </td>
        </tr> 
        <tr>
            <td>E-Mail<font color="#d25911">*</font></td>
            <td><input type="text" id="email" name="email" placeholder="[email protected]" value="" size="45"/></td>
        </tr>
        <tr>    
            <td>Telefon:</td>
            <td><input type="text" id="telefon" name="telefon" placeholder="Optional" size="45"/></td>
        </tr> 
        <tr>
            <td>Nachricht<font color="#d25911">*</font></td>
            <td>
                <textarea id="nachricht2" name="nachricht2" placeholder="Ihre Nachricht"></textarea>
                <textarea id="nachricht1" name="nachricht1" placeholder="Ihre Nachricht"></textarea>
            </td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <center>
                    <input type="submit" value="Senden" id="submit" name ="submit">
                    <!--<input type="reset" value="Leeren" id="reset" name ="reset">-->
                </center>
            </td>
        </tr>
        <tr>
            <td><div id="result"></div></td>    
        </tr>
    </table>
</form>

The script, that is placed inside form.php

/* attach a submit handler to the form */
$("#ContactForm").submit(function(event) {

    /* stop form from submitting normally */
    event.preventDefault();

    /* get some values from elements on the page: */
    var $form = $(this),
    a_betreff = $form.find('input[name="betreff"]').val(),
       a_name = $form.find('input[name="name"]').val(),
      a_email = $form.find('input[name="email"]').val(),
    a_telefon = $form.find('input[name="telefon"]').val(),
    a_nachricht2 = $form.find('textarea[name="nachricht2"]').val(),
    a_nachricht1 = $form.find('textarea[name="nachricht1"]').val(),
                    url = $form.attr('action');

    /* Send the data using post */
    var posting = $.post(url, {
        betreff: a_betreff,
        name: a_name,
        email: a_email,
        telefon: a_telefon,
        nachricht2: a_nachricht2,
        nachricht1: a_nachricht1,
    });

    /* Put the results in a div */
    posting.done(function(data) {
        var content = $(data).find('#content');
        $("#result").empty().append(content);
    });
});

And this is my contact.php

<?

// Assure that only via contact-form executable
if(!isset($_POST["submit"])){   
    exit;
}

// Returns true, if E-Mail is valid
function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

// Initialize Variables
$name = addslashes(htmlspecialchars($_POST["name"]));
$email = addslashes(htmlspecialchars($_POST["email"]));
$telefon = addslashes(htmlspecialchars($_POST["telefon"]));
$telefon = strtolower($telefon);
$nachricht2 = addslashes(htmlspecialchars($_POST["nachricht2"]));

$betreff = addslashes(htmlspecialchars($_POST["betreff"]));
$nachricht1 = addslashes(htmlspecialchars($_POST["nachricht1"]));

// Check if chatbot filled this input fields
if(($betreff != "") OR ($nachricht1 != "")){
    exit;
}

// Check if all required fields are field
if($name == ""){
    echo "Bitte Namen eingeben.";
    exit;
}

if($email == ""){
    echo "Bitte E-Mail eingeben.";
    exit;
}

if($nachricht2 == ""){
    echo "Bitte Nachricht eingeben.";
    exit;
}


$number = "/[0123456789]/";
if(preg_match($number, $name)) {
    echo "Der angegebene Name ist ung&uuml;ltig.";
    exit;
}

$digit = "/[a-z]/";
if(preg_match($digit, $telefon)) {
    echo "Die angegebene Telefonnummer ist ung&uuml;ltig.";
    exit;
}

if(!isValidEmail($email)){
    echo "Die angegebene E-Mail Adresse ist ung&uuml;ltig.";
    exit;
}

$message = "Guten Tag,\n\n";
$message .= "das Kontaktformular wurde am ".date("d.m.Y")." um ".date("H:i:s")." von:\n\nName: ".$name."\n";
$message .= "E-Mail: ".$email."\n";

if($telefon != ""){
    $message .= "Telefon: ".$telefon."\n";
}

$message .= "\nverwendet.\n\n";
$message .= "Die Nachricht lautet:\n'".$nachricht2."'";

if(mail("[email protected]", "Nutzung des Kontaktformulars", $message)){
    echo "Vielen Dank f&uuml;r Ihre Nachricht. Sie werden in den n&auml;chsten Tagen eine Antwort erhalten.";
} else {
    echo "Es ist ein unerwarteter Fehler beim Versenden der E-Mail aufgetreten.";
}


?>

Well.. this does right now absolutely nothing, and I dont know why. Can somebody tell me what exactly I need to fix because obviously I don't see it.

Upvotes: 0

Views: 123

Answers (1)

Cedric Ipkiss
Cedric Ipkiss

Reputation: 6337

Now here is a problem:

posting.done(function(data) {
  var content = $(data).find('#content');
  $("#result").empty().append(content);
});

Problem because you are passing the returned data as a jQuery selector string. Selector strings reference the existing DOM. So my guess is you want to do something like:

$("#result").empty().append(data);

Or if you are thinking of capturing a specific element from your returned string, try returning it either as JSON or XML, or use the parseHTML() method.

Edit

That was Error number 1. Error number 2 is in your PHP file. You did:

if(!isset($_POST["submit"])){   
    exit;
}

Now you are submitting as AJAX, and you are actually submitting name-value pairs to your PHP script, not the form itself, so the submit button is not carried alongside your form. Take off that block of code.

Error Number 3 is the returned data. It is automatically interpreted by jQuery as HTML, and if you check your console after submitting the form, you will see Syntax Error: Unrecognized expression ... + whatever your PHP script echoed. To solve this, either take off this line:

var content = $(data).find('#content');

or use the parseHTML() method I mentioned above:

var content = $($.parseHTML(data)).find('#content');

However, taking it off completely should be the best solution, because I don't really see its use there, given errors are actually echoed from your PHP script as plain strings and not HTML.

Upvotes: 2

Related Questions