[Tutorial JS] Formular simplu de contact - PHP + jQuery

#1
Nume Tutorial: Formular simplu de contact - PHP + jQuery = Ajax
Descriere: Formular simplu de contact - PHP + jQuery = Ajax
Download:
Autor: Anonim
Sursa (Link-ul oficial):
tutorialeonline
Propria parere: Folositor.
Tutorialul:

Codul este destul de lung, daca aveti erori sau probleme cu el lasati mesaj aici in comentarii sau in forum.

Cod: Selectaţi tot

<?php

// print_r($_POST);
        /* => vom avea (
        [sendForm] => true
        [_name] =>
        [_mail] =>
        [_phone] =>
        [_address] =>
        [_comments] =>
        [_find_0] =>
        [_find_1] => false
        [_find_2] => false
        [_find_3] => false
        [_find_4] => false
        ) */

// verificam daca s-a trimis POST-ul
        if(isset($_POST['sendForm']) && $_POST['sendForm']) {

 // presupunem ca totul este OK, fara nicio eroare
        $out = array(
        'error'=>false, 'done'=>'Formularul a fost trimis cu succes'
        );

 // incepem si verificam - campurile obligatorii
        $required = array('_name', '_mail', '_comments');
        foreach($required as $field) {
        if(!isset($_POST[$field]) || empty($_POST[$field])) {
        // daca unul din campuri nu e setat, facem DIE
        $out['error'] = 'Nu ai completat unul din campurile obligatorii, marcate cu steluta (*)';
        die(json_encode($out));
        }
        }

 // verificam adresa de e-mail
        if(false == preg_match('/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/', $_POST['_mail'])) {
        $out['error'] = 'Adresa de e-mail nu are format valid.';
        die(json_encode($out));
        }

 // facem un array cu checkbox-urile functie de potrivirea cheii
        $textNeAtiGasitIn = array();
        foreach($_POST as $f=>$v) {
        // daca avem 'ne-ati gasit in' si a fost bifat ( nu e gol sau false )
        if( strpos($f, '_find_') === 0 && $v ) {
        $textNeAtiGasitIn[] = $v;
        }
        }

 // o scurtatura la functia htmlspecialchars
        function h($w) { return htmlspecialchars(trim($w)); }

 // sa facem un mesaj pentru e-mail care sa arate bine
        $finalToSend = '
        Numele: '.h($_POST['_name']).'<br />
        Adresa de e-mail: '.h($_POST['_mail']).'<br />
        Numarul de telefon: '.h($_POST['_phone']).'<br />
        Adresa de acasa: '.h($_POST['_address']).'<br />
        Comentarii: '.h($_POST['_comments']).'<br />
        Ne-ati gasit in: '.implode(', ', $textNeAtiGasitIn).'<br />
        Adresa IP: '.$_SERVER['REMOTE_ADDR'].'<br />
        Data: '.date('d M Y, H:i').'
        ';

 // ca si test, sa vedem cum se trimite
        # die($finalToSend); // verifica in firebug

 // pregatim headerele de e-mail
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $headers .= 'To: '.h($_POST['_mail']) . "\r\n";
        $headers .= 'From: website.com <admin@website.com>' . "\r\n";
        # $headers .= 'Cc: ccAddress@example.com' . "\r\n";
        # $headers .= 'Bcc: blindccAddr@example.com' . "\r\n";

 // daca mail-ul nu se trimite, anuntam user-ul cu eroare
        if(false == @mail( 'admin@website.com' , 'Contact website', $finalToSend, $headers)) {
        // Asigura-te ca ai server de e-mail si acesta e OK.
        // de obicei pe localhost nu ai, decat daca-ti instalezi + configurezi
        $out['error'] = 'Mail-ul nu a putut fi trimis. Incercati mai tarziu.';
        }

 die(json_encode($out));
        }
        ?>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
    <title>Simple PHP AJAX jQuery contact form</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    <script type="text/javascript">
        function sendForm() {
        // e bine sa definim variabile (e recomandat)
        var fakeSubmitForm = $('#submitForm_fake');
        var SubmitForm = $('#submitForm');

 // prima data, inainte de request
        // afiseaza butonul fals si ascunde-l pe cel cu actiune
        fakeSubmitForm.show();
        SubmitForm.hide();

 // compune request-ul
        POST_TO_SEND = {
        sendForm:true,
        _name:$('#name').val(),
        _mail:$('#mail').val(),
        _phone:$('#phone').val(),
        _address:$('#address').val(),
        _comments:$('#comments').val()
        };
        // verificam FIECARE checkbox
        // daca vrei un alt set de checkbox-uri, mai poti face
        // un 'each' de genul asta, doar schimband clasa ( .ckFind )
        $('.ckFind').each(function(){
        var ths = $(this);
        // aici se adauga _[ID] = ( valoare DOAR daca checkbox-ul e bifat altfel FALSE )
        POST_TO_SEND['_'+ths.attr('id')] = ths.is(':checked') ? ths.val() : false;
        });
        // la final vom avea valoarea in POST a tuturor ID-urilor asa cum ne dorim
        // console.log(POST_TO_SEND); // javascript test - ai nevoie de firebug

 // make the _POST
        $.post('<?php echo basename(__FILE__) ?>', POST_TO_SEND, function(data) {
        // if we have errors
        if(data.error != false) {
        $('#errorDiv').html(data.error).slideDown();
        fakeSubmitForm.hide();
        SubmitForm.show();
        // else, no erors
        } else {
        $('#errorDiv').hide();
        $('#noticeDiv').html(data.done).slideDown();
        // ascundem si butonul fals
        fakeSubmitForm.hide();
        }
        }, 'json');
        return false;
        }
    </script>
    <style type="text/css">
        #contactForm { width:300px; margin:0 auto; padding:30p 0; }
        #contactForm * { margin:0; padding:0; outline:none; font:12px Arial, sans-serif; }
        #contactForm p { padding:5px 0; }
        #contactForm p .tf,
        #contactForm p .ta { padding:3px; width:250px; }
        #contactForm p .ta { height:100px; }
        #errorDiv { display:none; color:#c00; background:#fee; border:1px solid #c99; padding:10px; }
        #noticeDiv { display:none; color:#090; background:#efc; border:1px solid #9c0; padding:10px; }
        #submitForm_fake { display:none }
    </style>
    </head>

<body>

<div id="contactForm">
    <div id="noticeDiv">&nbsp;</div>
    <div id="errorDiv">&nbsp;</div>
    <p><label>Name *<br /><input type="text" name="name" id="name" /></label></p>
    <p><label>E-Mail address *<br /><input type="text" name="mail" id="mail" /></label></p>
    <p><label>Phone number<br /><input type="text" name="phone" id="phone" /></label></p>
    <p><label>Home address<br /><input type="text" name="address" id="address" /></label></p>
    <p><label>Comments *<br /><textarea name="comments" id="comments" cols="1" rows="1"></textarea></label></p>
    <p>Where did you find us<br />
    <label><input type="checkbox" name="find0" id="find_0" value="" checked="checked" /> can't remember</label><br />
    <label><input type="checkbox" name="find1" id="find_1" value="google" /> on Google</label><br />
    <label><input type="checkbox" name="find2" id="find_2" value="newspaper" /> in a newspaper</label><br />
    <label><input type="checkbox" name="find3" id="find_3" value="tv" /> on TV</label><br />
    <label><input type="checkbox" name="find4" id="find_4" value="other" /> other</label>
    </p>
    <p>
    <button id="submitForm" onclick="return sendForm()">Submit contact form</button>
    <button id="submitForm_fake">Wait...</button>
    </p>
    </div>

</body>
        </html>

Înapoi la “Tutoriale JS”

Cine este conectat

Utilizatori răsfoind acest forum: Niciun utilizator înregistrat și 2 vizitatori