Notice when sending PHP form

2

I am sending a form with SendGrid. How do I get the message "Your request has been sent" or otherwise in case it is a failure ?, How do I run $ okMessage and $ errorMessage?

HTML

<form id="contact-form" method="post" action="enviar_email.php" role="form">
                    
                    <div class="messages"></div>
                    
                    <div class="form-group">
                        <select class="form-control" name="categoria">
                            <option>-- Selecciona una 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 id="form_message" name="detalles" class="form-control" placeholder="Detalles *" rows="4" required="required" data-error="Detalles requerido." ></textarea>
                        <div class="help-block with-errors"></div>
                    </div>
                    
                    <div class="form-group">
                        <input id="form_email" type="email" name="email" class="form-control" placeholder="Email *" required="required" data-error="Email requerido." />
                        <div class="help-block with-errors"></div>
                    </div>
                    
                    <div class="row">
                        <div class="form-group col-md-8">
                            <input id="form_name" type="text" name="nombre" class="form-control" placeholder="Nombre *" required="required" data-error="Nombre requerido.">
                            <div class="help-block with-errors"></div>
                        </div>
                        <div class="form-group col-md-4">
                            <input id="form_phone" type="tel" name="telefono" class="form-control" placeholder="Teléfono *" required="required" data-error="Teléfono requerido.">
                            <div class="help-block with-errors"></div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="form-group col-md-8">
                            <p><small>Índice de respuesta: 1 hra. aproximadamente.</small></p>
                        </div>
                        <div class="form-group col-md-4 text-right">
                            <input type="submit" class="btn btn-primary" value="Enviar Requerimiento">
                        </div>
                    </div>
                    
                </form> 

send_email.php

<?php
require 'vendor/autoload.php'; 

    $from = new SendGrid\Email('Name', "[email protected]");
    $subject = "Asunto";
    $to = new SendGrid\Email('Name', "[email protected]");
    
    $categoria = strip_tags($_POST['categoria']);
    $detalles = strip_tags($_POST['detalles']);
    $email = strip_tags($_POST['email']);
    $nombre = strip_tags($_POST['nombre']);
    $telefono = strip_tags($_POST['telefono']);

    $content = new SendGrid\Content("text/html", "Hola, ha llegado un nuevo mensaje <br><br>Categoría: $categoria<br>Detalles: $detalles<br>Email: $email<br>Nombre: $nombre<br>Teléfono: $telefono<br>");


    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $okMessage = 'Tu requerimiento ha sido enviado.';
    $errorMessage = 'Se produjo un error, por favor inténtalo nuevamente.';

    $apiKey = 'MyApiKey';
    $sg = new \SendGrid($apiKey);

    $response = $sg->client->mail()->send()->post($mail);
    echo $response->statusCode();
    echo $response->headers();
    echo $response->body();   
?>

PHP (previous) Before I was using this code and if I got the notice.

<?php
 

// configure
$from       = 'Name <[email protected]>';
$sendTo     = 'Name <[email protected]>';
$subject    = 'Asunto';
$fields     = array('categoria' => 'Categoría', 'detalles' => 'Detalles', 'email' => 'Email', 'nombre' => 'Nombre', 'telefono' => 'Teléfono'); // array variable name => Text to appear in the email
$okMessage = 'Tu mensaje ha sido enviado.';
$errorMessage = 'Se produjo un error, por favor inténtalo nuevamente.';

// let's do the sending

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

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

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value<br><hr style='border-top: 1px solid #eaeaea;'>";
        }
    }
    
    
    $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'];
}

?>

contact.js

$(function () {

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

    $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "enviar_email.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;
        }
    })
});
    
asked by Paco Zevallos 01.03.2017 в 16:12
source

2 answers

0

In your case, it seems that the only thing you need to know is the statusCode of the response. Your code would be like this

<?php
require 'vendor/autoload.php'; 

$from = new SendGrid\Email('Name', "[email protected]");
$subject = "Asunto";
$to = new SendGrid\Email('Name', "[email protected]");

$categoria = strip_tags($_POST['categoria']);
$detalles = strip_tags($_POST['detalles']);
$email = strip_tags($_POST['email']);
$nombre = strip_tags($_POST['nombre']);
$telefono = strip_tags($_POST['telefono']);

$content = new SendGrid\Content("text/html", "Hola, ha llegado un nuevo mensaje <br><br>Categoría: $categoria<br>Detalles: $detalles<br>Email: $email<br>Nombre: $nombre<br>Teléfono: $telefono<br>");


$mail = new SendGrid\Mail($from, $subject, $to, $content);

$okMessage = 'Tu requerimiento ha sido enviado.';
$errorMessage = 'Se produjo un error, por favor inténtalo nuevamente.';

$apiKey = 'MyApiKey';
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($mail);

$status_code = $response->statusCode();

if( substr($status_code,0,1) == 2 )
    $responseArray = [
        'type' => 'success', 
        'message' => $okMessage,
        'status'=>$status_code
    ];
} else {
    $responseArray = [
        'type' => 'danger', 
        'message' => $errorMessage
        'status' => $status_code
        ];
}

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'];
}

The statusCode is a value whose meaning corresponds to one of the HTTP status codes . Broadly:

  • A 2xx response is successful
  • A 3xx response is redirection
  • A 4xx answer is an error of yours
  • A 5xx response is an error of them

That's why I say that if the first digit of the answer is a 2, then the request worked fine. Otherwise, I send the $ error Message.

    
answered by 01.03.2017 в 19:40
0

Thanks @amenadiel, it worked for me with some slight adjustments of the bracket and the array.

<?php
require 'vendor/autoload.php'; 

    $from = new SendGrid\Email('Name', "[email protected]");
    $subject = "Asunto";
    $to = new SendGrid\Email('Name', "[email protected]");

    $categoria = strip_tags($_POST['categoria']);
    $detalles = strip_tags($_POST['detalles']);
    $email = strip_tags($_POST['email']);
    $nombre = strip_tags($_POST['nombre']);
    $telefono = strip_tags($_POST['telefono']);

    $content = new SendGrid\Content("text/html", "Hola, tienes un nuevo mensaje <br><br>Categoría: $categoria<br>Detalles: $detalles<br>Email: $email<br>Nombre: $nombre<br>Teléfono: $telefono<br>");


    $mail = new SendGrid\Mail($from, $subject, $to, $content);

    $okMessage = 'Tu mensaje ha sido enviado.';
    $errorMessage = 'Se produjo un error, por favor inténtalo nuevamente.';

    $apiKey = 'MyApiKey';
    $sg = new \SendGrid($apiKey);

    $response = $sg->client->mail()->send()->post($mail);
   

    
    $status_code = $response->statusCode();

    if( substr($status_code,0,1) == 2 )
        $responseArray = array('type' => 'success', 'message' => $okMessage, 'status'=> $status_code);
   

    else {
        $responseArray = array ('type' => 'danger', 'message' => $errorMessage, 'status' => $status_code);
    }

    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'];
}

?>
    
answered by 01.03.2017 в 23:03