Search code examples
phpformsjquerycolorbox

colorbox submit / send mail form and confirm in same colorbox (ajax?)


I've been searching all around here, but haven't found the way to do this :( And I'm not capable of adapting the existing answers available for this problem.

What I'm doing right now is: 1) When a user clicks on a button, colorbox gets triggered and opens the href attribute, in this case "contact-form.html"

<a href="contact-form.html" class="contacto"><span class="button green">19.999 € (kit)</span></a>

$('a.contacto').colorbox({
href:function(){ return $(this).attr('href'); }, 
width:function(){ 
    if (window.innerWidth > 750) {return '60%';} 
    else if (window.innerWidth > 481) {return '75%';} 
    else {return '90%';}},
onComplete:function(){
    var ruta = document.location.protocol + "//" + document.location.host + document.location.pathname;
    $('input[name=web]').val(ruta);
}
});

2) The form gets displayed in the colorbox

<div id="contactForm">
    <h4>Póngase en contacto con nosotros</h4>
    <form name="formulario" id="formulario" method="post" action="contact-form.php">
        <inputs>........
        <input type="reset" name="reset" id="resetbtn" class="resetbtn button" value="Limpiar datos">
        <input type="submit" name="submit" id="submitbtn" class="submitbtn button green macro" tabindex="7" value="Enviar consulta!">
        <br>
    </form> 
</div><!--Fin del contactForm-->

3) Once the user completes the form and hits submit, the contact-form.php is triggered (some validation, and the mail sending itself. At the end I inserted a header("Location: " + original-pathname-from-where-the-form-was-sent)

<?php
$errors = ''; /*Para comprobar si ha habido errores*/

/*Retrieve variables from $_POST.......*/

if (empty($emailField)) { 
    $errors .= "\n Error: Se requiere un correo electrónico"; 
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $emailField)) {
    $errors .= "\n Error: Correo electrónico inválido";
}

$header = /*Prepare the MAIL HEADERS TO BE SENT*/

$mensaje = /*Prepare the MESSAGE........*/

if (empty($errors)) /*Some validation*/
{
    if (mail($mi_email, $asuntoEmail, utf8_decode($mensaje), $header)) {
        header("Location: $pageRefresh");
    }
    else {
        echo '<script type="text/javascript">';
        echo 'alert("Ha habido algun error en el envio. Por favor, vuelva a intentarlo")';
        echo '</script>';
    }
}
else
{
    echo '<script type="text/javascript">';
    echo 'alert("Ha habido algun error en el envio:'.$errors.'")';
    echo '</script>';
    echo '<p>Ha habido algun error:' .$errors. '</p>';
}
?>

EVERYTHING UP UNTIL THIS POINT is done correctly. The mail is sent to my account, with all the variables filled correctly, and the user is relocated to the original page where the form (colorbox) was opened.

What I can't manage to do is:

I would like the form to be submitted via AJAX, not to have to redirect the user to the same page... OR... if that isn't possible, be able at least, to give the user an alert message that the message/mail was sent successfully or not.

Help very much appreciated! Sorry again if this is a repeated question, but I just can't adapt/solve this on my own :(


Solution

  • If you want to submit the form via AJAX, instead of submitting and loading the action url, you can do this using jQuery's serialize function.

    There are a few changes to make to your code. First, you need to get rid of the submit button. Do this by changing its type to button:

    <input type="button" name="button" id="submitbtn" class="submitbtn button green macro" tabindex="7" value="Enviar consulta!">
    

    Next, we need code to submit the form via AJAX:

    <script type="text/javascript">
    $('#submitbtn').click(function() {
      $.post('contact-form.php', $('#formulario').serialize());
    });
    </script>
    

    This will submit the form fields, via AJAX, without loading a new URL.

    If you want to do something like show a success notification after submission, you can do this:

    <script type="text/javascript">
        $('#submitbtn').click(function() {
          $.post('contact-form.php', $('#formulario').serialize(), function(){
     // Anything here is executed if the post is successful
     alert('success');
     }
    
     );
     });
    </script>