0

I am more of a java developer and am having difficulty with javascript callback. I am wondering if any experts here would help me out of my struggle with this code.

I am trying to pull our locations from db and populating in an array. On first load i am trying to refresh all locations and I am having trouble to control the flow of execution and loading values. Below is the code and I have put in the output at the end.

JQUERY CODE:

         // load all locations on first load.
            refreshLocations();
            $("#locInput").autocomplete({source: locationData});
             }); // end of document.ready

            // function to refresh all locations.
             function refreshLocations() {
                 getLocationArray(function(){
                     console.log("firing after getting location array");
                  });
              }
            // function to get the required array of locations.
            function getLocationArray() {
               getJsonValues("GET", "getLocalityData.php", "", getLocalityFromJson);
            }

            // function to pick up localities from json.
            function getLocalityFromJson(json){
                if (!json) {
                    console.log("====> JSON IS NOT DEFINED !! <====");
                    return;
                } else {
                    console.log("json is defined so processing...");
                    var i = 0;
                    $.each(json.listinginfo, function() {
                    var loc = json.listinginfo[i].locality;
                            locationArray[i] = loc;
                            console.log("added location ->" + locationArray[i]);
                            i++;
                    });
                }
                //return locationArray;
            }

            // function to get raw json from db.
            function getJsonValues(type, url, query, getLocalityFromJson) {
                    var json;
                    // if the previous request is still pending abort.
                    if (req !== null)
                        req.abort();
                    var searchString = "";
                    if (query !== "") {
                        searchString = "searchStr" + query;
                    }       

                    console.log("searchString : (" + query + ")");
                    req = $.ajax({
                    type: type,
                            url: url,
                            data: searchString,
                            contentType: "application/json; charset=utf-8",
                            dataType: "text",
                            success: function(result) {
                            json = JSON.parse(result);
                                    console.log("========start of json 
                                                             return============");
                                    console.log(JSON.stringify(json));
                                    console.log("========end of json
                                                               return============");
                                    //return json;
                            }
                    });
                    getLocalityFromJson(json);
                    return json;
            }

the output from above code is as follows:

     searchString : () (18:25:36:473)
     at locality1.php:74
     ====> JSON IS NOT DEFINED !! <==== (18:25:36:518)
     at locality1.php:48
     ========start of json return============ (18:25:37:606)
     at locality1.php:83
     {"listinginfo":[{"listing":"1","locality":"birmingham"},       
     {"listing":"2","locality":"oxford"}]} (18:25:37:624)
     at locality1.php:84
      ========end of json return============ (18:25:37:642)
     at locality1.php:85
      > 

Help will be greatly appreciated.

4 Answers 4

2

call getLocalityFromJson(json); inside your success callback

function getJsonValues(type, url, query, getLocalityFromJson) {
    var json;
    // if the previous request is still pending abort.
    if (req !== null)
        req.abort();
    var searchString = "";
    if (query !== "") {
        searchString = "searchStr" + query;
    }       

    console.log("searchString : (" + query + ")");
    req = $.ajax({
        type: type,
        url: url,
        data: searchString,
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        success: function(result) {
            json = JSON.parse(result);
            console.log("========start of json return============");
            console.log(JSON.stringify(json));
            console.log("========end of json return============");
            //return json;
            getLocalityFromJson(json);
        }
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

done that but the function in the refreshLocations not printing the console log. Are the syntax of all callbacks good? or need modification?
and also please let me know which is the best debug that can I use to debug js in netbeans?
Cause the function in refreshLocations is never called.
0

You need to call getLocalityFromJson(json) and return json inside your ajax success function. Ajax requests are asynchronous, there's no guarantee that the request will be finished by the time you get to the lines getLocalityFromJson(json); return(json); where they are currently.

Comments

0

The call back functions from a jquery ajax call is complete, failure, success, etc.. Success is called after a request is successful, Failure is called if theres something like an error 500, or a 404, or w/e. Complete is Always called after a ajax call.

If you want your code to just follow sequence like in java, throw async: false into your ajax call.. but I wouldnt' recommend this as it defeats the purpose of using this method, and also locks up your browser.

You should make sure you are waiting for the request to finish before moving on - so put code in the success function that you want to run AFTER the request has finished fetching your data.

Comments

0

I think you need to remember Ajax is running async, so you need to follow this thread to execute your refresh.

Comments

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.