0

i use $.getJSON and here is my php file echo:ing back jsonstring

for($i=1; $i<=10; $i++)
{
    $nr[] = "nr" . $i;
}

$nr = json_encode($nr);

echo "{'result': 'error', 'count': '$nr'}";

how do i loop all the nr through with jquery html()?

i want to echo it back to webpage like:

nr 1 nr 2 nr 3 nr 4 nr 5 nr 6 nr 7 nr 8 nr 9 nr 10

2 Answers 2

1

In jquery, eval the "count" like

array_data=eval(json_data["count"])

php return this

{'result': 'error', 'count': '["nr1","nr2","nr3","nr4","nr5","nr6","nr7","nr8","nr9","nr10"]'}

Once you eval "count"

array_data will be ["nr1","nr2","nr3","nr4","nr5","nr6","nr7","nr8","nr9","nr10"]

After that you can loop array_data

Sign up to request clarification or add additional context in comments.

1 Comment

what if the count variable holds different string values?
0
$.getJSON('file.php', function(data){
  for(var i=0; i<data.count.length; i++){
    alert(i+": "+data.count[i]);
  }
});

edit: The problem is that the way you store it, the php array is stored as a string in the json. Try the following instead:

for($i=1; $i<=10; $i++)
{
    $nr[] = "nr" . $i;
}
$ json = array('result' => 'error', 'count' => $nr);
echo json_encode($json);

Comments

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.