Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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". –  Rocket Hazmat May 29 at 18:48

1 Answer 1

up vote 5 down vote accepted

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)));
share|improve this answer
    
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! –  djbhindi May 29 at 18:50
1  
@djbhindi If the answer solved your question, please click the check mark to accept it. Please see "what does it mean to accept an answer?" and the linked articles for more information. –  MattDMo May 30 at 1:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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