-1
I intend to pass a variable in the url in my wordpress project.
I have the following form:
<input type="text" id="CodigoUtente" name="CodigoUtente" placeholder="Digite número do utente" />
<input type="button" onclick="carrega()" value="OK" />
<br />
<input type="text" id="Nome" placeholder="Nome" disabled="disabled" />
<br />
<input type="text" id="DataNasc" placeholder="Data Nascimento" disabled="disabled" />
<script>
var http = false;
http = new XMLHttpRequest();
function carrega(){
var nome = document.getElementById('CodigoUtente').value;
var url_="conexao4.php?CodigoUtente="+CodigoUtente;
http.open("GET",url_,true);
http.onreadystatechange=function(){
if(http.readyState==4){
var retorno = JSON.parse(http.responseText);
document.getElementById('Nome').value = retorno.email;
document.getElementById('DataNasc').value = retorno.cidade;
}
}
http.send(null);
}
</script>
php is on the page conexao4
$CodigoUtente = $_GET['CodigoUtente'];
if(isset($CodigoUtente)){
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8');
$sql = "SELECT Nome,DataNasc from centrodb.PsicUtentes WHERE CodigoUtente = '$CodigoUtente'";
$resultados = $conn->query($sql);
$json = array();
while ($rowResultados = $resultados->fetch_assoc()) {
$dados = array(
'Nome' => $rowResultados['Nome'],
'DataNasc' => $rowResultados['DataNasc']
);
$json = $dados;
}
echo json_encode($json);
mysqli_close($conn);
}
When I run on the page I get these two errors in the console:
GET http://192.168. 0.22/connection4? Code=[Object%20HTMLInputElement] 404 (Not Found) loads @psychology:362 onclick @psychology:337 VM373:1 Uncaught Syntaxerror: Unexpected token < in JSON at position 0 at JSON.parse () At Xmlhttprequest.http.onreadystatechange (psychology:355)
The problem is in this line when calling the page conexao4.php
:
var url_="conexao4.php?CodigoUtente="+CodigoUtente;
In the wordpress
when I call another page on url
of ajax
do so:
$.ajax({
type: "POST",
url: "./conexao4",
In this situation I don’t know how to do it, it might help?
Would not be
var url_="conexao4.php?CodigoUtente="+nome;
?– Sam
@Sam, yes, it was a mistake and I already solved the mistake of not found
var url_="/index.php/conexao4?CodigoUtente="+nome;
. Now I have this mistakeUncaught SyntaxError: Unexpected token < in JSON at position 0
 at JSON.parse (<anonymous>)
 at XMLHttpRequest.http.onreadystatechange
– Bruno
The page
conexao4.php
probably has HTML, so the error.– Sam
@Sam, no, I’m going to show an image the error. I’m going to update the question
– Bruno
Exactly that. You want to parse an Ajax return in JSON, but this return is an HTML and not a JSON object.
– Sam
@Sam didn’t understand. But on the side of
conexao4.php
I don’t have html, I just have php code– Bruno
Let’s go continue this discussion in chat.
– Sam