Home > Software engineering >  Can't pass data from asp.net webforms to client side using ajax
Can't pass data from asp.net webforms to client side using ajax

Time:07-30

I am trying to pass some data to client side using ajax, but can't do it succesfully. I get error in browser failed to load resource. I checked jQuery is loaded correctly.

[HttpGet]
    public string GetGraphData()
    {

        try
        {
            DataTable dt = new DataTable();
            int[,] datar = new int[,] { { 1, 10 }, { 2, 15 }, { 3, 13 }, { 4, 17 } };
            // create columns
            for (int i = 0; i < 2; i  )
            {
                dt.Columns.Add();
            }

            for (int j = 0; j < 4; j  )
            {
                // create a DataRow using .NewRow()
                DataRow row = dt.NewRow();

                // iterate over all columns to fill the row
                for (int i = 0; i < 2; i  )
                {
                    row[i] = datar[j, i];
                }

                // add the current row to the DataTable
                dt.Rows.Add(row);
            }

            string JsonString = JsonConvert.SerializeObject(dt);
            return JsonString;
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex);
            return null;
        }
        
    }

This is my c# code. It is placed in controller named HomeController.cs.

Here is my js script:

$(document).ready(function () {

$.ajax({

    type: 'GET',
    url: '/Home/GetGraphData',
    data: {},
    success: function (result) {
        alert("Data is here");
        console.log(result);
        
    },
    error: function (result) {
        alert("Data isnt here");
    }
});

})

I am trying to pass data from asp.net webforms and i am using .net framework 4.5. I am trying just to send data for now and i will worry about other thins when i successfuly send it.

CodePudding user response:

test it after adding this in your ajax property,

        type: 'GET',
        url: '/Home/GetGraphData',                
        dataType: "json",
        ContentType: "application/json;charset=utf-8",

CodePudding user response:

 $(document).ready(function () {
    
    $.ajax({
    
        type: 'GET',
        url: '/Home/GetGraphData',                
        dataType: "json",
        ContentType: "application/json;charset=utf-8",
        data: {},
        success: function (result) {
            alert("Data is here");
            console.log(result);
            
        },
        error: function (result) {
            alert("Data isnt here");
        }
    });
    
    })
  • Related