0

In my php:

$result = $conn->query("select address, lat, lang from user where phoneno = '" . $phoneno. "'");


$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '"'  . $rs["address"] . '",';
$outp .= '' . $rs["lat"] . ',';
$outp .= ''   . $rs["lang"]        . '';
}
$outp .="]";

The value output from my php: ["Tampines Street 86, Singapore",1.3497658,103.9274115]

var locations = [
  ['Bondi Beach', -33.890542, 151.274856],
  ['Coogee Beach', -33.923036, 151.259052],
  ['Cronulla Beach', -34.028249, 151.157507],
  ['Manly Beach', -33.80010128657071, 151.28747820854187],
  ['Maroubra Beach', -33.950198, 151.259302]
];

The above is an example of how I want my php output value to be for my var locations. How can I do this?

Xinee
  • 61
  • 1
  • 10

1 Answers1

1

Do not invent the wheel. Use json_encode.

PHP:

$locs = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    $locs[] = array($rs["address"], $rs["lat"], $rs["lang"]);
}

JS:

var locations = <?php echo json_encode($locs)?>;
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • the javascript is in a html5 file which is separated from the php. I'm building a mobile app – Xinee Dec 07 '16 at 17:33
  • And what? You output nothing from php? Then why do you use php? – u_mulder Dec 07 '16 at 17:37
  • I usually do https request from my html – Xinee Dec 07 '16 at 17:39
  • function showcontact(){ var xmlhttp = new XMLHttpRequest(); var url = serverURL() + "/showcontact.php"; url += "?phoneno=" + localStorage.getItem("phoneno"); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { showcontactresult(xmlhttp.responseText); } }; xmlhttp.open("GET", url, true); xmlhttp.send(); } – Xinee Dec 07 '16 at 17:40
  • function showcontactresult(response) { var arr = JSON.parse(response); var tbl=$("
    ").attr("id","thisForm"); $("#div1").append(tbl); for(var i = 0; i < arr.length; i++ ){ var tr=""; var chk=""+"" + ""; var td1=""+arr[i].contactname+""; $("#thisForm").append(tr+chk+td1); } }
    – Xinee Dec 07 '16 at 17:40
  • Something like that – Xinee Dec 07 '16 at 17:40
  • Then your `$outp = json_encode($locs)`. And I advise you to __edit__ question instead posting codes in comments, they're __unreadable__. – u_mulder Dec 07 '16 at 17:54
  • Okay so sorry! Anyway my problem is that becoz i cant do the functions inside var location which is why I'm stuck. Sorry I'm a beginner in coding – Xinee Dec 07 '16 at 18:40