-3

I have a globally defined JavaScript function which performs an ajax request to fetch some data from a model. The issue I am having is that when I load the page and inspect element, it gives the error:

Uncaught ReferenceError: response is not defined

Here is the function:

function getRating(work_id)
        {
            $.ajax({
                url: '/read/getRatings',
                type: 'GET',
                async: true,
                data: { field1: work_id},
                success: function (data) {
                    //your success code
                   response = data;
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("Error: " + thrownError);
                }
            });
            return response;
        }

The function gets called in my HTML like this:

  <div class="extra">
    <script>
    document.write(getRating(112));
    </script>
  </div>

Error in browser console]:

Error in browser console

The Ajax request works fine as when I inspect it in Chrome's developer tools, the correct response comes back. However the variable response does not get initialized in the $.ajax() method.

When I try to add $response = ""; at the start of the function so that it gets explicitly defined, it always returns the empty string and the variable does not get changed inside the ajax request as it should.

Anyone know what's going wrong here?

user3574492
  • 6,225
  • 9
  • 52
  • 105

1 Answers1

2

This is a common misunderstanding of asynchronous programming. You don't have a result to return when the initial call ends-- you need a callback to do the writing for you (the success part).

function getRating(work_id, selectorToWriteTo)
        {
            $.ajax({
                url: '/read/getRatings',
                type: 'GET',
                async: true,
                data: { field1: work_id},
                success: function (data) {
                    //your success code
                    $(selectorToWriteTo).html(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("Error: " + thrownError);
                }
            });
        }

HTML:

<div class="extra" id="myDiv">
    <script>
         getRating(112, '#myDiv')
    </script>
  </div>
ps2goat
  • 8,067
  • 1
  • 35
  • 68