0

I have the following PHP code which pulls the data form mysql (unicode entries)

$conn = mysqli_connect("localhost", "root", "", "mapping") or die ("Error".mysqli_error($conn));
mysqli_set_charset($conn,"utf8");
$sql = "select * from villages";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
    $myArray[] = $row;
}
mysqli_close($conn);

echo json_encode($myArray, JSON_UNESCAPED_UNICODE);

?>

$myArray[0] is:

{"id":"1","village":"अकबरपुर","villageEn":"akbarpur","subdiv":"हुजूर","tehsil":"हुजूर","ricircle":"रातीबढ़","patwarih":"अकबरपुर"}

When I do console.log() all the array items are shown in at once, what I want is to view them as objects[javascript (aka JSON)] in browser devtools

7
  • 1
    You already converted it. What's your question? Commented Apr 8, 2017 at 18:16
  • Browser devtools not showing objects; if it is already converted how do i display all villages using object call? Commented Apr 8, 2017 at 18:17
  • I'm not sure if I understand what you mean by "display using object call". Commented Apr 8, 2017 at 18:18
  • Do you mean: "I want to use it in javascript as object"? Commented Apr 8, 2017 at 18:22
  • Browser devtools is showing whole data of array in a <body> not showing object view like object1{village.. subdiv...}..object2.. etc. Commented Apr 8, 2017 at 18:23

3 Answers 3

4

Try this one to print in browser devtools :

$myArray = json_encode($myArray, JSON_UNESCAPED_UNICODE);
echo 'village : '.$myArray['village'];
echo 'subdiv : '.$myArray['subdiv'];
Sign up to request clarification or add additional context in comments.

Comments

1

if you want to use the json in javascript you can simply do that:
(I suppose you call that php file directly, not via an ajax call!)

<?php
$conn = mysqli_connect("localhost", "root", "", "mapping") or die ("Error".mysqli_error($conn));
mysqli_set_charset($conn,"utf8");
$sql = "select * from villages";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();
while($row = mysqli_fetch_assoc($result)){
   $myArray[] = $row;
}
mysqli_close($conn);

?>
<script>
// here's the trick!
var villages = <?php echo json_encode($myArray, JSON_UNESCAPED_UNICODE); ?>;
console.log(villages);
</script>

If you use it via an ajax call check out @julekgwa's answer!

Comments

0

use JSON.parse() in your javascript (using jQuery).

//assuming that you are using ajax
$.post('get_villages.php', function(data) {
   var villages = JSON.parse(data);
   for (var village in villages) {
       console.log(village.id + ' ' + village.village + ' ' + village.villageEng);
   }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.