1

I've searched through the site and can't see a question quite like mine so I hope this isn't a copy.

So I've got a PHP script which is supposed to return a JSON array to my AJAX, and I want to use the array to generate a URL.

However, even though I'm pretty sure I've got an array on the PHP end, when I json_encode I'm getting a simple string out on the other end.

PHP Code:

    $n = 10;
    $all_titles = array();

    while($row = mysqli_fetch_array($result)) {
        $title = trim($row['Job Title']);
        if(array_key_exists($title, $all_titles)) {
            ++$all_titles[$title];
        } else {
            $all_titles[$title] = 1;
        }
    }

    arsort($all_titles);
    $top_titles = array_slice($all_titles, 0, $n);
    $title_list = array();

    foreach (array_values($top_titles) as $key => $val) {
        array_push($title_list, array_keys($top_titles)[$key]);
    }
    echo json_encode($title_list);

These array operations seem to be working so far, based on other tests I've done, so I'm pretty sure that $title_list is an array.

Here is my JS:

    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        alert("Generated URL: " + URL_gen(xmlhttp.responseText));
      }
    }

And finally where the problem arises:

function URL_gen(list) {
    var url = list[2];
    return url;
}

I have varied the number in list[#] (list[0], list[1], etc.) and each one is a character, meaning list (which is passed in from onreadystatechange as the responsetext from the PHP function above) is a string, not a JSON array.

Any suggestions?

1
  • 1
    JSON is by definition a string. It's a string format used to transport data. Its format is a (strict) subset of JavaScript's array/object notation. There is no such thing as a "JSON array". You either have a "JavaScript array" or a "JSON string". Commented May 29, 2014 at 18:48

1 Answer 1

7

That's what it does. Returns a string. You need to parse it on the client side.

alert("Generated URL: " + URL_gen(JSON.parse(xmlhttp.responseText)));
Sign up to request clarification or add additional context in comments.

1 Comment

Oh jeez. I'm so dumb, I was reading only through the json_encode documentation and I didn't look at what had to be done on the other end. Thank you thank you thank you!

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.