Synchronous problem with ajax - Quote Machine

Synchronous problem with ajax - Quote Machine
0.0 0

#1

Hi, I have the following code:

    //GET QUOTE WHEN BUTTON IS CLICKED
    jQuery('#button').on('click', function(){
        
        jQuery.ajax({
        url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
        type: 'GET',
        dataType: "jsonp",
        }); 
    
        function mycallback(json){
        document.getElementById('quote').innerHTML = json[0].content;
        
        };
        
        var quote = document.getElementById('quote').innerHTML;
        document.getElementById('anchor').href =  'https://twitter.com/intent/tweet?text=' + quote;
    })

The code works fine. My problem is: when I get the quote inside the quote ID at the end of the code, it gets the previous quote, and not the current one showing on the screen. I know this happens because the mycallback function takes more time and the code jumps to the next part of the code, but I don’t know how to fix it. I’ve tried the then() method, but it didn’t work. Could somebody help me please? All day stuck on it.


#2

Why not put that part of the code in the callback is well?


#3

I’ve tried that Ben, but the it doesn’t work. Do you know any other way?


#4

Simple working example: https://codepen.io/benjaminvanzwienen/pen/LeqOBG


#5

The dataType: ‘jsonp’ and the callback are not necessary. You can use dataType: ‘json’, but make sure you add cache: false so you get a new quote each time instead of same one after the first click of the button.

  $.ajax({
    url:
      "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1",
    type: "GET",
    dataType: "json",
    success: function(json){
      document.getElementById("quote").innerHTML = json[0].content;
      document.getElementById("anchor").href =
    "https://twitter.com/intent/tweet?text=" + json[0].content;
    }
  });