Show result of Ajax in the modal itself with Bootstrap

1

I would like to know how I do it so that when the user submits the form he notifies it in the same modal, without reloading the page.

Content to be included in modal

<div class="modal-body">                  
    <div class="">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">Requerimiento</h4><br>
    </div>

    <form id="" method="post">

        <div class="form-group">
            <select class="form-control" name="categoria">
                <option>-- Selecciona un categoría --</option>
                <option>Branding e identidad de marca</option>
                <option>Comunicación interna</option>
                <option>Diseño Editorial</option>
                <option>Desarrollo Web</option>
                <option>Multimedia y 3D</option>
                <option>Redes Sociales</option>
                <option>Marketing Electrónico</option>
                <option>Diseño de Empaques</option>
                <option>Otro</option>
            </select>
        </div>


        <div class="form-group">
            <textarea class="form-control" rows="4" placeholder="Detalles" name="detalles"></textarea>
        </div>

        <div class="form-group">
            <input class="form-control" type="text" name="email" placeholder="Email" />
        </div>

        <div class="row">
            <div class="form-group col-md-8">
                <input type="text" class="form-control" placeholder="Nombre" name="name" >
            </div>
            <div class="form-group col-md-4">
                <input type="text" class="form-control" placeholder="Teléfono" name="telefono">
            </div>
        </div>

        <p>Índice de respuesta: 1 hra. aproximadamente.</p><br>     


        <div class="text-right">
            <button type="button" class="btn btn-link" data-dismiss="modal">Cerrar</button>
            <button class="btn btn-primary" type="submit" name="btn_send">Enviar requerimiento</button>
        </div>      

    </form>  
</div>

Code used in the form:

$(function() {
    $("#contact-form").submit(function(e) {
        e.preventDefault();
        $form = $(this);
        $.post(document.location.url, $(this).serialize(), function(data) {
            $feedback = $("<div>").html(data).find("form-feedback");
            $form.prepend($feedback);
        });
    });
})

Expected result

    
asked by Paco Zevallos 24.02.2017 в 18:24
source

3 answers

4

First change the type of button by a buttoon, since the submit reloads the page

<button class="btn btn-primary" type="button" name="btn_send">Enviar requerimiento</button>

Afterwards, I recommend that you throw the confirmation modal in the succes function of the ajax.

Note: you are not necessarily going to use that ajax structure, use the one that best suits your needs.

$.ajax({
        async: true,
        url: action,
        type: 'POST',
        dataType: "html",
        data: JSON.stringify(objRequerimiento),
        contentType: 'application/json',
        success: function (data) {
            lanzarConfirmacion(data);
        },
        error: function (error) {
            funError(error);
        }
    });

And finally, the casting function will be executedConfirmation ()

<div class="modal-confirmacion">
    //Contenido del modal
</div>
<script>
    lanzarConfirmacion(data){
       //Llamado a modal-contenido 
  }
</script>
    
answered by 24.02.2017 в 19:26
1

I think I have found the solution. I followed the following tutorial: Form with Bootstrap, Ajax and PHP ( includes validation).

The only thing I have added is that the form that appears there I put it in a modal (previous creation of a button).

I leave the files for who can serve: Contact form modal

These are the codes that I used (well the essentials, there are more that are in the downloadable file)

HMTL

<div class="container">

            <div class="row">
                
                <button  type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Cuéntanos tu caso</button>
                
              <!-- Modal -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
          <div class="modal-dialog" role="document">  
            <div class="modal-content">
              <div class="modal-body">  
                
                
                
                

                <div>    
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel">Requerimiento</h4><br>
                </div>

                    <form id="contact-form" method="post" action="contact.php" role="form">
                        <div class="messages"></div>
                        <div class="controls">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_name">Firstname *</label>
                                        <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" required="required" data-error="Firstname is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_lastname">Lastname *</label>
                                        <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *" required="required" data-error="Lastname is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_email">Email *</label>
                                        <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="form_phone">Phone</label>
                                        <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="form_message">Message *</label>
                                        <textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
                                        <div class="help-block with-errors"></div>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <input type="submit" class="btn btn-success btn-send" value="Send message">
                                </div>
                            </div>
                            <div class="row">
                                
                            </div>
                        </div>

                    </form>

                
                
                
                        </div>
                    </div>
                </div>
            </div>
                
                
                
                
                
                

            </div> <!-- /.row-->

        </div> 

PHP

<?php

// configure
$from       = 'Asunto <[email protected]>';
$sendTo     = 'Asunto <[email protected]>';
$subject    = 'Nuevo requerimiento desde Khapac.com';
$fields     = array('name' => 'Name<br>', 'surname'=> 'Surname<br>', 'phone' => 'Phone<br>', 'email' => 'Email<br>', 'message' => 'Message'); // array variable name => Text to appear in the email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';

// let's do the sending

try
{
    $emailText = "Hola, ha llegado un nuevo requerimiento desde la web de Khapac.com";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    $headers = array('Content-Type: text/html; charset="UTF-8";',
        'From: ' . $from,
        'Reply-To: ' . $from,
        'Return-Path: ' . $from,
    );
    
    mail($sendTo, $subject, $emailText, implode("\n", $headers));

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}

JS

$(function () {

    $('#contact-form').validator();

    $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#contact-form').find('.messages').html(alertBox);
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});
    
answered by 27.02.2017 в 19:38
0

1.- First create a div where the message will be placed (the design is of your choice).
2.- In your backend (be it php, java, etc.) you must have a function that sends your message when it is finished. Do an echo 'Thank you, your message was sent'; (assuming it's PHP).
3.- in your ajax try printing the returned data (console.log, alert (), etc.). 4.- if you work, do this within the success or done (as the case may be) $ ('div of the message'). Html (data)

html

<div id="respuesta"></div>


PHP (Class)

<?php
    Class LaClase {
        // esto es una clase pero omito lo demás 
        public function tuMetodoEnviarMensaje() {
            $bandera = false;
            // aquí haces todo el proceso para enviar el mensaje
            if ( /* Solo si el mensaje se envió*/) {
                $bandera = true;
            }
            return $bandera; // tu mismo proceso asigna el valor a la bandera
        }
    }
?>


PHP (POO) this file will be called iran.php

<?php
    // si trabajas con POO aquí ya sabes que código va
    include_once('path');
    $objClass = LaClase();
    $bandera = $objClass->tuMetodoEnviarMensaje();
    // bandera es un booleano ( true o false dado por el método )
    if ( $bandera ) {
        echo 'Gracias tu mensaje fue enviado';
    } else {
        echo 'Hubo un error';
    }
?>


AJAX

$.post( "iran.php", function( data ) { // importante que el archivo sea php
    $( "#respuesta" ).html( data );
});
    
answered by 24.02.2017 в 19:50