0

I know there are lots of questions and answers on this topic but none that are answering my specific query - I've been searching and going around in circles for a month!

I'm getting values from may database using php and returning via json:

    $staff_list = array(
          "name" => $staff_names,
          "id" => $staff_ids,
          "img" => $staff_imgs,
          "typeID" => $staff_types,
    );

    print(json_encode($staff_list));

I'm pulling into a javascript:

$.getJSON(requestURL, function(data) {
    if( data.errorResponse ) {
            element.html("<p>(" + data.errorResponse.message + ")</p>");
    } else {
        $('#designeesloading').remove();

        $.each(data, function(i, field){
            $.each(field, function(x, value){
                haystack.push({
                  i:value //this should put into 4 arrays as per above shouldn't it?
                });
            });
        });


    } //errorResponse else

  }); //getJSON

But instead of haystack now being 25 elements (as there are 25 names, images etc), when I go to extract here, it goes through 100 something times (which I imagine is 4 times x 25):

(this triggers each time someone types in search box):

    $.each(haystack, function(i,v) { //this goes through 100 times instead of 25
    if ((v['name'].toLowerCase().indexOf(needle) >= 0)) {
      choices.push({ //only want to add to choices if what they are searching for is found
        "id":v['id'],
        "name":v['name'],
        "typeID":v['typeID'],
        "img":v['img']
      });
      resultflag++;
    }
    });

It's here if anyone wants a look. So frustrating, I'd have this done in 5 minutes in PHP.

http://cybril.com/donation/donate.php

Thanks in advance for any help.

2
  • You're pushing everything into the top level of the haystack array, you're not pushing into sub-elements. Commented Sep 14, 2013 at 1:03
  • I tried to find the JS code you specified on your website but could not find it. Can you provide a jsfiddle ? Commented Sep 14, 2013 at 1:05

1 Answer 1

0

There are two problems with your code. First, you're just pushing everything onto haystack, you're not creating nested objects to hold each staff member. Second, in an object literal like { key: val }, i is not evaluated, it's treated as a literal name; only val is evaluated. If you want to use a computed key, you must use square bracket notation.

    $.each(data, function(i, field){
        $.each(field, function(x, value){
            if (!haystack[x]) {
                haystack[x] = {};
            }
            haystack[x][i] = value;
        });
    });
0

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.