0

I am fetching results from php via ajax. My result in the serverside looks like this.

Array
(
    [0] => IBM Mainframe
    [1] => Intel
    [2] => MIPS
    [3] => MMIX
    [4] => Computer Science (AP/College Intro)
    [5] => Computer Science (College Advanced)
    [6] => Android Programming
)

I am currently printing it out in console.

Serverside : print_r($result);

Clientside :

success: function(r){
                   console.log(r)
               }

I want to fetch the result and within the success convert it into something like this :

var name = [
        "IBM Mainframe",
        "Intel",
        "MIPS",
        "MMIX",
        "Computer Science (AP/College Intro)",
        "Computer Science (College Advanced)",
        "Android Programming"
]

So I can use that variable later

success : function(r){

..............

var name = ....

}
3
  • 2
    Why do you need it be array? Commented Jun 23, 2015 at 10:07
  • I am using autocomplete and will create a search out of that. The autocomplete example is given as arrays. So I want to populate a result iike that. Commented Jun 23, 2015 at 10:08
  • Look at the output from a print_r() !!! Javascript is not going to be able to make any sense of that!!! Encode the array to JSON and then you have a array that javascript can actually make some sense of. I want to fetch the result and within the success convert it into something like this That will all be done in a simple one line command if you send JSON data back to the browser Commented Jun 23, 2015 at 10:22

1 Answer 1

2

Use json_encode from your server script:

Returns the JSON representation of a value

echo json_encode($result, true);

And on client side in success:

r = JSON.parse(r); // Might not required if dataType set as json
console.log(r); // Use it as array here
Sign up to request clarification or add additional context in comments.

4 Comments

@SamirReddy: Yes it is: PHP echo json_encode($array); JS: console.log(r);, depending on the ajax settings, console.log(JSON.parse(r)); will give you exactly what you need
@HarigovindR: JSON == JavaScriptObjectNotation. If you send a JSON string as response, JS just has to parse it to get the desired object (an Array in this case)
@HarigovindR: Then look at the data the OP has PHP side, and what he wants to send over to JS... The only way is JSON, whether OP likes it or not
I hate it when people downvote and don't explain why?

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.