0

I have the following JavaScript function:

    $('div[id^="event"]').each(function( index ) {
    fullID = $(this).attr('id');
    object = $(this);
    idOnly = fullID.replace( /^\D+/g, '');
    var jqxhr = $.ajax({
    type: 'POST',
    url: '/welcome',
    data: { 
        'lat': lat, 
        'lon': lon ,
        'eventID': idOnly
    },
    success: function(msg){
        object.show();
        
  }
});
                
});

What I want this piece of code to do is the following :

For each div id which has an ID which starts with event, get the number portion of the div element id (for example one could have an id of 'event39410') - so get the '39410' piece - send that along with two variables to an AJAX service - and when the response comes back, show the div with id 'event39410'.

The ajax component works fine - the problem is however, that if i have 10 of these event tags, I get 10 ajax calls to my backend, but I only ever get the last 'event' div shown - which suggests that by the time the success function gets called the object is always referencing the last entry in the loop.

Can somebody help me to fix this variable scoping issue?

0

1 Answer 1

2

You need var in front of those 3 globals variables!

$('div[id^="event"]').each(function( index ) {
    var fullID = this.id;
    var object = $(this);
    var idOnly = fullID.replace(/^\D+/g, '');
    var jqxhr = $.ajax({
        type: 'POST',
        url: '/welcome',
        data: { 
            'lat': lat, 
            'lon': lon ,
            'eventID': idOnly
        },
        success: function(msg){
            object.show();

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

1 Comment

Boom! Too much switching between different languages! Thank you

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.