views:

1434

answers:

5

I am calling a Web Method in the code behind with a Method Signature that has 4+ strings accepted. I am creating a params variable and using it to add all input fields I want to pass to the method.

                var params = {
                    showStartDate: showStartDate,
                    showEndDate: showEndDate,
                    arrivalDate: arrivalDate,
                    pickUpDate: pickUpDate
                };

How do I then pass "params" in my AJAX call? Below is my current code which does not seem to be working. I don't want to have to pass each param explicitly in the data section.

                $.ajax({
                    type: "POST",
                    url: "OrderSummary.aspx/JSONUpdateOrder",
                    async: false,
                    data: "{'" + params + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data) {
                    }
                });
A: 

You can pass params itself, without the enclosing braces.

var params = 
{
  "showStartDate": showStartDate,
  "showEndDate": showEndDate,
  "arrivalDate": arrivalDate,
  "pickUpDate": pickUpDate
};

$.ajax({
  type: "POST",
  url: "OrderSummary.aspx/JSONUpdateOrder",
  async: false,
  data: params,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) {
  }
});
David Andres
Are you sure about this with Web Methods? My Web Method is not being called just passing "params" per your suggestion. Do the params have to be in the same order as the Method Signature? I wouldn't think so...
aherrick
I wouldn't assume anything about how well ordered the parameters have to be. Try to make that order match the server-side code. Do you get an error message of some kind when you try this?
David Andres
No error message it just doesn't hit the break point in my Web Method. I can expliclity pass each variable like this but I don't want to do that for each one...data: "{'showStartDate': '" + params.showStartDate + "'}"
aherrick
Is Page_Load firing at the server-side? Your url may not be correct.
David Andres
I mean my URL is correct. If I can explicitly pass each param in the data, then I would say yes it is correct. Any other thoughts?
aherrick
Just to rule this out, can you please change the name of the variable params to something else?
David Andres
A: 

Here is an example from my code:

A link to the JSON functions you see (http://www.json.org/js.html)

var selected = $("#ddPackageContainerType option:selected");    
var DTO =  JSON.stringify({ sContainerType: selected.val(), sLocation: '<%=Location%>' });

                    $.ajax({
                        data: DTO,
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        url:"helpers/packinguiservice.asmx/GetContainerDetail",

                        success: function (data, textStatus) {
                            var oContainerDetail = JSON.parse(data);

                            //Fill In All the data returned
                            $('#txtPackageLength').val(parseFloat(oContainerDetail.Length).toFixed(1));
                            $('#txtPackageWidth').val(parseFloat(oContainerDetail.Width).toFixed(1));
                            $('#txtPackageHeight').val(parseFloat(oContainerDetail.Height).toFixed(1));
                            $('#ddPackageDimensionsUOM').val(oContainerDetail.LengthUOM);
                            $('#txtPackageWeight').val(parseFloat(oContainerDetail.PackageWeight).toFixed(1));

                            hideInfoOverlay(); 
                        },
                        error: function(objXMLHttpRequest, textStatus, errorThrown) {
                            //Show Error
                            hideInfoOverlay();
                            showErrorOverlay(' ' + objXMLHttpRequest.responseText);    
                        }
                    });

And the corresponding WebMethod:

<WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Function GetContainerDetail(ByVal sContainerType As String, ByVal sLocation As String) As String
        Dim oPackageInfo As New Dictionary(Of String, String)()
        Dim oPackage As Pacejet.Base.Package

        Try
            AppStatic.MyLocation = sLocation

            oPackage = Pacejet.Base.Package.GetPackageByKey(sContainerType)
            If Not oPackage Is Nothing Then
                oPackageInfo.Add("Length", oPackage.Length.Value)
                oPackageInfo.Add("Width", oPackage.Width.Value)
                oPackageInfo.Add("Height", oPackage.Height.Value)
                oPackageInfo.Add("LengthUOM", oPackage.LengthUOM.Value)
                oPackageInfo.Add("PackageWeight", oPackage.StandardWeight.Value)
            End If

        Catch ex As Exception
            Throw New HttpException(System.Net.HttpStatusCode.InternalServerError, ex.Message)
        End Try

        Return New JavaScriptSerializer().Serialize(oPackageInfo)
    End Function
Rick Hochstetler
So I need to "stringify" my params before passing it to my web method?
aherrick
I'm not exactly sure what your issue is - I was just posting a working code excerpt in hopes you could take a look at it and figure something out.Couple thoughts:1) IS the ajax call getting into your web method?2) Add a error: section to your ajax call to see if anything relevant is being returned.
Rick Hochstetler
I added an error catch per your suggestion and it turns out it wasn't an invalid JSON error. My guess it is i have to explicitly call out each param or like you use a JSON stringify
aherrick
+1  A: 

I think all you're missing is serializing your parameters to JSON with JSON.stringify(data).

Some browsers, like FF3+ and IE8, implement JSON.stringify natively. Others need a reference to http://json.org/json2.js (hosted on your own domain of course).

Also, try using removing async:false from the options - maybe it affects nothing but I've never used it.

One final thing: is your web method URL really OrderSummary.aspx/JSONUpdateOrder? Could it be '.asmx' instead of '.aspx'?

Edit: use fiddler to see what response the server returns, if any.

orip
A: 

In simple way try this code its working

function ShowAvailability() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/CheckUserName",
        data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '",userName1: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response);
        }
    });
}
anish
A: 

$.ajax({

type: "POST",

    url: "CS.aspx/CheckUserName",
    data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '",userName1: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: function(response) {
        alert(response);
    }
});
anish