0

I have included an external javascript file whose contents are:

function getTopNews(){
  $.ajax({
    url: 'http://api.feedzilla.com/v1/categories/26/articles.json',
    type: 'GET',
    dataType: 'json',

    success: function(response){
        alert("Got top news!");
    },

    error: function(){
        alert("There was an error!");
    },

    complete: function(){
        alert('Executed');
    }
  });
}

Now the above javascript file is included in another file where I have written this code:

$(document).ready(getTopNews);  // works

Now suppose my getTopNews is defined like getTopNews(var newsId), then how should I call it? I have tried following and it does not work:

$(document).ready(getTopNews(26));  // does not work

$(document).ready(fucntion(){  // does not work
  $(this).getTopNews(26)
});

Both of these do not work for me. Help!

3
  • 1
    You have a typo (fucnition), maybe that's why it's not working? Did you check the browser console for errors? Commented Jun 23, 2013 at 21:10
  • @bfavaretto: Good one, but that typo is here, not in actual code :D Commented Jun 23, 2013 at 21:17
  • 2
    The tip about the browser console is still valid though. Always check that, it will catch all syntax errors like getTopNews(var newsId). Commented Jun 23, 2013 at 21:19

2 Answers 2

4

What abt this ? getTopNews isnt an object of document so it wont come under $(this) :

$(document).ready(function(){
  getTopNews(26);
});
Sign up to request clarification or add additional context in comments.

6 Comments

@stalin any console erros?
getTopNews function have to be defined before you call it. If it's the case, this answer works for sure.
"getTopNews isnt an object of document so it wont come under $(this)" - Even if it was a property of document it still wouldn't be accessible from $(this), because $(this) returns a jQuery object, not document.
I am including the js containing getTopNews() function before $(document).ready(), it works without argument but not with argument.
@passionateCoder: you are correct. this is the correct way. 'var' was the problem
|
3

"Now suppose my getTopNews is defined like getTopNews(var newsId)"

Then what you'd have is a syntax error and the code wouldn't work. Remove the var:

function getTopNews(newsId) {
   // your code here
}

To call that on ready, do this:

$(document).ready(function(){
  getTopNews(26);
});

Note that in your code when you did something similar you had a typo on this line:

$(document).ready(fucntion(){  // does not work

...where you spelled function as fucntion.

Note that both problems should've been reported in your browser's console.

1 Comment

Thanks @bfavaretto, I didn't notice that at first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.