?
Solved

2 references to same variable returning different values

Posted on 2011-04-28
1
Medium Priority
?
211 Views
Last Modified: 2012-05-11
Ok I have a function that's driving my nutty.

I get 2 different values for a variable (recipecount) on sequential calls

Note the area on line  108

 
alert(recipecount);  //Returns 0
            alert(recipecount);  //Returns 5

Open in new window


Here is the complete function

 
function doSearch() {
        try {

            // Set URL We Want To Fetch
            var url = 'http://www.eatchicken.com/chickenhookups/chickenhookupsresults.aspx?find=';
            // Set Initial Recipe Count To 0
            var recipecount = 0;
            // Random Recipe Number
            var randomseed;
            // Records Requested
            var recordsrequested = 3;
            // Image for Popup
            var hookupimage;
            // What to Search For
            var query = $("#find").val();
            // What Category
            var cat = $('input[name=drpPrep]:checked').val();


            //Alert if No Category Selected
            if (cat == "" || cat == null) {
                alert('Be sure to check a chicken type!');
                return false;
            }


            $.getJSON(url + query + '&catname=' + cat + '&groupid=5' + '&callback=?', function (json) {
                var randomseed;

                // Treat recipe as an array even though it will always return 1 result
                $.each(json[0].Recipe, function (i, recipe) {
                    // RecipeCount will be used as ceiling number for randomize
                    recipecount++
                    // End Each
                     });


                //Pick a Random Recipe From Results
                randomseed = Math.floor(Math.random() * recipecount);

                //Update Thickbox Popup

                //Map Choices To Image 
                switch (cat) {
                    case 'Baked':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Baked.png";
                        break;
                    case '|Broil':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Broil.png";
                        break;
                    case 'Fried':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Fried.png";
                        break;
                    case 'Grill':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Grill.png";
                        break;
                    case 'Marinade':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Marinade.png";
                        break;
                    default:
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Baked.png";
                        //End Switch
                }


                //Set Image   
                $("#match_result_image").attr("src", hookupimage);

                // Set Url
                $("a#match_result_url").attr("href", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Set Recipe Title
                $("#match_result_title").html(json[0].Recipe[randomseed].RecipeName);

                // Facebook Link
                $("#st_facebook").attr("st-url", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Twitter Link
                $("#st_twitter").attr("st-url", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Email Link
                $("#st_email").attr("st-url", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Dynamically load share this, we have to back load this to fire after we have changed the fields.
                var switchTo5x = true;

                $.getScript('http://w.sharethis.com/button/buttons.js', function () {
                    stLight.options({
                        publisher: '6ddf0f4e-d8c8-4485-abcb-2ddbb25c3ae8'
                    });
                });


                //Close Json
            });


            //************************************************
            // PROBLEM IS HERE
            //************************************************


            alert(recipecount);  //Returns 0
            alert(recipecount);  //Returns 5
            

            if (recipecount < 1) {
               alert('There are so many great chicken hookups in the world but you did not find one. Maybe you should be a bit less picky with your keyword.');

               return false;

            }


            //Pop Up Thickbox
            fireThickBox();
            //Exit Function
            return true;

       } 
        catch (ex) {

            alert('There was an error:' + ex);
            return false;
            }
    
    }

Open in new window


I'm assuming this is because of the inline JSONP function but I can't figure out why.

Any ideas?

Thanks

Michael

0
Comment
Question by:mcunn
1 Comment
 
LVL 82

Accepted Solution

by:
hielo earned 2000 total points
ID: 35485377
$.getJSON() sends an ASYNCHRONOUS request. So when you do the first alert() you see zero because the ajax request has not completed and you see that alert(). While that FIRST alert is being displayed, the ajax request is STILL processing in the background. By the time you dismiss the first alert, the ajax request completes in the background and the variable gets updated. So the second alert sees the "correct"/expected number of items.

You need to move those statements BEFORE the "close Json" line:
function doSearch() {
        try {

            // Set URL We Want To Fetch
            var url = 'http://www.eatchicken.com/chickenhookups/chickenhookupsresults.aspx?find=';
            // Set Initial Recipe Count To 0
            var recipecount = 0;
            // Random Recipe Number
            var randomseed;
            // Records Requested
            var recordsrequested = 3;
            // Image for Popup
            var hookupimage;
            // What to Search For
            var query = $("#find").val();
            // What Category
            var cat = $('input[name=drpPrep]:checked').val();


            //Alert if No Category Selected
            if (cat == "" || cat == null) {
                alert('Be sure to check a chicken type!');
                return false;
            }


            $.getJSON(url + query + '&catname=' + cat + '&groupid=5' + '&callback=?', function (json) {
                var randomseed;

                // Treat recipe as an array even though it will always return 1 result
                $.each(json[0].Recipe, function (i, recipe) {
                    // RecipeCount will be used as ceiling number for randomize
                    recipecount++
                    // End Each
                     });


                //Pick a Random Recipe From Results
                randomseed = Math.floor(Math.random() * recipecount);

                //Update Thickbox Popup

                //Map Choices To Image 
                switch (cat) {
                    case 'Baked':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Baked.png";
                        break;
                    case '|Broil':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Broil.png";
                        break;
                    case 'Fried':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Fried.png";
                        break;
                    case 'Grill':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Grill.png";
                        break;
                    case 'Marinade':
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Marinade.png";
                        break;
                    default:
                        hookupimage = "http://www.chickenhookups.com/wp-content/themes/chickenhookups_theme/images/Baked.png";
                        //End Switch
                }


                //Set Image   
                $("#match_result_image").attr("src", hookupimage);

                // Set Url
                $("a#match_result_url").attr("href", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Set Recipe Title
                $("#match_result_title").html(json[0].Recipe[randomseed].RecipeName);

                // Facebook Link
                $("#st_facebook").attr("st-url", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Twitter Link
                $("#st_twitter").attr("st-url", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Email Link
                $("#st_email").attr("st-url", "http://www.eatchicken.com/recipedetail.aspx?id=" + json[0].Recipe[randomseed].ID);

                // Dynamically load share this, we have to back load this to fire after we have changed the fields.
                var switchTo5x = true;

                $.getScript('http://w.sharethis.com/button/buttons.js', function () {
                    stLight.options({
                        publisher: '6ddf0f4e-d8c8-4485-abcb-2ddbb25c3ae8'
                    });
                });


                 //************************************************
                 // PROBLEM IS HERE
                 //************************************************
     
     
                 alert(recipecount);  //Returns 0
                 alert(recipecount);  //Returns 5
                 
     
                 if (recipecount < 1) {
                    alert('There are so many great chicken hookups in the world but you did not find one. Maybe you should be a bit less picky with your keyword.');
     
                    return false;
     
                 }
     
     
                 //Pop Up Thickbox
                 fireThickBox();
                 //Exit Function
                 return true;
                //Close Json
            });



       } 
        catch (ex) {

            alert('There was an error:' + ex);
            return false;
            }
    
    }

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The most up-to-date version of this article is on my Blog https://iconoun.com/blog/
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question