I have to make a JSON ajax request and have an array in return.
i found this code on multiple other questions (edited to my problem):
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
var data = response.get_response;
for (i in data){
hej.push([i,data[i]]);
}
alert(hej[0]);
}
In the php part, i have a database from which i need the data i have have 5 columns pr. row. I only have one row, and i need all five columns in the array.
$sql = "SELECT * FROM 'table'
LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = Array();
while($row = mysql_fetch_array($result))
{
$storeArray[0]=$row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode($storeArray);
echo $json;
I know im doing something wrong, and i am new to programming. I need to be able to access all column values in my javascript after the call and use them in other functions, but i cant get it to return.
I would really appriciate help, with both the javascript and the php if there are errors in either.
Why use response.get_response?
var hej[];
function ajax_search(){
$.getJSON('test.php',function(data){
$.each(data, function (i,item) {
hej.push([i,item]);
}
alert(hej[0]);
}
Try this:
Javascript Code:
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
$.each(response.results, function(key, val) {
hej.push(val);
});
alert(hej[0]);
});
}
PHP Code:
<?php
$sql = "SELECT * FROM 'table' LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = array();
while($row = mysql_fetch_array($result)) {
$storeArray[0]= $row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode( array('results' => $storeArray ) );
echo $json;
?>
Hope this helps.
It should be:
function ajax_search(){
$.getJSON('test2.php',function(response){
// response.column1
// response.column2
// response.column3
// for array push:
var hej = [];
$.each(response, function(key, val) {
hej.push(val);
});
alert(hej[0]); // it will alert column1
});
}
and MySQL:
$sql = "SELECT `column1`, `column2`, `column3`, `column4`, `column5` FROM `table` LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$json = json_encode($row);
echo $json;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.