0

I have a javascript which gets JSON data from URL and loads the data on to the page, then I want to call another javascript to add the slide effects.

There is a simpler solution, i.e using setTimeout. But this solution is not complete because getting data from a URL does not have a fixed amount of time. It varies on every call.

Hence I want to check if my first javascript has loaded and then I want to call the second javascript.

6
  • 3
    how do you get the JSON ? Usually you use an AJAX request, which provides an event for when the request is completed.. Commented Jul 23, 2012 at 23:42
  • @GabyakaG.Petrioli by ajax calls, $.ajax, which on success calls a function A. I want this function A to be done then I want to call function B. Commented Jul 23, 2012 at 23:44
  • +1 to Gaby. Definitely use ajax and it's success callback, definitely. Commented Jul 23, 2012 at 23:45
  • 1
    @Lings, at the end of the success function call the next one .. If you could provide some source code it would help describe the solution better.. Commented Jul 23, 2012 at 23:45
  • Isn't it as simple as funcA(); funcB();? If the functions are not doing any asynchronous stuff, function calls are sequential. Commented Jul 23, 2012 at 23:49

1 Answer 1

2

JavaScript is an asynchronous language, or at least, its HTTP API is (mostly) asynchronous.

You shouldn't use settimeout, but you should use asynchronous chaining instead for building a list of causal events. There's a big bunch of libraries out there to assist this, like http://www.infoq.com/articles/surviving-asynchronous-programming-in-javascript

If you're loading content from your own site, then there'll be an onsuccess/oncomplete event when the JSON finally gets loaded, you can assign a callback to it. How it is actually called depends on your javascript framework if you use one.

If you're using data from a remote site in a format called JSONP, you're to define a callback to it, it should be a public function name, like onMyDataArrived. You should add your callback code there. Some frameworks hide this detail from you, they generate a random function which they remove when the data has arrived, and provide an API similar to onSuccess / onComplete instead.

Nowadays, the most popular javascript framework is jQuery, where you can do such things, like:

$.ajax({
    url: 'give_me_my_json.php',
    dataType: 'json', 
    success: function(data){
         //call your second javascript
    }, 
    error: function(){
         //WHOOOPSIE... data could not be loaded
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.