Ajax get / post on the same method

I am trying to call a server method from my controller using the ajax method Get

in which I provided the data. The method takes arguments, some work and return a list. I want to use the same method for posting.

I am getting undefined error when I try to do this.

My Get method looks like this:

$.ajax({
        traditional:true,
        type: "GET",
        url: "/Graphs/chartData",
        data: { id: 0, WeatherAll: 0, paramSites: 0 },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            alert(r);
        },
        failure: function (r) {

            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
});

      

My post method has google charts like this:

google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        var options = {
            backgroundColor: 'transparent',
            title: 'Humidity/Temperature Measure',
        };
        var idSite = $('#DDLSites').val();
        var idWeatherALL = $('#DDLParameterWeatherAll').val();
        var idParamSites = $('#DDLParameterWeatherSites').val();
        $.ajax({
            traditional: true,
            type: "POST",
            url: "/Graphs/chartData",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                alert(r);
                var data = google.visualization.arrayToDataTable(r);
                var options = {
                    title: 'Humidity/Temperature Measure for Site 1',
                    'backgroundColor': 'transparent',
                    vAxis: {
                        title: 'Temperature/Humidity',
                    },
                    hAxis: {
                        title: 'Time',
                    },
                };
                var chart = new google.visualization.AreaChart($("#chart")[0]);
                chart.draw(data, options);
            },
            failure: function (r) {

                alert(r.d);
            },
            error: function (r) {
                alert(r.d);
            }
        });
    }

      

My ChartData method:

[AcceptVerbs("Get", "Post")]
public JsonResult chartData(int id, int WeatherAll,int  paramSites)
{
    string ids = Convert.ToString(id) + Convert.ToString(WeatherAll) + Convert.ToString(paramSites);
    List<object> chartData = new List<object>();
    chartData.Add(new object[]
    {
        "Date Time", "Temp", "Humidity"
    });
        ////Some Code here
    return Json(chartData);
}

      

I cannot figure out how I can do this. Please let me know in any way convenient for you. Thanks to

+3


source to share


2 answers


Here is my solution, I created a sample Action with AJAX calls.

Let the controller action be

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public JsonResult Data(int id, string s)
{
    return Json("Test", JsonRequestBehavior.AllowGet);
}

      

let the buttons in HTML be

<input type="button" value="GET" id="get" />
<input type="button" value="POST" id="post" />

      

JQuery code to create AJAX POST and GET -

@section scripts{
<script>
    $(function() {
        $("#get").click(function() {
            $.ajax({
                traditional: true,
                type: "GET",
                url: "/home/data",
                data: { id: 2, s : 'Test'},
                success: function (r) {
                    alert(r);
                },
                failure: function (r) {

                    alert(r.d);
                },
                error: function (r) {
                    alert(r.d);
                }
            });
        });

        $("#post").click(function () {
            $.ajax({
                traditional: true,
                type: "POST",
                url: "/home/data",
                data: JSON.stringify({ id: 4, s: 'Test' }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r);
                },
                failure: function (r) {

                    alert(r.d);
                },
                error: function (r) {
                    alert(r.d);
                }
            });
        });
    })
</script>
}

      



Make sure there is an appropriate Route Config entry -

 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}/{s}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, s = UrlParameter.Optional }
            );

      

When you create AJAX GET -

enter image description here

When you do AJAX POST -

enter image description here

+2


source


For the GET method, you must set JsonRequestBehavior.AllowGet

in your controller

return Json(chartData, JsonRequestBehavior.AllowGet);

      

So:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public JsonResult chartData(int id, int WeatherAll,int  paramSites)
{
    string ids = Convert.ToString(id) + Convert.ToString(WeatherAll) + Convert.ToString(paramSites);
    List<object> chartData = new List<object>();
    chartData.Add(new object[]
    {
        "Date Time", "Temp", "Humidity"
    });
        ////Some Code here
    return Json(chartData, JsonRequestBehavior.AllowGet);
}

      



And remove contentType: "application/json; charset=utf-8"

in the GET Ajax method as the data sent to the server is not a JsonString. GET Ajax

$.ajax({
        traditional:true,
        type: "GET",
        url: "/Graphs/chartData",
        data: { id: 0, WeatherAll: 0, paramSites: 0 },
        dataType: "json",
        success: function (r) {
            alert(r);
        },
        failure: function (r) {

            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
});

      

POST Ajax

    $.ajax({
        traditional: true,
        type: "POST",
        url: "/Graphs/chartData",
        data: JSON.stringify({id: 0, WeatherAll: 0, paramSites: 0 }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            alert(r);
            var data = google.visualization.arrayToDataTable(r);
            var options = {
                title: 'Humidity/Temperature Measure for Site 1',
                'backgroundColor': 'transparent',
                vAxis: {
                    title: 'Temperature/Humidity',
                },
                hAxis: {
                    title: 'Time',
                },
            };
            var chart = new google.visualization.AreaChart($("#chart")[0]);
            chart.draw(data, options);
        },
        failure: function (r) {

            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
    });

      

+1


source







All Articles