-1

I'm trying to learn how to do javascript promises. I am aiming to have a button run a function which displays the promise result of another function. This is how far I have got from tutorials:

function myfunction() {
    var post = ajaxrequest();
    post.done(function (r) {
        console.log(r);
    });

}

function ajaxrequest() {
    console.log("hello");
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/todos/1",
        dataType: 'json',
        data: {
        },
    });
};

The error I am getting is:

Uncaught TypeError: Cannot read property 'done' of undefined
    at myfunction (indexboll.html:11)
    at HTMLInputElement.onclick (indexboll.html:6)

I'm really confused though. Why is it it can't read the property of done?

Jimbob
  • 27
  • 5
  • 1
    the `ajaxrequest` function doesn't return anything, so `post = ajaxrequest()` will be `undefined`. – VLAZ Oct 08 '18 at 21:02

2 Answers2

2

You would have to call your function into the success callback function of the Ajax call as below. Let me know is you have more question.

function myfunction(r) {
    console.log(r);
}

function ajaxrequest() {
    console.log("hello");
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/todos/1",
        dataType: 'json',
        data: {},
        success: function(response){
            //if request if made successfully then the response represent the data
            myfunction(response);
        }
    });
};

ajaxrequest();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Output:

hello
{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
Jonathan Gagne
  • 4,241
  • 5
  • 18
  • 30
1

Right now, you're not returning anything from your ajaxrequest() function, so post is undefined. You need to return the actual request:

function ajaxrequest() {
    console.log("hello");
    return $.ajax({
        url: "https://jsonplaceholder.typicode.com/todos/1",
        dataType: 'json',
        data: {
        },
    });
};
Blue
  • 22,608
  • 7
  • 62
  • 92