PHP does not display Json

Asked

Viewed 96 times

1

I have a code that takes the data from a form and sends it to a PHP page via AJAX.

When I try to display JSON data, PHP does not display and only shows square brackets as an array.

HTML:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <title>Cadastro Cliente</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src="js/jquery-3.3.1.js"></script>
    <script src="js/popper-min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/bootstrap.js"></script>
    <script src="js/envio.js"></script>
</head>
<body>
    <div id="principal" class="container mt-5" left="10px">
        <form class="form-horizontal">
        <fieldset>

        <!-- Form Name -->
        <legend>Cadastro Cliente</legend>

        <!-- Text input-->
        <div class="form-group">
          <label class="col-md-4 control-label" for="Digite o seu nome:">Nome:</label>  
          <div class="col-md-4">
          <input id="nome" name="Digite o seu nome:" type="text" placeholder="Digite seu nome" class="form-control input-md" required="true">
          <span class="help-block">nome</span>  
          </div>
        </div>

        <!-- Multiple Radios -->
        <div class="form-group">
          <label class="col-md-4 control-label" for="Sexo">Sexo</label>
          <div class="col-md-4">
          <div class="radio">
            <label for="Sexo-0">
              <input type="radio" name="sexo" id="sexo" value="M" checked="checked">
              Masculino
            </label>
            </div>
          <div class="radio">
            <label for="Sexo-1">
              <input type="radio" name="sexo" id="sexo" value="F">
              Feminino
            </label>
            </div>
          </div>
        </div>

        <!-- Multiple Checkboxes (inline) -->
        <div class="form-group">
          <label class="col-md-4 control-label" for="interesses">Interesses</label>
          <div class="col-md-4">
            <label class="checkbox-inline" for="Interesses-0">
              <input type="checkbox" name="interesses[]" id="interesses" value="esportes">
              Esportes
            </label>
            <label class="checkbox-inline" for="Interesses-1">
              <input type="checkbox" name="interesses[]" id="interesses" value="estudar">
              Estudar
            </label>
            <label class="checkbox-inline" for="Interesses-2">
              <input type="checkbox" name="interesses[]" id="interesses" value="videogame">
              Video Game
            </label>
            <label class="checkbox-inline" for="Interesses-3">
              <input type="checkbox" name="interesses[]" id="interesses" value="outros">
              Outros
            </label>
          </div>
        </div>

        <!-- Select Basic -->
        <div class="form-group">
          <label class="col-md-4 control-label" for="como">Como nos encontrou ?</label>
          <div class="col-md-4">
            <select id="como" name="como" class="form-control">
              <option value="" selected>Escolher</option>
              <option value="Tv">Tv</option>
              <option value="amigos">Amigos</option>
              <option value="familia">Família</option>
            </select>
          </div>
        </div>

        <!-- Textarea -->
        <div class="form-group">
          <label class="col-md-4 control-label" for="comentarios">Comentários</label>
          <div class="col-md-4">                     
            <textarea class="form-control" id="comentarios" name="comentarios">Comente Aqui !!!</textarea>
          </div>
        </div>

        <!-- Button (Double) -->
        <div class="form-group">
          <label class="col-md-4 control-label" for="enviar">Enviar</label>
          <div class="col-md-8">
            <button type="submit" id="enviar" name="enviar" class="btn btn-success">Enviar</button>
            <button type="reset" id="reset" name="reset" class="btn btn-danger">Resetar</button>
          </div>
        </div>

        </fieldset>
        </form>
        <span id="resp"></span>
    </div>
</body>
</html>

Javascript/Jquery (This is the.js upload):

$(document).ready(function()
{
    $('form').submit(function(e){
        e.preventDefault();
    })

    $("#enviar").click(function(){
        let cliente = {};

        cliente.nome = $("#nome").val(); // pega o nome do cliente
        cliente.sexo= $("#sexo:checked").val();// pega o sexo selecionado
        cliente.comentarios = $("#comentarios").val();// armazena os comentários
        cliente.como = $("#como").val();// armazena o valor do select

        let interesses = new Array();

        $.each($("#interesses:checked"),function(indice,elemento){
            interesses[indice] = elemento.value;
        })

        cliente.interesses = interesses;

        $.ajax({
            type:'POST',
            url:'php/destino.php',
            context:document.body,
            data:cliente,
            dataType:'json',
            success:function(resposta){
                console.log(resposta);
                $("#resp").attr('style','color:blue');
                $("#resp").html(resposta.nome +" "+ "Cadastro feito com sucesso !!");
            },
            error:function(erro){
                console.log(erro);
                $("#resp").attr('style','color:red');
                $("#resp").html(erro);
            }
        })
    })
})

PHP (destination.php):

<?php  
    echo json_encode($_POST);
?>
  • Is this error not happening because you are setting the Content-Type as json, this MIME type does not exist? Try to reset it as application/json. In fact most of the time you don’t need to set it manually, jQuery does it for you.

2 answers

0

Use the method serialize to take the form data, so it is not necessary to take the client data manually in Javascript.

$("#enviar").click(function(){

     $.ajax({
        type:'POST',
        url:'php/destino.php',
        context:document.body,
        data: $('form').serialize(),
        dataType:'json',
        success:function(resposta){
            console.log(resposta);
            $("#resp").attr('style','color:blue');
            $("#resp").html(resposta.responseJSON.nome + " Cadastro feito com sucesso !!");
        },
        error:function(erro){
            console.log(erro);
            $("#resp").attr('style','color:red');
            $("#resp").html(erro);
        }
    });

});

Code in PHP:

<?php

$nomeCliente = $_POST['nome'];

echo json_encode([
    'nome' => $nomeCliente,
    // Outros dados podem ser adicionados no array se precisar
]);

0

This is because you are using jQuery Slim version. Replace with the jQuery Uncompressed version below, which will work(download and paste into your js folder which is your context, download site is this here):

<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

For the jQuery Slim does not have the function $.ajax o jQuery Uncompressed yes, even when you debug will appear the message stating that $ajax is not a Function. Take advantage and put the other fields of the form. Follow changes I made for improvement:

index.html file

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <title>Cadastro Cliente</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
        crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


        <script type="text/javascript">
            $(document).ready(function ()
            {
                $('form').submit(function (e) {
                    e.preventDefault();
                })

                $("#enviar").click(function () {
                    let cliente = {};

                    cliente.nome = $("#nome").val(); // pega o nome do cliente
                    cliente.sexo = $("#sexo:checked").val();// pega o sexo selecionado
                    cliente.comentarios = $("#comentarios").val();// armazena os comentários
                    cliente.como = $("#como").val();// armazena o valor do select

                    let interesses = new Array();

                    $.each($("#interesses:checked"), function (indice, elemento) {
                        interesses[indice] = elemento.value;
                    })

                    cliente.interesses = interesses;

                    $.ajax({
                        type: 'POST',
                        url: 'php/destino.php',
                        context: document.body,
                        data: cliente,
                        dataType: 'json',
                        success: function (resposta) {
                            console.log(resposta);
                            $("#resp").attr('style', 'color:blue');
                            $("#resp").html("<h6>Cadastro feito com sucesso !!!</h6>Dados preenchidos:<div style='color:black'>" + "Nome: " + resposta.nome + "<br>Sexo: " + resposta.sexo + "<br>Interesses: " + resposta.interesses + "<br>Comentários: " + resposta.comentarios + "</div>");
                        },
                        error: function (erro) {
                            console.log(erro);
                            $("#resp").attr('style', 'color:red');
                            $("#resp").html(erro);
                        }
                    })
                })
            });
        </script>
    </head>
    <body>
        <div id="principal" class="container mt-5" style="left: 10px;">
            <form class="form-horizontal">
                <fieldset>

                    <!-- Form Name -->
                    <legend>Cadastro Cliente</legend>

                    <!-- Text input-->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="Digite o seu nome:">Nome:</label>  
                        <div class="col-md-4">
                            <input id="nome" name="Digite o seu nome:" type="text" placeholder="Digite seu nome" class="form-control input-md" required="true">
                            <span class="help-block">nome</span>  
                        </div>
                    </div>

                    <!-- Multiple Radios -->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="Sexo">Sexo</label>
                        <div class="col-md-4">
                            <div class="radio">
                                <label for="Sexo-0">
                                    <input type="radio" name="sexo" id="sexo" value="M" checked="checked">
                                    Masculino
                                </label>
                            </div>
                            <div class="radio">
                                <label for="Sexo-1">
                                    <input type="radio" name="sexo" id="sexo" value="F">
                                    Feminino
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Multiple Checkboxes (inline) -->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="interesses">Interesses</label>
                        <div class="col-md-4">
                            <label class="checkbox-inline" for="Interesses-0">
                                <input type="checkbox" name="interesses[]" id="interesses" value="esportes">
                                Esportes
                            </label>
                            <label class="checkbox-inline" for="Interesses-1">
                                <input type="checkbox" name="interesses[]" id="interesses" value="estudar">
                                Estudar
                            </label>
                            <label class="checkbox-inline" for="Interesses-2">
                                <input type="checkbox" name="interesses[]" id="interesses" value="videogame">
                                Video Game
                            </label>
                            <label class="checkbox-inline" for="Interesses-3">
                                <input type="checkbox" name="interesses[]" id="interesses" value="outros">
                                Outros
                            </label>
                        </div>
                    </div>

                    <!-- Select Basic -->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="como">Como nos encontrou ?</label>
                        <div class="col-md-4">
                            <select id="como" name="como" class="form-control">
                                <option value="" selected>Escolher</option>
                                <option value="Tv">Tv</option>
                                <option value="amigos">Amigos</option>
                                <option value="familia">Família</option>
                            </select>
                        </div>
                    </div>

                    <!-- Textarea -->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="comentarios">Comentários</label>
                        <div class="col-md-4">                     
                            <textarea class="form-control" id="comentarios" name="comentarios">Comente Aqui !!!</textarea>
                        </div>
                    </div>

                    <!-- Button (Double) -->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="enviar">Enviar</label>
                        <div class="col-md-8">
                            <button type="submit" id="enviar" name="enviar" class="btn btn-success">Enviar</button>
                            <button type="reset" id="reset" name="reset" class="btn btn-danger">Resetar</button>
                        </div>
                    </div>

                </fieldset>
            </form>

            <span id="resp"></span>
        </div>

    </body>
</html>

php destination.

<?php

echo json_encode($_POST);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.