I have some columns in mysqli that I'm reading from PHP. It's fetching and echoing perfectly.

$results = mysqli_fetch_assoc(mysqli_query($conn, $querystring));
echo json_encode($results);

//$results = {"title":"Sea Shells","location":"./Sea Shells.txt","type":"text"}

however, javascript/jquery then reads the echo as a string:

var contentarr = [];
(ajax magic here, success: function(results){
    contentarr = results;
});
contentarr[0] = {
contentarr[1] = "

how could I directly read an associative array from PHP and map it to an associative array in Javascript? Jquery is the only library I'm using.

  • In JavaScript the equivalents to php's json_[de|en]code() is JSON.stringify and JSON.parse - medium.com/mindorks/… – ivanivan 1 hour ago
  • If you're using jQuery's ajax method you should already get a JSON.parsed object as results - IF you set the right content headers (header('Content-Type: application/json');) in php. – Jeff 1 hour ago
up vote 1 down vote accepted

Change contentarr = results; To contentarr = JSON.parse(results);

https://www.w3schools.com/js/js_json_parse.asp

This converts to a javascipt object.

  • truly a blessing – Omar 1 hour ago

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.