0

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.

2
  • In JavaScript the equivalents to php's json_[de|en]code() is JSON.stringify and JSON.parse - medium.com/mindorks/… Commented Dec 16, 2018 at 1:39
  • 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. Commented Dec 16, 2018 at 1:43

1 Answer 1

1

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

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

This converts to a javascipt object.

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

1 Comment

truly a blessing

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.