Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

"this is undefined" error in JS

Hi, I can't seem to figure out this problem where the below code works when the "for loop" is disabled, and the attributes "locations" and "startAddress" are just simple strings. But if they are not, I am getting a "this is undefined" error when the ajax post request is submitted. Do you have any ideas why would this be?

Thanks!

    // create an event handler for the save route button

    $("#saveRouteButton").click(function(){
        var saveRouteName = $("#saveRouteNameField").val();
        if (!saveRouteName) {
            alert("Please supply a proper name to be submitted to the database");
        } else {
            var routeLength = directionsDisplay.getDirections().routes[0].legs.length;
            var returnRoute = {
                alias: null,
                locations : [], // make this a string - it works!
                startAddresses : [], // make this a string - it works!
            };

            // disable this - it works!
            for (var i = 0; i < routeLength; i++){

                returnRoute.locations[i] = directionsDisplay.getDirections().routes[0].legs[i].start_location
                returnRoute.startAddresses[i] = directionsDisplay.getDirections().routes[0].legs[i].start_address
            };


            route_info = returnRoute;
            route_info.alias = saveRouteName;

            alert(route_info.alias);
            alert(route_info.locations);
            alert($.isPlainObject(route_info))

            $.ajax({
                url: "save_route/", 
                type: "POST",
                data : route_info, 
                success: function(data){
                            if (data != "None") {
                                $("#savedRoutesList").append('<li class="savedRoutesListItem">' 
                                + data + '</li>');
                            }
                            else {alert("You need to enter a route name");}
                        }
                });
        }
        return false;
    });

the error originates from the : google maps main js

  • line 13