Saghir A. Khatri
Saghir A. Khatri

Reputation: 3128

Ajax get/post on same method

I am trying to call a server method from my controller using ajax Get method, in which i have provided data. Method accepts arguments does some work and returning a list. I want to use same method for post.

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

My Get method looks like:

$.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 some 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 is:

[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 am unable to figure out how i can do it. Please let me know of any way that is convenient. Thanks

Upvotes: 3

Views: 441

Answers (2)

Dawood Awan
Dawood Awan

Reputation: 7328

For the GET method you have to 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 the contentType: "application/json; charset=utf-8", on the GET Ajax Method, as the Data sent to the server is not 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);
        }
    });

Upvotes: 1

ramiramilu
ramiramilu

Reputation: 17182

Here goes my solution, I created sample Action with AJAX Calls.

Let 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 make the 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 proper Route Config entry is present -

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

When you make the AJAX GET -

enter image description here

When you make the AJAX POST -

enter image description here

Upvotes: 2

Related Questions