0

Wrapping one's head around the json/ajax/jquery relationship is quite a battle for someone new to it. But what a fun puzzle! One of the most confusing parts has been how to frame this question.

Using php in my module file, utilizing db_query function, the database query has been made, and now we're going to loop through the results, create json data and encode it and send it back to jquery for re-inclusion into our website.

$json = array(); foreach ($query as $row) {

      $fid = $row->thefid;
      $file = file_load($fid);


      $jsonelement=array(

         'title' => $row->title,
         'path' => $file->uri,
         'style_name' => 'swatch'

        );
          array_push($json,$jsonelement);   
    } 

        // encode to json
        $jsonstring = drupal_json_encode($json);

        //output the json string
        drupal_json_output($jsonstring);

This returns this json string:

[{"title":"Test Swatch 5","path":"4DS_AB_BrittanyBeige_CAT.jpg","style_name":"swatch"},{"title":"Test Swatch 6","path":"4DS_AB_ArdennesGray_CAT.jpg","style_name":"swatch"}]

Where I am having trouble, is figuring out how to access each element.

A simple side example to illustrate the issue without an array :

var data = jQuery.parseJSON('{"title":"Test Swatch 5","path":"4DS_AB_BrittanyBeige_CAT.jpg","style_name":"swatch"}');

alert (data.title); data.title returns the string Test Swatch 5, which is what I expect.

However, in the output I have (back at the top of the question) the json object(s) has an extra set of brackets around it suggesting another array that I am not sure how to access, but for now I will call it x.

My question is 2 parts and any one of the solutions will get me to where I need to be.

1) Is there a way to get the key value pairs out of the current output I have already created? Any example would be helpful.

2) Is there a way to frame the output in a way to utilize x as the name of the array so that the values can be accessed via myjson.x.title or myjson.x.path or myjson.x.style_name, etc..?

I noticed a very similar question here with no answer as well https://stackoverflow.com/questions/1607937/how-to-parse-json-array-in-jquery

2

You should be able to access the JSON response objects by saying data[0] and data[1]. These will be the swatches. So instead of namespacing the objects (swatches) by name, as in "myjson.x.path" you will be able to access them by index, as in "myjson[#].path". Does it imply any limitation for your setup?

As per getting the key/value pairs, you should be able to use either jQuery.each function, or native js for (item in coll) traversal.

  • You are absolutely right! Wow, who would have known it could be so simple. I've spent a lot of time trying to make sense of this and you are my new hero. ;) – Starfs Jan 4 '12 at 23:44
  • Glad to help. I hope you use Firebug or another js console. This really helps getting through json chores. – Artur Jan 5 '12 at 0:01
  • Definitely. This tool has been helpful too. It is #1 on google so an obvious first choice. json.parser.online.fr – Starfs Jan 5 '12 at 6:09
0

I do this un drupal 6 (i'm not sure if this work in D7)

//Server side:
//Al your code for generate your json string
drupal_set_header('Content-Type: application/json');
drupal_to_js(array("status","data" => $json));   

And in the client side should be enough with this:

//Client Side:
$.ajax({
  url: Drupal.settings.basePath + 'the/path/to/your/ajax/call',
  dataType: 'json' //this is important jquery parser automatically the response and convert it
  type: 'GET',
  success: function(msg) { 
    console.log(msg.data.title);
    console.log(msg.data.path);
    console.log(msg.data.style_name);
  } 

});

And it's all.

  • Im not sure about the differences in drupal 6 and 7, but I didn't realize parsing the data was unnecessary if the data type has already been declared as json in the ajax request... – Starfs Jan 4 '12 at 23:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.