0

I'm trying to make an AJAX request. The update is done in the database, but it does not fall into success, if I remove the dataType, it arrives at success, however of both forms it is returning the JSON and HTML when it should return only the JSON.

I could not see anything out of the ordinary in the code. Why this happens. Would my JSON be invalid in any way?

Javascript

$(document).ready(function () {
    $('#depositar').submit(function () {
        var form = $(this);
        var dados = $(this).serialize();

        $.ajax({
            url: 'http://localhost/caixamvc/conta/depositar',
            method: 'POST',
            dataType: 'json',
            data: dados,
            beforeSend: function () {
                $("#retorno").html('Aguarde, validando dados...');
            },
            success: function (resposta) {
                $("#retorno").html(resposta.dados);
            }
        });
        return false;
    });
});

Controller

public function depositar() {
    if (isset($_POST['valor'])) {
        $value = $_POST['valor'];
        $json = [];

        if ($_SESSION['tipo_conta'] == 1) {
            $conta = new ContaCorrente;
        } else {
            $conta = new ContaPoupanca;
        }

        $conta->depositar($_SESSION['user'], $value);
        if ($conta->getResult()) {
            $json['dados'] = "Tudo certo";
        }else{
            $json['retorno'] = "Nada aqui";
        }
        echo json_encode($json);
    }

    $this->loadTemplate('depositar', $this->getData());
}

View

<h4>Depositar</h4> 
<form id="depositar" method="POST">
    Conta:<br/>
    <input type="text" name="valor" /><br/><br/>
    <input type="submit" name="depositar" value="Depositar"/>
    <div id="retorno"></div>
</form>

Response

Response

Ivar
  • 6,138
  • 12
  • 49
  • 61
Leo
  • 3
  • 1

2 Answers2

0

In your controller you conditionally return JSON:

if (isset($_POST['valor'])) {
    //...
    echo json_encode($json);
}

But then always return HTML:

$this->loadTemplate('depositar', $this->getData());

When not returning JSON (the condition is false), this returns valid HTML. But when the condition is true you end up returning both to the client. So the response is neither valid JSON nor valid HTML.

When returning JSON, don't also return HTML. It has to be one or the other:

if (isset($_POST['valor'])) {
    //...
    echo json_encode($json);
} else {
    $this->loadTemplate('depositar', $this->getData());
}

Ideally you would use two different controller actions for this entirely. One which displays the page, another which returns the data. That way you don't have one function which does multiple things and needs if conditions to check which thing it's supposed to do.

Each function should do one thing.

David
  • 208,112
  • 36
  • 198
  • 279
0

The docs say that dataType is:

The type of data that you're expecting back from the server.

While you are echoing out some JSON, you are actually returning HTML. This is because you’re doing one (or both) of these:

  1. Still rendering the template. So the response is some JSON and then an HTML page, both stuck together.

  2. Just because you’re echoing out JSON, doesn’t mean it’s JSON. See a question like Returning JSON from a PHP Script for how to correctly return JSON as JSON.

Zoe Edwards
  • 12,999
  • 3
  • 24
  • 43
  • It really was lack of attention. Thank you. – Leo Dec 21 '17 at 12:48
  • It’d also consider separating your methods to make it simpler to manage. Have one accept the GET request and show the template, and another to manage the POST request. – Zoe Edwards Dec 21 '17 at 14:34