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
  • 34,531
  • 8
  • 55
  • 100
D3181
  • 2,037
  • 5
  • 19
  • 44
  • 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
  • 674
  • 1
  • 6
  • 21