1

Im trying to make a class to handle ajax requests and its returning undefined.

My Class:

class AjaxRequest {
    constructor(url, data = null) {
        this.data = data
        this.url = url
        this.datatype = 'json'
    }

    post() {
        $.ajax({
            url: this.url,
            method: 'post',
            success: function(result) {
                console.log(result)
            }
        })
    }

    get() {
        $.ajax({
            url: this.url,
            method: 'get',
            success: function(result) {
                let json = JSON.parse(result)
                return json
            }
        })
    }
}

in the php file i just have an array that is sent as json

$result = [
    'text' => 'this is a simple text as a test',
    'type' => 'success'
];

echo json_encode($result);

when i use my class it returns undefined.

let ajaxRequest = new AjaxRequest('file.php', null)
console.log(ajaxRequest.get())

this should be returning a json object am i wrong? When i change the console.log to inside the class method, it works.

Tks for the help.

eskimopest
  • 401
  • 3
  • 18
  • Your `get` function doesn't return anything (neither does `post`). – tkausl Jul 04 '21 at 12:47
  • 1
    *"am i wrong"*. Yes definitely. Numerous issues here. A `return` in `success` does not return to outer function, `$.ajax` is **asynchronous** and your class methods have no `return` – charlietfl Jul 04 '21 at 12:48

0 Answers0