0

Possible Duplicate:
How to return AJAX response Text?

I have a bit of a problem with my getJsonObject function. What I want my code to do is everytime I click next, getJsonObject function gets the next page of articles and, when dom is ready, I display the headline of the article. But if there's an error(like when we run out of pages) then the pageNr won't increment anymore. The problem is that getJsonObject function doesn't return 0 although the alert('return is 0)' does display.

Here is my code:

<html>
    <head>
        <title>World News</title>
        <link rel="stylesheet" type="text/css" href="css/fullWindow.css" />
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
        <script src = "https://raw.github.com/janl/mustache.js/master/mustache.js" type = "text/javascript"></script>
    <body>      
        <section id="mainContent">          
            <div class="prevNext floatRight"><a id="prev" href="#">prev</a> | <a id="next" href="#">next</a></div>
            <section id="news">
                <p id="headline">This is my headline for the moment.</p>

            </section>
        </section>              


    <script type="text/javascript">
        $(document).ready(function(){
            var pageNr = 1;
            var sectionName = "science";
            var err = '2';

            $("#next").click(function(){

                /* it removes the tag 'p' with id="headline" and inserts some other content */
                $.when($('#headline').remove()).then(function(){                            
                    err = getJsonObject(sectionName, pageNr+1);
                    alert('err: '+err);

                    /* if there is no error go to the next page */
                    if(err == '0'){
                        pageNr++;                   
                    }
                });
            });
        });
        function getJsonObject(sectionName, pageNr){        

            $.getJSON('http://content.guardianapis.com/search?q=' + sectionName +      '&page=' + pageNr + '&page-size=5&order-by=relevance&format=json&show-fields=all&date-  id=date%2Flast7days&api-key=gd6ndfndjyr8sd2p3rq3ubkg&callback=?', 
            function(data){                 
                var results;    

                /* I get status == error when I finish iterating the pages*/    
                if(data.response.status != 'error'){            

                    $('#news').append('<p id="headline">'+data.response.results[pageNr].fields.headline+'</p>');                        

                    alert('return is 0');
                    return '0';
                }else{

                    alert('return is 1');           
                    return '1';         
                }
            });
        }
    </script> 
    </body>
</html>

Any ideas why return doesn't work? Thanks.

Community
  • 1
  • 1
Carmen Cojocaru
  • 333
  • 1
  • 7
  • 16

3 Answers3

0

Your getJsonObject(sectionName, pageNr) makes a $.getJSON is a AJAX Asynchronous call

hence the return is not working correctly

frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
0

Because getJSON is executed asynchronously. The common solution is to pass another argument to getJsonObject, a callback, which you'll then call with the value you wanted to return in the first place.

function getJsonObject(sectionName, pageNr, callback){        

    $.getJSON('http://content.guardianapis.com/search?q=' + sectionName +      '&page=' + pageNr + '&page-size=5&order-by=relevance&format=json&show-fields=all&date-  id=date%2Flast7days&api-key=gd6ndfndjyr8sd2p3rq3ubkg&callback=?', 
    function(data){                 
        var results;    

        /* I get status == error when I finish iterating the pages*/    
        if(data.response.status != 'error'){            

            $('#news').append('<p id="headline">'+data.response.results[pageNr].fields.headline+'</p>');                        

            alert('return is 0');
            callback('0');
        }else{

            alert('return is 1');           
            callback('1');         
        }
    });
}

This is also the reason you're passing a callback function to $.getJSON as well. Because behind the scenes it is using something that executes the HTTP request asynchronously.

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • @Fabrizio What my project actually does is to display the articles from a page everytime I click next. So it removes the current displayed articles and appends some others. Well, sometimes it appends without removing the current ones. I don't know why it does that, so I took some measures. You know what might cause that? – Carmen Cojocaru Jan 04 '13 at 14:15
  • @asgoth I know it's an asynchronous call and I tried to add a callback function and it didn't work but now I see I didn't write it properly. Thanks a lot all. – Carmen Cojocaru Jan 04 '13 at 14:23
0

You should rewrite your getJsonObject with a callback function:

function getJsonObject(sectionName, pageNr, callback){   
   $.getJSON(..., function(data) {

      ...
      callback('1');
   }

Using getJsonObject:

getJsonObject(sectionName, pageNr+1, function(err) {
   alert(err);
});
asgoth
  • 35,552
  • 12
  • 89
  • 98