0

I'm trying to pass message from phpto ajax but that's not working, besides I want if a field is blank show something like 'enter username'..

Here's what I got:

user.php

<!-- conexion_user.php -->
 <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "usuarios";

$nombre = $_REQUEST['nombre'];
$email = $_REQUEST['email'];
$mensaje = $_REQUEST['mensaje'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO `usuarios`.`usuarios` (`nombre`, `email`, `mensaje`) VALUES ('$nombre', '$email', '$mensaje')";


        if (($_POST['nombre']!="")
            &&($_POST['email']!="")
            &&($_POST['mensaje']!="")) {
            $conn->query($sql) === TRUE;
            echo "Se ha guardado en la BD.";

             $data = Array(
                'success' => true,
                'message' => 'Well done!',
                'data' => Array(
                        'nombre' => $_POST['nombre'].'1',
                        'email' => $_POST['email'].'1',
                        'mensaje' => $_POST['mensaje'].'1',
                    )
                );

            echo json_encode($data);
        }

        else{
            $res = Array(
                'success' => false,
                'message' => 'Error',
                );

            echo json_encode($res);
        }


$conn->close();
?>

ajax.js

$(document).ready(function(){
    $('#formulario').validate({
        rules:{
            nombre:{
                required:false,
                minlength:2
            },
        },
        messages:{
            nombre:{
                minlength: 'Introduzca mas de {0} caracteres'
            }
        },
        submitHandler:function(){
        var datos = {
            nombre: $('#nombre').val(),
            email: $('#email').val(),
            mensaje: $('#mensaje').val()
        }
        $('#exito').show();
        $.ajax({
            url: '../php/conexion_user.php',
            type: 'POST',
            data: datos,
            dataType: 'json',
            success:function(data){
                console.log(data);
                $('#dos').html('<p>' + data.message + '</p>');
                $('#exito').html('Inserción a usuario.').addClass('alert-success');
                $('#exito').fadeOut(3500);
            },
                        error: function(jqXHR,estado,error){
                            console.log(jqXHR);
                            console.log(estado);
                            console.log(error);
                        }
        });

    }
    });
});

html

<div align="center" >
<form id="formulario" method="post" class="form-horizontal">
            <div class="form-group">
                <legend>Usuario</legend>
            </div>
            <center>

            <input type="text" name="nombre" id="nombre" class="form-control" value="" placeholder="Nombre">
            <br>
            <input type="text" placeholder="Email" id="email" name="email"  class="form-control">
            <br>
            <input type="text" name="mensaje" id="mensaje" class="form-control" value="" placeholder="Ingrese Mensaje">
            <button type="submit" id="insert" name="insert" class="btn btn-primary">Submit</button>
    </form>
    <p id="dos"></p>
    </div>  

My insert to db is working, if I hit submit it will successful insert to my db, but it's showing:

object object

instead of message.

Cœur
  • 37,241
  • 25
  • 195
  • 267
User100696
  • 687
  • 4
  • 12
  • 26

2 Answers2

0

Try using JSON.parse().

var parsedData = JSON.parse(data);
Abhinav Jain
  • 329
  • 1
  • 2
  • 9
-1

1) You need to set response header to json. please refer Returning JSON from a PHP Script for detail.

2) you are encoding array not object.

$.ajax({
            url: '../php/conexion_user.php',
            type: 'POST',
            data: datos,
            dataType: 'json',
            success:function(data){
                console.log(data['success']); // check this
                console.log(data['message ']); // check this
                $('#dos').html('<p>' + data.message + '</p>');
                $('#exito').html('Inserción a usuario.').addClass('alert-success');
                $('#exito').fadeOut(3500);
            },
                        error: function(jqXHR,estado,error){
                            console.log(jqXHR);
                            console.log(estado);
                            console.log(error);
                        }
        });

if you want to return object instead of array then refer AJAX Function live preview from drop down list

Community
  • 1
  • 1