0

I am trying to do a small web tool. Therefore I want to get a list of categories from a Mysql database via a Ajax request in Jquery. Unfortunately my Jquery function which should return an array of categories, returns only "undefined".

Jquery function (the returned data from the database are correct)

function get_categories($categoryname) {
    var values =[];
    $.ajax({
        url: '../php/get_categories.php',
        method: 'POST',
        data: {categoryname: $categoryname},
        success: function (data)
        {
            values = JSON.parse(data);
            return values;
        }

    });
}

Button Event using the request:

function update_categories() {
    var list = "<ul>";
    alert(get_categories("%"));
    var result = get_categories("%");
    $.each(result, function (index, value)
    {
        list += "<li>" + value + "</li>";
    });
    list += "</ul>";
    $("#category_list").html(list);
}

When showing the result of the request (data), the proper categories are listed, but when I show the returned value (result), it displays "undefined".

Can anyone tell me what I am doing wrong?

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
Zudy
  • 49
  • 7
  • 1
    `return values;` returns from your `success` callback, not from the ajax function. – Patrick Q May 09 '19 at 20:32
  • 2
    Possible duplicate of [jquery - return value using ajax result on success](https://stackoverflow.com/questions/3302702/jquery-return-value-using-ajax-result-on-success) also [this](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and [this](https://stackoverflow.com/questions/10768991/return-value-of-jquery-ajax-call) and many others. – Patrick Q May 09 '19 at 20:33
  • Why you have put $categoryname in jquery. You should change it to just 'categoryname' – Jeeva May 10 '19 at 09:13

0 Answers0