2015-10-13 7 views
7

Ho un modulo di contatto HTML che è incorporato in index.html, e quindi ho un file mail.php che invia una mail e usa anche alcuni Javascript. Quando compilo il modulo e lo invio, l'ho codificato per inviare la posta, quindi viene visualizzata una finestra di messaggio di successo e quindi viene reindirizzato a index.html.Sostituendo il modulo HTML con il messaggio di successo dopo l'invio, il modulo invia la posta utilizzando il file php separato

Quello che vorrei è che il modulo venga sostituito con il messaggio di successo, per evitare un aggiornamento della pagina e anche per evitare la finestra del messaggio.

forma da index.html:

<form action="mail.php" method="POST"> 
    <div class="row uniform"> 
    <div class="6u 12u$(xsmall)"> 
     <input type="text" name="name" id="name" value="" placeholder="Name" /> 
    </div> 
    <div class="6u$ 12u$(xsmall)"> 
     <input type="email" name="email" id="email" value="" placeholder="Email" /> 
    </div> 
    <div class="12u$"> 
     <!--<div class="select-wrapper"> 

     </div>--> 
    </div> 
    <div class="12u$"> 
     <textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea> 
    </div> 
     <center><div class="g-recaptcha" data-sitekey=""></div></center> 
    <div class="12u$"> 
     <ul class="actions"> 
     <li><input type="submit" value="Send Message" class="special" /></li> 
     <li><input type="reset" value="Reset" /></li> 
     </ul> 
    </div> 
    </div> 
</form> 

file php, indirizzo e-mail e il token recaptcha rimosso per ovvi motivi:

<?php $name = $_POST['name']; 
$email = $_POST['email']; 
$message = $_POST['message']; 
$formcontent = "From: $name \n email: $email \n Message: $message"; 
$recipient = 'email address here'; 
$subject = 'Message from Website'; 
$mailheader = "From: $email \r\n"; 
$captcha; 
{ 
    if(isset($_POST['g-recaptcha-response'])) 
    { 
     $captcha=$_POST['g-recaptcha-response']; 
    } 
    if(!$captcha) 
    { 
     echo '<script language="javascript">'; 
     echo 'alert("Please check the Captcha")'; 
     echo '</script>'; 
     exit; 
    } 
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); 
    if($response.success==false) 
    { 
    echo '<h2>Please do not try and spam here.</h2>'; 
    }else 
    { 
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); 
echo '<script language="javascript">'; 
echo 'alert("Your Message successfully sent, we will get back to you ASAP.");'; 
echo 'window.location.href="index.html";'; 
echo '</script>'; 
    } 
} ?> 

Questo è un argomento che ho effettivamente guardato:

Clear form after submit and success message

risposta

2

modo migliore per farlo tutte le tue cose è quello di utilizzare l'Ajax. Includi jquery nel tuo html.

Metti la tua forma all'interno di un div involucro

<div class="something"> 
<!-- your form here --> 
</div> 

inoltrare il modulo tramite ajax, anziché tramite il modulo di base presentazione

//"idform" is the id of the form 
$("#idForm").submit(function() { 

    var url = "path/to/your/script.php"; // the script where you handle the form input. 

    $.ajax({ 
      type: "POST", 
      url: url, 
      // serialize your form's elements. 
      data: $("#idForm").serialize(), 
      success: function(data) 
      { 
       // "something" is the class of your form wrapper 
       $('.something').html(data); 
      } 
     }); 
    // avoid to execute the actual submit of the form. 
    return false; 
}); 

E ultima cosa che devi cambiare è nel codice php

mantenere un solo eco per il successo

echo "Your Message successfully sent, we will get back to you ASAP."; 
+0

solo FYI: 'data.message' sarà indefinito,' data' stesso sarà una stringa - '" Il tuo messaggio inviato con successo, ti risponderemo al più presto. "' – Pogrindis

+0

oops .. Ho pensato di restituire un formattato json ... Grazie, aggiornerò la mia risposta. –

+0

@SumitPandey Sono interessato a provare la tua risposta, ho implementato la risposta inviata da hunijkah ma c'è un errore nel controllo degli errori, l'ho guardato per vedere qual è il problema, ma sono nuovo per Ajax e jQuery. Il mio file php aveva già tutto il controllo degli errori, quindi pensavo che il file php avrebbe continuato a gestirlo. La tua risposta avrebbe risolto la mia soluzione? Sono così vicino ad avere questo lavoro ma il controllo degli errori è letteralmente l'unico bump in the road, se il modulo è compilato correttamente funziona perfettamente. – Troy

1

È possibile eseguire ciò utilizzando jQ invio di uery e Ajax.

In primo luogo, includere jQuery nel vostro elemento testa

<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
</head> 

Avanti, date il vostro modulo di un ID

<form id='mail_form' action="mail.php" method="POST"> 

Aggiungere un arco da qualche parte con l'id = 'errore'

<span id='error' style='color:red; font-weight:bold;'></span> 

Modifica il mail.php al seguente:

<?php 
$success = true; 
$errors = array(); 

$name = $_POST['name']; 
$email = $_POST['email']; 
$message = $_POST['message']; 
$formcontent = "From: $name \n email: $email \n Message: $message"; 
$recipient = 'email address here'; 
$subject = 'Message from Website'; 
$mailheader = "From: $email \r\n"; 
$captcha = false; 

    if(isset($_POST['g-recaptcha-response'])) 
    { 
     $captcha=$_POST['g-recaptcha-response']; 
    } 
    if(!$captcha) 
    { 
     $success = false; 
     array_push($errors, "Please check the captcha"); 
    } 
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); 
    if($response.success==false) 
    { 
    $success = false; 
    array_push($errors, "Please do not try and spam here."); 

    } 

if ($success) 
{ 
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); 
} 

$output_array = array("success" => $success, "errors" => $errors); 
echo json_encode($output_array); 
?> 

Poi, nella parte inferiore della pagina aggiungere

<script> 
$('#mail_form').on('submit', function(){ 
    var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to mail.php. Try doing alert(dataIn); to see what it holds. 
    $.post("./mail.php", dataIn) 
     .done(function(dataOut) 
     { 
     //dataOut holds the response from mail.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery. 
     var myArray = JSON.parse(dataOut); 
     if (myArray['success'] == true) //Check if it was successfull. 
      { 
      $("#mail_form").html("Congrats! We just e-mailed you!"); 
      } 
     else //there were errors 
      { 
      $('#error').html(""); //Clear error span 

      $.each(myArray['errors'], function(i){ 
      $('#error').append(myArray['errors'][i] + "<br>"); 
      } 
     }); 
return false; //Make sure you do this or it will submit the form and redirect 
}); 
</script> 
+0

Quindi ho usato la soluzione e funziona. tuttavia, nessuno dei miei errori di controllo funziona più, cioè inserisco solo il nome e un messaggio senza riempire l'e-mail o spuntando il recaptcha, e viene comunque fornito con un messaggio di successo, cosa dovrei fare per essere sicuro di ottenere lo stesso errore di controllo che ho avuto l'abitudine di usare il mio file php? – Troy

+0

@Troy cambia fatto in: 'successo' e aggiunge un' .fail' che sarà in grado di produrre in base alla risposta del server. http://api.jquery.com/jquery.ajax/ – Pogrindis

+1

@Troy Ho appena aggiornato la mia risposta per includere la verifica degli errori nel modo in cui ho spiegato in un commento con gli array JSON – hunijkah

1

Prima di tutto è necessario utilizzare la chiamata AJAX per inviare il modulo. Se ti ostini a usare puro JS lo script sarebbe simile a questa (scritto in 5 secondi - probabilmente ha bisogno di qualche regolazione):

<script> 

document.forms['yourForm'].onsubmit = function(form) { // you have to add 'name' attribute to the form and replace 'yourForm' with it 
    var data = ... //here you have to get all the values from form elements and store them in data object. to make less changes to the script use the elements' names as object names 
    if (window.XMLHttpRequest) 
    { 
     var xhReq = new XMLHttpRequest(); 
    } 
    else 
    { 
     var xhReq = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 


    var method= 'POST') 
    var async = false; //you can actually set true here, it doesn't matter much in this case 
    var url = 'mail.php'; 
    xhReq.open(method, url, async); 
    xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
    xhReq.send(data); 



    document.getElementById("form's parent's ID goes here").innerHTML = "new content" 


    return false; 
} 
</script> 

Che è necessario rimuovere tutti gli echi da file php in quanto non sarebbe stata mostrata in ogni caso . Puoi anche aggiungere un po 'più di raffinatezza a questo script, ad es. controlla se la funzione mail ha funzionato correttamente (restituendo qualcosa nel file php e verificando la risposta AJAX in JS) o catturare gli errori captcha.Sarebbe anche estremamente più facile ottenere in jQuery se sei disposto a percorrere questa strada.

+0

più 1 per xhr nativo. – Pogrindis

Problemi correlati