Reputation: 133
So i am fetching rows from my database using AJAX and then turning them into an array with a variable identifier Here is the code PHP:
$query_val = $_GET["val"];
$result = mysql_query("SELECT * FROM eventos_main WHERE nome_evento LIKE '%$query_val%' OR local_evento LIKE '%$query_val%' OR descricao_evento LIKE '%$query_val%'");
for($i=0;$i<mysql_num_rows($result);$i++){
$array = array();
$array[$query_val] = mysql_fetch_row($result); //fetch result
echo json_encode($array);
}
Here is the javascript:
$('#s_query').keyup(function(){
var nome = document.getElementById('s_query').value;
$.ajax({
url: 'search.php',
data: '&val='+nome,
dataType: 'json',
success: function(data)
{
console.log(nome);
var image_loc = data.nome[7];
console.log(image_loc);
If i change the line var image_loc = data.nome[7];
to var image_loc = data.nidst[7];
it works perfectly. Nidst is the term i search for.
This code returns the error:
"Uncaught TypeError: Cannot read property '7' of undefined".
What should i do?
Upvotes: 0
Views: 84
Reputation: 78006
data.nome[7];
is trying to access a property of data
named nome
, which doesn't exist. Since you declared a variable nome
which holds your desired property name, you need to reference the value as the property name, like data[nome][7]
.
Example: If var nome = 'foo'
, then data[nome][7]
will evaluate to data['foo'][7]
which is the same as data.foo[7]
.
What you are doing is data.nome[7]
which is the same as data['nome'][7]
, and the only way that would work is if var nome = 'nome'
.
Upvotes: 3
Reputation: 193311
Another problem is that server does not resond with valid json data. Try to modify the code:
$array = array();
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$array[$query_val] = mysql_fetch_row($result);
}
die(json_encode($array));
Upvotes: 0