0

Okay. I'll try this again. I didn't get very far over here. I'm very new to ajax and jQuery.

in an attempt to even see if I can obtain the filerValues on the server but to no avail. In addition, I do Not want to use asmx pages, so I guess I cannot use web methods.

I'm just trying to obtain the post URL with the appropriate checked values so I can parse it on the server. Every time I check a checkbox, it should send all checked values to the server. However, I'm having trouble obtaining the URL. The filterValues is supposed to hold a query string like name=value&name=value&name.... and it does show that in the payload when I am running the Developer's Console. It is indeed posting the correct data. but when I test if I can access it on the server, it keeps hitting the error function in ajax. I'm using web forms app, not MVC and not asmx pages. Also, I'm new to ajax and their behavior. Thanks.

EDIT:

I have figured out the solution. It turns out that I needed to post Form Data, and not any other kind of payload.

Community
  • 1
  • 1
SKY
  • 53
  • 1
  • 11
  • An ajax request returns the result directly to the JavaScript, to the `success` function (assuming no error). It doesn't update the web page's html automatically, regardless of what the server-side code returns. You've set `dataType: "json"` in your ajax call, which means jQuery is expecting the *response* to be in JSON format, but your server-side code doesn't return JSON. Does your `success` function actually get called? All it has is an empty if/else. Try adding an `error` callback too and see if it is called. – nnnnnn Jan 05 '15 at 00:29
  • What are you trying to do? You're using ajax so I guess you want to run some code when someone clicks a checkbox without refreshing the page? – garethb Jan 05 '15 at 01:27
  • @nnnnnn I see, I did not know that. I was under the impression that I could return null and manipulate the data that's passed on the server. – SKY Jan 05 '15 at 02:54
  • @garethb Yes. User checks a checkbox -- the name + value of that checkbox gets sent to the server (along with any other checkboxes that were checked) - I use that data to update the page. Think Amazon -- how you can filter your search results from criteria without refreshing the whole page. – SKY Jan 05 '15 at 02:56
  • I should add that it involves round trips to a database each time a checkbox is checked. I would use the checkbox values to edit the query to return updated results. – SKY Jan 05 '15 at 02:59
  • To be honest, I don't need a success function because I'm updating the html on the server. – SKY Jan 05 '15 at 03:38
  • If you just want to send data to the server and don't need a response then I guess you don't need a success function. But what is the html you say you are updating on the server? Don't you want to display that? If so your server-side code will have to put it in the response which you'll then process in the success function to do that. – nnnnnn Jan 05 '15 at 07:37
  • @nnnnnn The html are the results from checking the checkbox. I display it in a different div simply using <% htmlVariable %>. I've updated my code above to use success/error yet it still just throws the error and not success. I am not sure why. – SKY Jan 05 '15 at 13:40

3 Answers3

0

This answer should help: https://stackoverflow.com/a/4508430/853295

Below is a copy of the answerby @Darin Dimitrov

If you want to call methods in the code behind in a classic WebForms application you could use PageMethods:

[WebMethod]
public static string GetDate()
{
    return DateTime.Now.ToString();
}

And then to call the method:

$.ajax({
    type: 'POST',
    url: 'PageName.aspx/GetDate',
    data: '{ }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(msg) {
        // Do something interesting here.
    }
});

And here's a full working example I wrote for you:

Add this method to your code behind:

    [WebMethod]
    public static string SayHello(List<string> names)
    {
        var str = "hello ";
        for (var i=0; i<names.Count; i++)            
        {
            str += (names[i] + ", ");
        }
        return str;
    }

Add this to your aspx file.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script type="text/javascript">
        var myArr = ["John", "Fred", "Sam"];
        $(function () {
            $.ajax({
                type: 'POST',
                url: 'test.aspx/sayhello',
                data: "{ 'names': " + JSON.stringify(myArr) + "}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (msg) {
                    // Notice that msg.d is used to retrieve the result object
                    alert(msg.d);
                }
            });
        });
    </script>
</head>
<body>
    <form id="Form1" runat="server">

    </form>
</body>
</html>

PageMethods are not limited to simple argument types. You could use any type as input and output, it will be automatically JSON serialized.

Community
  • 1
  • 1
garethb
  • 3,951
  • 6
  • 32
  • 52
  • I've updated my code, I don't necessarily need to use the success function but I'm trying to test it and it keeps hitting the error method. Can you look at my updated code? In addition, does the web method have to be static? I would like to access other controls in the method that is not possible if the WebMethod is static. – SKY Jan 05 '15 at 04:05
  • Yes, it has to be static. Also, you have to call the page the method exists on, so url: "/tools/oppy/Default.aspx/UpdateProjectResults". Note the .aspx. Updated example for a list. – garethb Jan 05 '15 at 04:24
  • Is the page your webmethod is on called default.aspx? If you set a breakpoint, does it ever get hit in the webmethod? – garethb Jan 05 '15 at 23:45
  • See edit. Copy the code to a new page called test.aspx (make sure you leave the <%Page %> tag at the top of the page) and let me know the result. This is working fine for me. – garethb Jan 06 '15 at 00:15
0

Points should be considered while using ajax call

  1. url:PageName/functionName(AjaxSubmit) AjaxSubmit should be static with [WebMethod]
  2. If you want to pass any argument to that [WebMethod] then argument name should be same in both the files. 3.If you are passing array from client side to that WebMethod then the argument of Webmethod will be the List
  • "3.If you are passing array from client side to that WebMethod then the argument of Webmethod will be the List" So I can use a WebMethod on an .aspx page? And if I'm passing an array to the server, the WebMethod should accept a parameter List<>? – SKY Jan 05 '15 at 02:57
0

I have figured out the solution. It turns out that I needed to post Form Data, and not any other kind of payload.

$(function () {

                $("#chkFilter").on("click", "input", function (e) {
            var filterCheckboxes = new Array();
            $("#chkFilter").find("input:checked").each(function () {
                filterCheckboxes.push(" " + $(this).prop("name") + "=" + $(this).val() + ", ");
            });

            filterObj = {};
            filterObj.action = "updateProjects";
            filterObj.list = filterCheckboxes;
            var filtersStringify = JSON.stringify(filterObj)
            $.ajax({
                url: "/api/project/",
                type: "POST",
                data: filtersStringify,
            }).done(function (response) {
                //some stuff to do

            });
        });
    });

 if (Request.HttpMethod == "POST")
    {            
        // get json out of body
        var serializer = new JsonSerializer();
        var sr = new StreamReader(Request.InputStream);
        var jtr = new JsonTextReader(sr);
        dynamic data = serializer.Deserialize(jtr);

        if (data.action == "getProjects")
        {
            getProjects(data);
        }
        if(data.action =="updateProjects")
        {
            updateProjects(data);

        }

    }
    else
    {

    }

}

public void getProjects(dynamic data)
{
  //do stuff with the data

}
SKY
  • 53
  • 1
  • 11