1

I'm trying to write a contact form with PHP, Ajax and JQuery.

The error is this:

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (

but I dont know what I'm doing wrong, because I copied and paste the code of some tutorial.

i´m using foundation6, php and ajax.

I think that the error is for JSON.parse but i don´t know how resolve

This is my code, you can help me? Thanks

contact.php

 <form method="post" id="formulario" data-abide novalidate action="<?php echo get_stylesheet_directory_uri(); ?>/src/assets/php/enviar.php">
                            <div class="campo">
                                <label for="nombre">Nombre: 
                                    <input type="text" id="nombre" placeholeder="Nombre" name="name" required>
                                    <span class="form-error">Error el nombre no puede ir vacio.</span>
                                </label>
                            </div>
                            <div class="campo">
                                <label for="email">Email: 
                                    <input type="text" id="email" placeholeder="Email" name="email" required pattern="email">
                                    <span class="form-error">Error correo vacio o invalido.</span>
                                </label>
                            </div> 

                            <div class="campo">
                                <label for="fecha">Mensaje: 
                                    <textarea name="mensaje" rows="6" required></textarea>
                                    <span class="form-error">Error correo vacio o invalido.</span>
                                </label>
                            </div> 
                            <div class="campo">
                                <input type="submit" name="enviar" value="Enviar" class="button explorar">
                            </div>
                        </form>

enviar.php

<?php 
    function is_ajax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
    }



if(is_ajax()) {
    $nombre = $_POST['nombre'];
    $email = $_POST['email'];
    $mensaje = $_POST['mensaje'];

    $header = 'From: ' . $email . "\r\n";
    $header .= "X-Mailer: PHP/" . phpversion() . "\r\n";
    $header .= "Mime-Version: 1.0 \r\n";
    $header .= "Content-Type: text/html";

    $mensajeCorreo = 'This message was sent by: ' . $nombre . "\r\n";
    $mensajeCorreo .= "Email: " . $email . "\r\n";
    $mensajeCorreo .= "Mensaje: " . $mensaje . "\r\n";

    $para = "email";
    $asunto = "Contacto de sitio web";
    mail($para, $asunto, utf8_encode($mensajeCorreo), $header );

    echo json_encode(array(
        'mensaje' => sprintf('El mensaje se ha enviado!')
    ));

} else {
    die("Prohibido!");
}

app.js

// Form Contact
$('#formulario')
.on("invalid.zf.abide", function(ev,elem) {
    swal(
        'Error!', 
        'El formulario se envio incompleto',
        'error'
    );
  })


  // form validation passed, form will submit if submit event not returned false
  .on("formvalid.zf.abide", function(ev,frm) {
      var formulario = $(this);
        $.ajax({
            type: formulario.attr('method'),
            url: formulario.attr('action'),
            data: formulario.serialize(),
            success: function(data) {
                    var resultado = data;
                    var respuesta = JSON.parse(resultado);
                  console.log(respuesta);
                  swal(
                      respuesta.message,
                      'Thank You, ' + respuesta.name + ' for your reservation!',
                      'success'
                  )
             }
        });
  })
  // to prevent form from submitting upon successful validation
  .on("submit", function(ev) {
    ev.preventDefault();
    console.log("Submit for form id "+ev.target.id+" intercepted");
  });
John Conde
  • 217,595
  • 99
  • 455
  • 496
atole
  • 11
  • 2
  • whatever it is that you are trying to parse isnt JSON, which is breaking your JSON parser. You should set a breakpoint and debug what the value of `resultado` is when you get to the line `var respuesta = JSON.parse(resultado);` – Will M. May 24 '18 at 17:30
  • You're likely getting a PHP error, which is causing HTML to be returned. View the actual response in your browser's developer tools and/or check your error logs. – Patrick Q May 24 '18 at 17:36
  • 1
    `name="name"` vs `$_POST['nombre'];` – Patrick Q May 24 '18 at 17:38
  • Look at the response in the network tab for your browser console. What are you getting? – aynber May 24 '18 at 17:40
  • i see in console this: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Object.success (app.js:36) at i (jquery.min.js?ver=3.2.1:2) at Object.fireWith [as resolveWith] (jquery.min.js?ver=3.2.1:2) at A (jquery.min.js?ver=3.2.1:4) at XMLHttpRequest. (jquery.min.js?ver=3.2.1:4) – atole May 24 '18 at 18:15
  • Look at the Network Tab, click on the request, and look at the Response tab. What do you see there? – aynber May 24 '18 at 18:23
  • i dont understand very well, what do you want in Network tab>header Request Method: GET Status Code: 304 Not Modified Remote Address: [::1]:3000 Referrer Policy: no-referrer-when-downgrade I upload the example in this url: http://softnur.com/contacto/ But in this the error is another – atole May 24 '18 at 19:05
  • Not the Header, the Response tab. – aynber May 24 '18 at 19:22
  • >
    ( ! ) Notice: Undefined index: nombre in C:\wamp64\www\Softnur\wp-content\themes\FoundationPress\src\assets\php\enviar.php on line 7
    {"mensaje":"Reserva Confirmada","nombre":"$nombre"}
    – atole May 24 '18 at 19:36
  • You have errors that need to be fixed. Specifically, your input is named `name`, not `nombre`. – aynber May 24 '18 at 19:39
  • 1
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Patrick Q May 24 '18 at 19:42
  • I fix the error of input named. but i dont find the solution.....thanls – atole May 24 '18 at 20:00

0 Answers0