views:

36

answers:

3

If I want to separate out my ajax success function so that it is defined elsewhere in my <script>, does it have to be inside the

$(document).ready(function()
{

section or could it be defined along with non-jQuery javascript functions?

  $.ajax(
  {
    url: '/load_prayer',
    cache: false,
    dataType: 'json',
    type: 'POST',
    data: ({ 'prayerId' : prayerId }),
    success: function(data)
    {
        $('#prayer_date').html(data.Date);
        console.log(data);
    },
    error: function(e, xhr)
    {
        console.log(e);
    }
  });

The reason I don't want to define it inside the call to ajax is it will eventually be a large function and it will be confusing to read if it's mixed in with the other ajax call parameters.

For example, would this work:

$.ajax(
{
    url: '/load_prayer',
    cache: false,
    dataType: 'json',
    type: 'POST',
    data: ({ 'prayerId' : prayerId }),
    success: handlePrayer(data),
    error: function(e, xhr)
    {
        console.log(e);
    }
});

handlePrayer(data)
{
    $('#prayer_date').html(data.Date);
    console.log(data);
}
A: 

i believe you can define the function outside the scope of both the ajax call and the onready.

Orbit
+4  A: 

As long as the function has been loaded before $.ajax is called, it should work. That means it can be outside $(document).ready(...).

With one exception: All variables that need to be accessed need to be outside that success function. The below ajaxCallWorked() function would be able to access outside but not inside.

var outside;

function ajaxCallWorked(data) {
    ...
}

$(document).ready(function() {
    var inside;
    $.ajax({
        ...
        success: ajaxCallWorked,
        ...
    });
}
idealmachine
For pointing out that 'ajaxCallWorked' is just an expression for a function-object (just as a function-expression is...) :-) It's all explained here: http://jibbering.com/faq/notes/closures/ (somewhere)
pst
So, if `ajaxCallWorked` is defined inside `$(document).ready(...)`, it can access inside and the `$.ajax()` call can also access it?
Ken Hume
+4  A: 

You have to change it so its only the function name. Like so:

$.ajax(
{
    url: '/load_prayer',
    cache: false,
    dataType: 'json',
    type: 'POST',
    data: ({ 'prayerId' : prayerId }),
    success: handlePrayer,
    error: function(e, xhr)
    {
        console.log(e);
    }
});

And you need put function where you declare it like so

function handlePrayer(data)
{
    $('#prayer_date').html(data.Date);
    console.log(data);
}
Amir Raminfar