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