0

I just can't get the getCategory function to return anything apart from undefined or false. I've stepped through in the console and all the data is there. I'm still unsure on the best way to make functions call syncronosly

function getCategory(url) {

    if ( url ) {
        let message = false
        $.ajax({
            url: url,
            global: false,
            type: 'GET',
            dataType: 'json',
        }).done( function(data) {
            message = `<a class="post__category post__link" href="${data[0].link}">${data[0].name}</a>`
            return message
        })
    } else {
        return ''
    }
}

function posts() {

    $.get(WPPosts, data => {

        data.forEach( d => {

            const excerpt           = d.excerpt.rendered.substr(0, characterCount)
            const featuredImage     = d._links['wp:featuredmedia']
            const featuredImageURL  = featuredImage ? featuredImage[0].href : ''

            const terms             = d._links['wp:term']
            const category          = terms.filter( term => term.taxonomy === 'category')
            const categoryURL       = category[0].href



            let post = `<article class="column">
                            <div class="decoration decoration__paper decoration__tape decoration__tape--left text-center post">

                                <a href="${d.link}">
                                    ${ getFeaturedImage(featuredImageURL) }
                                </a>

                                <h2 class="post__title">${d.title.rendered}</h2>

                                <p>
                                    ${d.date_gmt}
                                    ${ getCategory(categoryURL) }
                                </p>

                                <div class="post__excerpt">
                                    ${excerpt}... <a class="post__link" href="${d.link}">Read more</a>
                                </div>
                            </div>
                        </article>`

            post = $.parseHTML( post )
            postsWrapper.append(post)
        });
    })
}

I am trying to avoid the { async: false } option

a-windett
  • 151
  • 1
  • 7
  • 1
    You need to add a callback to `getCategory` function. Ajax is by definition an asynchronous call (acronym for "asynchronous JavaScript and XML"), you cannot make it synchronous. – Juan Stiza Jun 13 '16 at 15:10
  • Well, yes, but: http://stackoverflow.com/questions/1478295/what-does-async-false-do-in-jquery-ajax – Juan Stiza Jun 13 '16 at 15:11
  • 1
    Stapal: I tried that, buts its been depricated for a while – a-windett Jun 13 '16 at 15:11
  • 1
    Possible duplicate of [jQuery: Performing synchronous AJAX requests](http://stackoverflow.com/questions/6685249/jquery-performing-synchronous-ajax-requests) – Mike Perrenoud Jun 13 '16 at 15:11
  • Juan Stiza, would you be able to give an example...? – a-windett Jun 13 '16 at 15:12
  • _"I am trying to avoid the `{ async: false }` option"_ - [rightly so](https://xhr.spec.whatwg.org/#sync-warning) – James Thorpe Jun 13 '16 at 15:18
  • ^^ I don't get it – you want to make it synchronous, but don't want to use the option that would specifically make it synchronous? – JJJ Jun 13 '16 at 15:18
  • That trailing comma on the last property will get you sometimes `dataType: 'json',` – Mark Schultheiss Jun 13 '16 at 15:19
  • I don't think the question you ask is the right one, instead perhaps you should inquire about how to properly handle the asynchronous request process and results. – Mark Schultheiss Jun 13 '16 at 19:53
  • Ok, What is the best way to handle an ajax request that then triggers another by the data that is provided from the first. I am using the WP JSON API plugin, from the initial post request I get the JSON url for the featured image. I am them doing another AJAX request to this url to get the featured image source.... – a-windett Jun 13 '16 at 20:09

1 Answers1

0

Issue here is there are many get calls happening by 'getCategory' after first get call.

We can modify logic so that data inside anchor tag gets loaded once get call relevant to that anchor tag is done.

Modifying anchor tag to give it a unique id:(Use any ID you may want to)

  <a href="${d.link}" id="${d.link}">
                                    Loding ..${ getFeaturedImage(featuredImageURL,${d.link}) }
                                </a>

Then modify function to read id:

function getCategory(url,id) {

    if ( url ) {
        let message = '';
        $.ajax({
            url: url,
            global: false,
            type: 'GET',
            dataType: 'json',
        }).done( function(data) {
            message = `<a class="post__category post__link" href="${data[0].link}">${data[0].name}</a>`

            $("#"+id).html(message ); // append data to anchor tag rather than returning.
        })
    } else {
       $("#"+id).html(''); 
    }
}
Don
  • 1,334
  • 1
  • 10
  • 18
  • 2
    @a-windett, indeed, but you should not rely on the return value, because you get it *before* the Ajax response is available. The action happens in the `done` function. – trincot Jun 13 '16 at 15:23
  • We don't need to return anything. I modified my answer – Don Jun 13 '16 at 15:27
  • It all depends on whether you want to know when you got that Url or not. If you want control, you'll need the callback. – Juan Stiza Jun 13 '16 at 15:33
  • So the above works, however while waiting for the request to be sent back undefined appears on the page. I understand why this is happening, but don't know how to fix it – a-windett Jun 13 '16 at 15:36
  • which place exactly you are getting undefined ? – Don Jun 13 '16 at 15:50
  • On the initial page render. Then two seconds or so later the correct data is rendered. Is there a way the nothing is rendered at first - instead of underfunded – a-windett Jun 13 '16 at 16:05
  • I mean which div you are seeing undefined rendered? – Don Jun 13 '16 at 16:07
  • Where the html is being append to in the above answer – a-windett Jun 13 '16 at 16:19
  • try modifying let message = false to let message = 'Loading..' – Don Jun 13 '16 at 16:31
  • Oh yeah, I'm on mobile but that sounds look it should do it – a-windett Jun 13 '16 at 16:33