Sid M
Sid M

Reputation: 4354

Push items in an array after ajax postback

I've this script on my .cshtml page

$(function () {
        var tempArray = [];
        var tbValue = $('#tb1').val();
        $.ajax({
            url: "/ControllerName/getdata",
            dataType: 'json',
            data: { strText: tbValue },
            success: function (Data) {
                $.each(Data, function (index, value) {
                    tempArray.push(value.Name);
                });

                $("#tb1").autocomplete({
                    source: tempArray,
                    minLength: 0
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(xhr.responseText);
                console.log(thrownError);
                alert("failure");
            }

        });

    });

Now after the ajax call i get a list of objects in Data, like this

enter image description here

I get the following values of index and value in each loop

enter image description here

enter image description here

The problem comes when i try to push data in the tempArray inside each loop.

enter image description here

I get undefined item in my array and it comes out of each loop. How can i add items in the array?

Note: There are no errors in console log and I'm working on MVC3.

Upvotes: 2

Views: 2880

Answers (1)

easywaru
easywaru

Reputation: 1153

Try this.

$.each(Data.Data, function (index, value) {
    tempArray.push(value.Name);
});

Your Ajax return variable "Data" is Object

Data = {Data:[array maybe has 12 size]}

Upvotes: 4

Related Questions