0
Guys I’m trying a connection with bd via php and returning a json to my javascript, but there’s something I’m forgetting or doing wrong, because I’ve tried to do several ways but never returns the value of the bank, always gives an error in some "trycatch" halfway.
These files are all on the same server.
If you want to see the code running:
My Code:
/**
* Capturar itens do banco de dados
*/
function carregarItens(){
//variáveis
var itens = "", url = "dados.php";
//Capturar Dados Usando Método AJAX do jQuery
$.ajax({
url: $url,
cache: false,
dataType: "json",
beforeSend: function() {
$("h2").html("Carregando..."); //Carregando
},
error: function() {
$("h2").html("Há algum problema com a fonte de dados");
},
success: function(retorno) {
if(retorno[0].erro){
$("h2").html(retorno[0].erro);
}
else{
//Laço para criar linhas da tabela
for(var i = 0; i<retorno.length; i++){
itens += "<tr>";
itens += "<td>" + retorno[i].id + "</td>";
itens += "<td>" + retorno[i].nome + "</td>";
itens += "<td>" + retorno[i].console + "</td>";
itens += "<td>" + retorno[i].preco + "</td>";
itens += "</tr>";
}
//Preencher a Tabela
$("#minhaTabela tbody").html(itens);
//Limpar Status de Carregando
$("h2").html("Carregado");
}
}
});
}
<!DOCTYPE HTML>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<!-- <link rel="icon" type="favicon.png" />
<link rel="stylesheet" type="text/css" href="estilo.css"> -->
<!--jQuery-->
<script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
<!--Script-->
<script src="script.js" type="text/javascript"></script>
</head>
<body onload="carregarItens()">
<section>
<h1>PortilloDesign Tutorial JSON + PHP</h1>
<!--Área que mostrará carregando-->
<h2></h2>
<!--Tabela-->
<table id="minhaTabela">
<caption>Cadastro de Jogos</caption>
<thead>
<th>ID</th>
<th>Jogo</th>
<th>Console</th>
<th>Valor</th>
</thead>
<tbody>
</tbody>
</table>
</section>
</body>
</html>
<?php
/**
* Tutorial jSON
*/
//Definir formato de arquivo
header('Content-Type:' . "text/plain");
$username = ''; //
$password = '';
$hostname = ''; //
$database = '';
//$porta = '' //
$con = mysql_connect($hostname, $username, $password)
or die("Não é possível conectar ao MySQL");
$selected = mysql_select_db($database,$con)
or die("Não foi possível conectar ao banco de dados");
//@pg_close($con); //Encerrrar Conexão
if(!$con) {
echo '[{"erro": "Não foi possível conectar ao banco"';
echo '}]';
}else {
//SQL de BUSCA LISTAGEM
$sql = "SELECT * FROM jogos ORDER BY console";
$result = pg_query($sql); //Executar a SQL
$n = pg_num_rows($result); //Número de Linhas retornadas
if (!$result) {
//Caso não haja retorno
echo '[{"erro": "Há algum erro com a busca. Não retorna resultados"';
echo '}]';
}else if($n<1) {
//Caso não tenha nenhum item
echo '[{"erro": "Não há nenhum dado cadastrado"';
echo '}]';
}else {
//Mesclar resultados em um array
for($i = 0; $i<$n; $i++) {
$dados[] = pg_fetch_assoc($result, $i);
}
echo json_encode($dados, JSON_PRETTY_PRINT);
}
}
?>
you can here the output of
json_encode($dados, JSON_PRETTY_PRINT)
?– MoshMage
What’s the mistake, where it stops?
– rray
@Moshmage http://engenini.com.br/tst/dados.php The error is in php because json was supposed to appear in the output.
– Giovanni Bernini
@rray it here: "error: Function() { $("H2"). html("There is some problem with the data source");" no js, but in php it is not returning anything.
– Giovanni Bernini
Give a console.log on
retorno
This already helps to identify what happened– rray
Where does the variable come from
$con
? And why usemysql
?– Edilson
@rray the console.log in "return" returns nothing.
– Giovanni Bernini
@Edilson, it was error when putting the code here, dbhandle is the con (I will edit)
– Giovanni Bernini
The url in ajax is '$url', but you have set only the variable 'url'.
– Joao Paulo
Friend it is kind of complicated to try to understand the code, because I see too many irregularities and variables that have not even been defined beyond the variable
$con
there are several others. I say then, that if the error is in thePHP
must be one of the connection lines that make use of the functiondie()
.– Edilson
@Joaopaulo Yes, I fixed it.
– Giovanni Bernini
@Edilson the code is quite strange, but it happened because I didn’t get the connection and so I went to get other codes on the Internet that weren’t mine. I believe if it’s simple, I’m not good yet with web, but whatever is wrong in your point of view can say that I seek to know and fix.
– Giovanni Bernini
@Edilson I removed the codes or die, and now it from connection error.
– Giovanni Bernini
Where did you get this tutorial ?
– Edilson
@Edilson here
– Giovanni Bernini
Friend, I edited your answer and put a fully functional example that I created and tested from the original tutorial.
– Edilson
@Edilson Sorry for the ignorance, but where is the code you edited? If you can put as an answer I think it would be better.
– Giovanni Bernini
Oh yeah, it looks like they refused my edition, I’m going to create a new answer.
– Edilson