0

I'm trying to get a PHP array with AJAX and turn it into a JSON array.

Right now in the external file I'm echoing the php array with JSON encoding:

echo json_encode($palabras);

Then on the main file I get the response and assign it to variable "jsarray ";

success:function(data_response){
    jsarray = data_response;
    }});

However I can't access jsarray as an array. How can I turn it into a proper array I can access?

4
  • 1
    Are you requesting a JSON response? Commented Dec 18, 2011 at 1:15
  • what is the value of data_response ?? Commented Dec 18, 2011 at 1:17
  • Add console.log(jsarray) in the success function and have a look. If nothing is logged then sucess was not called -> error occured. In that case edit your question and add exact output from your php page echoing JSON and also client-side code that is using AJAX. Commented Dec 18, 2011 at 1:20
  • the PHP is echoing: [{"palabra":"uno"},{"palabra":"dos"}] Commented Dec 18, 2011 at 1:40

2 Answers 2

1

You can use eval:

eval(data_response)

You can use jquery.parseJSON too:

var obj = jQuery.parseJSON(data_response);
Sign up to request clarification or add additional context in comments.

2 Comments

-1 for immediately suggesting heavy libraries such as jQuery.
@Tom what's wrong with mentioning jQuery as an additional solution? +1 to even out.
0

If you are 100% certain you can trust the contents of data_response, you can simply evaluate it.

I don't know what library you are using, but that should be something like jsarray = eval(data_response.responseText);

WARNING: This does pose a security risk if a third party can inject data into data_response. Since it's a simple eval(), any javascript code can be executed.

I believe that most modern webbrowsers provide a JSON library to work around this issue. You should be able to use JSON.parse(data_response.responseText) in that case. However, that will not work on all browsers.

2 Comments

I think that might fix my problem, but I couldn't implement it. alert(data_response) produces: [{"palabra":"aa"}]. If I use eval or JSON.parse I get: [object Object]. But I can't manage to access the object. How can I make get the value on key 1 or "palabra" for example? thanks
That looks like an array of objects. If you want to get the first object's value for palabra, you'll want jsarray[0]['palabra']. If you want all palabra values in your arrays, you'll want to iterate: for (var i = 0; i < jsarray.length; i++) { var item = jsarray[i]; alert(item['palabra']); }

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.