0

I have the following in php:

$query = mysql_query($sql);
$rows = mysql_num_rows($query); 
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{

    $courseData = array(
    'course_name'=>$fetch['course_name'],
    'training_field'=>$fetch['training_field'],
    'speciality_field'=>$fetch['speciality_field'],
    'language'=>$fetch['language'],
    'description'=>$fetch['description'],
    'type'=>$fetch['type'],
    );

    array_push($data['course_data'],$courseData);
}

echo json_encode($data);

when I receive the result of this script in jquery (using post)

I log it using :

console.log(data['course_data']);

and the output is :

[Object { course_name="Introduction to C++",  training_field="Engineering" ,  speciality_field="Software",  more...}]

But I can't seem to figure out how to access the elements.

I tried

data['course_data'].course_name

data['course_data']['course_name']

Nothing worked. Any ideas

5 Answers 5

1

When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].

If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:

for (i in data['course_data']) {
  console.log(data['course_data'][i]['course_name']);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should specify the index in the first array for instance

data['course_data'][0]['course_name'];

you could make it better if you had defined the first array just as variable not a variable within an array

Comments

0
$data['course_data'][0]['course_name'] 

should do the trick. If not please send the output of var_dump($data)

1 Comment

I think this is a JS problem, not a PHP
0

Assuming the PHP code is correct, you will receive a JSON data like:

{
    "course_num":34,
    "course_data":[
        {
            "course_name":"name_value",
            ....
        },
        ....etc (other object based on SQL result)
    ]
}

So, if you want to access to the total number of result:

data.course_num

If you want to access to the first element of the list of result:

data.course_data[0]

If you want to access to the name of the first element of the list of result:

data.course_data[0].course_name

or

data.course_data[0]['course_name']

Comments

0

use jquery's parseJSON method to get all the goodies out of the json object...

http://api.jquery.com/jQuery.parseJSON/

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.