Having trouble understanding ajax calls

Terp4Life

basically what I want to do is grab 5 images from the RSS feed and display them afterwards. Unfortunately the RSS items don't have links to images so what I do is grab the article URL from the RSS feed and then I use YQL to scan through the article to see if there is an image. The articles may or may not have an image and there can be 10 or more articles so I have to have a counter to determine when I get 5 images. That's where I'm having the problem, I can't figure out how to update the counter in the success part of the ajax call (I have also tried using an array but it didn't work).

I have seen other examples and I've been trying to do this since yesterday but I have had no luck. Maybe there are other easier ways to do this but I have no clue. Any help would be greatly appreciated.

Please see my code below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>La Retama</title>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
    $(document).bind('mobileinit',function(){
    $.mobile.changePage.defaults.changeHash = false;
    $.mobile.hashListeningEnabled = false;
    $.mobile.pushStateEnabled = false;
    });
    </script>
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
    <link rel="stylesheet" href="./my_style.css"> 
</head>

<body>  
    <div id="home" data-role="page" >
        <div id="my_header" data-role="header">
            <h1>Insert Page Title Here</h1>
        </div>

        <div data-role="main" class="ui-content">

        </div>

        <div id="my_footer" data-role="footer" data-position="fixed">
            <h1>Insert Footer Text Here</h1>
        </div>
    </div> 
</body>

<script>
    var pagina7Arr = [];
    var pagina7SSPArr = [];

    /*Getting the RSS feed*/
    $.ajax({ 
        url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('http://web.paginasiete.bo/rss/feed.html?r=77'),
        dataType : 'jsonp',
        success  : function (data) {

            var myObject = data.responseData.feed.entries;
            var how_many = 0;

            for (var i=0; i < myObject.length;i++){

                var article_url = myObject[i].link;             
                var YQL_link = checkPagina7URL(article_url)     
                var YQL = "https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20data.html.cssselect%20WHERE%20url%3D'"+YQL_link+"'%20AND%20(css%3D'.fotoNota-ext%20'%20OR%20css%3D'.fotoNota')&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
                pagina7Arr.push(YQL)
            }

            pageImages(pagina7Arr)

        }
    });

    /* Here is where I want to store the 5 images */
    function pageImages(input){

        var module = 0;
        var testarr=[];
        for (var i=0; i<input.length; i++){

            $.ajax({ 
                url: input[i],
                dataType : 'jsonp',
                success  : function (data) {

/*I would like to update a counter here or insert images to an array I can use later on*/
                    try{
                        testarr.push(data.query.results.results[0].div.img.src);
                    }catch(err){
                        try{
                            testarr.push(data.query.results.results[1].div.img.src);
                        }catch(err){

                        }
                    }
                }
            });

            console.log("array: "+testarr.length)
        }

    }

    /*Formatting the page URL to insert into YQL call*/

    function checkPagina7URL (data){
        data = data.substr(data.indexOf('.bo')+4,data.length);
        var section = data.substr(0, data.indexOf('/'));
        data = data.substr(data.indexOf('/')+1,data.length)

        var year = data.substr(0,data.indexOf('/'))
        data = data.substr(data.indexOf('/')+1,data.length);

        var month = data.substr(0,2);

        if(month.indexOf('/') != -1){
            month = data.substr(0,1);
        }else{
            month = data.substr(0,2);
        }
        data = data.substr(data.indexOf('/')+1,data.length);

        var day = data.substr(0,2);
        if(day.indexOf('/') != -1){
            day = data.substr(0,1);
        }else{
            day = data.substr(0,2);
        }
        data = data.substr(data.indexOf('/')+1,data.length);

        var page_link = data.substr(data.indexOf('/')+1,data.length);
        var result = "http%3A%2F%2Fwww.paginasiete.bo%2F"+section+"%2F"+year+"%2F"+month+"%2F"+day+"%2F"+page_link;

        return result;  
    }
</script>

</html>
albattran

When you make $.ajax({}) call, the success is called asynchronously. So when you are calling this line: console.log("array: "+testarr.length)

It is too early to count the images, so what is happening here is that you are calling ALL the pages, and fetching the images for all of them. You can certainly do that, but then you have to stop calling testarr.push after your counter becomes >=5. (The counter check should be just before you make such push call)

A more efficient way, would be to fetch only what you need (though will be slower due to syncronousity) and that is by only making subsequent url calls from within the success function of previous call. The above should be easy to do.

You can also do more fancy work (though trickier to code), doing hybrid, fetching 5 urls async, then see in the success callback if you got 5 images you stop, if not, make (5-counter) async requests of the remaining page urls.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Group by and having trouble understanding

Having trouble understanding currying

Having some trouble understanding middleware

Having trouble understanding lbu instruction

Having trouble understanding pointer operations

Having trouble understanding the map() method

Having trouble understanding call signatures

Having trouble understanding sequence diagrams

Having trouble understanding a portion of code

Async and await - having trouble understanding

Having trouble understanding this assembly code

Having trouble submitting a form with AJAX

Having trouble creating a wrapper function for api calls

Having trouble with chaining method calls in Java

Having trouble understanding the logic of this while loop

Having trouble understanding interface/struct relationship

Having trouble understanding .this keyword use in this code

Haskell - Having trouble understanding a small bit of code

Having trouble understanding this javascript destructuring statement

Having trouble understanding Methods and Professor Instruction

Having trouble understanding how running aggregate works

Having trouble understanding function arguments in Python

Having a little trouble understanding objects (Java)

Having trouble understanding tree traversal recursive functions

Having trouble understanding the logic of this infinite loop

Having trouble understanding classes c++

Having trouble understanding pyOpenGl vertices and edges

Having a bit of trouble understanding inheritance? (Java)

I am having trouble understanding the flow of programming