Hello, I have a form that through AJAX and PHP I make a query to my DB to return some of the data, the problem is that it returns undefined when I try to paint a data from the JSON array in a query, I have looked at the browser debug and in PHP if it makes me the query well, returning the array correctly. Where can be the error? Thank you !!
PS: there are no bugs in the jquery libraries, etc, etc. They work right.
form.php (AJAX)
...
<form>
<div class="form-group">
<div class="row">
<label class="col-md-3" for="telf">Nº de teléfono:</label>
<div class="col-md-9">
<input type="text" name="telf" id="telf" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-4">
<button id="buscar" name="buscar">Buscar</button>
</div>
</div>
</div>
</form>
...
<script>
$(document).ready(function() {
$(document).on("click", "#buscar", function (e) {
e.preventDefault();
var telf = $('#telf').val();
var url = "buscar.php";
var dataValue = {'telf': telf};
$.ajax({
type: "POST",
url: url,
data: dataValue,
cache: false,
dataType: "json",
success: function (data) {
console.log(data.nombre_cli);
}
});
return false;
});
});
</script>
search.php (SQL)
<?php
require("conexion.php");
$telf= $mysqli->real_escape_string($_REQUEST['telf']);
$stmt = $mysqli->prepare("SELECT nombre_cli, ... FROM ... WHERE num_telefono = ?");
$stmt->bind_param("i", $telf);
$stmt->execute();
$result = $stmt->get_result();
$json = array();
while ($data = $result->fetch_assoc()) {
$json["data"][] = $data;
}
echo json_encode($json);
$stmt->free_result();
$stmt->close();
It returns
undefined
you because you are trying to access data that does not exist. You are saving your dataPHP
inside aArray
keydata
so what you will receive will be an object with this form:Either you change your implementation of
PHP
so that it doesn't create that indexdata
, or you should access that parameter first before trying to accessJavaScript
the data:On the other hand when calling
fetch_assoc
you are creating anArray
associative so the structure will be:See the following snippet so you understand the structure you are creating.
With that structure, the way
JavaScript
to access the first data would be:The best thing is that you do one
console.log
of what you receive from the server:This way you will see the structure of the object and you will be able to access its data guided by said structure.