cookie_good's avatar

jQuery.getJSON within a for loop

I searched google for this, and that didn't help, and I looked previous answers, and I didn't find here either.

Basically, I am trying to do a simple jQuery getJSON request. My code is correct if I search for 1 item. But if I iterate through a list of items, it the array is also undefined. I am losing my mind over this.

My pseudocode.


$(document).ready(function(){
    
    for(var i = 0; i<rows; i++){
        
        $(keys[i].input_id_with_hashmark).on('input', function(i){

            $.getJSON("{{ route(json.controller) }}", { term : keys[i].input_value }, function(result){
    
                console.log(result);

            });

        }

    });

});

Clearly this is just not knowing the syntax. For some reason I can't find this anywhere online.

JS is not my strong suit and I read some things about jQuery that weren't true. 1, it's being deprecated. 2. But it's still easy to learn and good for time to market. Hasn't been the case for me. I think I should done this in Vanilla.

0 likes
20 replies
jlrdw's avatar

I have something like:

           .
           . 
           $.ajax({
                url: 'testg',
                type: 'GET',
                data: 'somevar=' + somevar,
                dataType: 'json',
                  success: function (data) {
                    for (var i = 0; i < data.length; i++)
                    {
                        var item = data[i];
                        alert(item.dogname + " " + item.lastedit);
                    }
                },
           .
           . 
           .

Just quick example, but works.

I haven't used jQuery.getJSON, I use ajax like above.

1 like
Scooby's avatar

Is this what you're trying to do?

$(document).ready(function() {
    $('.add-this-class-to-all-inputs').on('input', function() {
        $.getJSON('{{ route(json.controller) }}', { term : $(this).val() }, function(result) {
            console.log(result);
        });
    }
});
cookie_good's avatar

jlrdw: I implemented your code and it worked except variable still came out as undefined. I've been following the trail, and I've determined that is a problem with access properties within an ARRAY of OBJECTS.

Console lets me do this:

keys[1].product_id;

Console won't let me do this.

for( var h=0; h<keys.length; h++){
    keys[h].product_id;
}

Man this is a new language to me.

cookie_good's avatar

Scooby, I don't know if that's what I'm trying to do because I don't what it does. That's not how I understand the use of the variable 'this'. I am applying these event listeners to a somewhat large spreadsheet like-table and I need to create id's dynamically and reference them specifically and dynamically with event listeners.

Scooby's avatar

The on "input" just listens for your input events:

$('.add-this-class-to-all-inputs').on('input', function() {...});

and within that function "this" refers to that particular input the events are taking place in.

cookie_good's avatar

I like the way you think, Scooby! I don't think it will work in my situation though. I might give it a try anyway.

cookie_good's avatar

why can't I iterate through an array of objects? Why does this work:

key[1].product_id

but this is always undefined.

key[i].product_id

Scooby's avatar

You should be able to iterate though an array of objects.. There must be something strange with what you got going on because try this example:

var keys = [{product_id: 1}, {product_id: 2}];

for (var h = 0; h < keys.length; h++) {
    console.log(keys[h].product_id);
}

You should see ids 1 and 2 in the console..

jlrdw's avatar

What are you sending back from your controller do you need to send a Json response back.

cookie_good's avatar

Yes. I am think that this is something to do with jQuery. I did console.log to my iterator and before I add jQuery my iterator is an integer, after I add the event listener, my iterator because some conflagrated javascript object. I can console log my keys object outside jQuery but not inside.

Scooby's avatar

If you're trying to log them to the console inside the jQuery event that's inside your for loop that's just not going to work.

cookie_good's avatar

I guess it had to do with nested functions. I don't know if JS supports nested functions but mine certainly didn't work. Un-nesting them fixed it. It's good because it makes it more difficult to write spaggheti code, but goodness! What a thing not to know when you really need to know it.

jlrdw's avatar

I was also referring to how you return, in my small test:

    public function testg()
    {
        $dogid = Request::input('somevar');
        $dog = Dog::select('dogname', 'comments', 'lastedit')
                ->where('dogid', '<', $dogid)
                ->get()
                ->toArray();
        return Response::json($dog);

    }

Works for eloquent.

But toArray doesn't work direct with query builder, see https://laracasts.com/discuss/channels/guides/to-array

cookie_good's avatar

My controller is returning valid JSON.

the output of route('cats_and_dogs') is

[
    { 
    "owner":"One Good Cookie",
    "dog":"Carpet Madness",
    "cat":"Pepperoni the Nonviolent Cat" 
    }
]
jlrdw's avatar

What had always worked for me is using the toArray() first.

Then I can just loop as needed.

Just the way I learned it and it works.

2 likes
cookie_good's avatar

I was able to loop through the getJSON response, and I was able to loop through the JSON object that I created to hold my selectors and keys, etc.

But once I got past a certain point, it was like the dog ate my homework.

so I have this object.


for(var i = 0; i < someArray.length; i++){

    var myKeys = new Object();

    myKey[i].selector = "#product_id" + i.toString();
    myKey[i].product_id = "product_id" + i.toString();

}

And then when I was accessing it in jQuery, it recognized the selector, but after that, it was like my object disappeared.

for(var i = 0; i < myKey.length; i++){

    $(myKey[i].selector).on('input', function(i){
        // the selector here worked
        document.getElementById(myKey[i].product_id).value = "Wow, this is a lot" + i.toString();
        // here my object suddenly became undefined.
    });
}
jlrdw's avatar

If you only get one result with first there is no looping see this example.

https://laracasts.com/discuss/channels/guides/jquery-get-response

Also I would skip that getJSON and just use ajax like the examples.

Just my opinion.

On my mobile now my laptop is going through a Windows 10 update will take a long time.

I have two or three other good examples of Json looping where it is different for a single row vs several rows.

But it can take a little trial and error to get it just right.

cookie_good's avatar

I had the same error with AJAX. It liked my code inside the loop. It just didn't like the loop. My controller worked fine. The problem was in my JS.

jlrdw's avatar
jlrdw
Best Answer
Level 75

See example again

var item = data[i];
 alert(item.dogname + " " + item.lastedit);

First iteration i=1

Second iteration i=2

ETC.

So second iteration

data[i].dogname

Same as

item.dogname

You will get it just a little trial and error.

data[i] is row

dogname is field in row.

1 like

Please or to participate in this conversation.