mastersuse
mastersuse

Reputation: 988

How to combine jQuery function with another ajax function?

How do I want to combine below two different functions in same jQuery (document.ready). The 1st function is for Marquee function and the second is some text that will be appear for marquee. The text will GET from backend, at this moment the data (text) is getting locally. Future will GET from Database through API. So I want to use Ajax as well. The text is should be auto load when page is fully loaded. But I don't know what method/attribute (not by clicking, hide, or else) that suitable to use for the Ajax.

HTML

<div class="col-lg-12">
    <div class="alert alert-info" role="alert">
        <div class="m-auto" style="width:100%">
            <span id="announcement"></span>
        </div>
    </div>
</div>

JS

$(document).ready(function(){
    //Function Marquee
    $('#announcement').textMarquee({
        mode:'loop'
    });

    //Function to load Text (I am stuck here)
    $.ajax({
        url: 'data/announcement.json',
        dataType : "json",
        contentType: "application/json",
        dataSrc : "data"
    });
});

Upvotes: 1

Views: 59

Answers (2)

Liad Yogev
Liad Yogev

Reputation: 874

Make the textMarquee function to preform once the ajax has beeen finished:

function getText(success){
    $.ajax({
        url: 'data/announcement.json',
        dataType : "json",
        contentType: "application/json",
        success:success
    });
}
getText(() => {
 $('#announcement').textMarquee({
        mode:'loop'
    });
})

More info about Ajax functionality can be found here

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

For this to work you need to make the AJAX call to get the text first, then put that in the DOM, then instantiate the marquee. It would look something like this:

jQuery(function($) {
  $.ajax({
    url: 'data/announcement.json',
    contentType: "application/json",
    success: function(response) {
      $('#announcement').text(response.yourPropertyHere).textMarquee({
        mode: 'loop'
      });
    }
  });
});

Note that in the $.ajax() call options, dataSrc isn't a valid property and dataType is irrelevant in this instance as you send no data in the request.

Upvotes: 1

Related Questions