0

I'm having an issue returning a value from PHP to Javascript. I have encoded the PHP array like so :

echo json_encode($myArray);

And on the Javascript side i do this within the $.ajax method:

success:function (data) {
  alert(data);
}  

This works and it alerts the returned array, however when i try to then set my Javascript array to the value of data :

success:function (data) {
  myArray = data;
}  

This completely breaks my looping operation and so instead of printing out for example:

This is a test

It will print:

t,h,i,s,i,s,a,t,e,s,t

and the length of the array rather than being 4, for 4 words it is 16+ including the square brackets etc. How can i reuse the json encoded array once it has been recieved by javascript and maintain its structure?

Ivan
  • 24,563
  • 6
  • 44
  • 76
D3181
  • 1,977
  • 5
  • 15
  • 39
  • You probably need to to do myArray = JSON.parse(data); Since it is technically coming in as a string, not as an object. – Architect Nate Aug 25 '16 at 17:31
  • you were right that fixed it, if you post it as an answer i will accept it. Thanks for the help – D3181 Aug 25 '16 at 17:33

1 Answers1

3

Related: Parse JSON in JavaScript?

What you are looking for:

myArray = JSON.parse(data);

Community
  • 1
  • 1
Architect Nate
  • 654
  • 1
  • 6
  • 21