0

filePHP.php

$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $json = array('id' => $row['id_kategori'], 'nama' => $row['nama_kategori']);
    echo json_encode($json);
}

and index.php

$.post('filePHP.php', function(data){
   console.log(data);
},'json');

but this not working, what would solve this problem?

4
  • 1
    Please provide information on what is not working. Error message, returned data, expected data. There can never be too much information Commented Oct 22, 2013 at 4:56
  • ohh i'm sorry @elzaer Commented Oct 22, 2013 at 5:13
  • 1
    in you ajax you are using "proses.php" while code is in "filePHP.php". Commented Oct 22, 2013 at 5:23
  • @developerCK : sorry for the file name,, but this code copy/paste from my project, mr. .. Commented Oct 22, 2013 at 10:21

2 Answers 2

2

Try this in PHP

$query = $kon->prepare("SELECT id_kategori,nama_kategori FROM t_kategori");
$query->execute();
$json=array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $arr=array('id'=>$row['id_kategori'],'nama'=>$row['nama_kategori']);
    array_push($json,$arr);
}
echo json_encode($json);

Read array-push

Sign up to request clarification or add additional context in comments.

3 Comments

best coding practice says you should use column name instead of asterisk(*). Use array_push() in loop
@Ryo check the file name you passed in $.post as Both are looking different in your question and in $.post
@rohan : ohh sorry,,, but this source copy/paste from my project .. hehehe
1

try something like this , your code will echo json in wrong format whereas below code will give you json array.

$query = $kon->prepare("SELECT * FROM t_kategori");
$query->execute();
$json_arr =array();
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $temp_arr = array();
    $temp_arr['id'] => $row['id_kategori'];
    $temp_arr['nama'] => $row['nama_kategori'];
    array_push($json_arr,$temp_arr);
}

echo json_encode($json_arr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.