1

I want to insert the specification of members that enter in textboxes of form in the database. I do this operation with jQuery Ajax when I call a webmethod with a static value. The operation is successful. For example, this code is okay:

 $.ajax({
     type: "POST",
     url:"MethodInvokeWithJQuery.aspx/executeinsert",
     data: '{ "username": "user1", "name":"john","family":"michael","password":"123456","email": "[email protected]", "tel": "123456", "codemeli": "123" }',
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     async: true,
     cache: false,
     success: function (msg) {
         $('#myDiv2').text(msg.d);
     },
     error: function (x, e) {
         alert("The call to the server side failed. " + x.responseText);
     }
 }
 );

But when I want to make use of the values that enter in textboxes dynamically, an error occurs. What's problem? I tried the following two code blocks.

<script type="text/javascript">
    $(document).ready(
    function () {
        $("#Button1").click(
            function () {
                var username, family, name, email, tel, codemeli, password;
                username = $('#<%=TextBox1.ClientID%>').val();
                name = $('#<%=TextBox2.ClientID%>').val();
                family = $('#<%=TextBox3.ClientID%>').val();
                password = $('#<%=TextBox4.ClientID%>').val();
                email = $('#<%=TextBox5.ClientID%>').val();
                tel = $('#<%=TextBox6.ClientID%>').val();
                codemeli = $('#<%=TextBox7.ClientID%>').val();

                $.ajax(
                {
                    type: "POST",
                    url: "WebApplication20.aspx/executeinsert",
                    data: "{'username':'username','name':name,
                            'family':family,'password':password,
                            'email':email,'tel':tel,
                            'codemeli':codemeli}",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    async: true,
                    cache: false,
                    success: function(msg) {
                        alert(msg);
                    },
                    error: function (x, e) {
                        alert("The call to the server side failed. "
                              + x.responseText);
                    }
                }
            );
        }
        )
     })
 </script>

and

$(document).ready(
    function () {
        $("#Button1").click(
            function () {
                var username, family, name, email, tel, codemeli, password;
                username = $('#<%=TextBox1.ClientID%>').val();
                name = $('#<%=TextBox2.ClientID%>').val();
                family = $('#<%=TextBox3.ClientID%>').val();
                password = $('#<%=TextBox4.ClientID%>').val();
                email = $('#<%=TextBox5.ClientID%>').val();
                tel = $('#<%=TextBox6.ClientID%>').val();
                codemeli = $('#<%=TextBox7.ClientID%>').val();

                $.ajax(
                {
                    type: "POST",
                    url: "WebApplication20.aspx/executeinsert",
                    data: '{"username" : '+username+', "name": '+name+', "family":     '+family+',
                    "password": '+password+', "email": '+email+', "tel": '+tel+' ,
                    "codemeli": '+codemeli+'}'
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    async: true,
                    cache: false,
                    success: function(msg) {
                        alert(msg);
                    },
                    error: function (x, e) {
                        alert("The call to the server side failed. "
                              + x.responseText);
                    }
                }
        );
    }
    )
})

The error content here is:

{"Message":"Invalid JSON primitive: myname.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
 at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
 at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
 at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
 at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
 at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
 at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
 at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)
 at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
 at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
1
  • its not important for me that i use json or key value .i want only this code works Commented Jul 7, 2012 at 9:12

1 Answer 1

3

for example this code is ok

Yes, in this specific example it is OK because you have hardcoded the values, but the code hides a huge flaw and this flaw is responsible for the problems you are encountering when you use dynamic values. You don't encode your JSON request values. And that's what happens when you want to insert dynamic values. If there's some special character in the name for example your JSON breaks because you have used string concatenations. You should never do that. You should use the JSON.stringify function and replace the following horror:

data: '{"username" : '+username+', "name": '+name+', "family":     '+family+',
            "password": '+password+', "email": '+email+', "tel": '+tel+' , 
            "codemeli": '+codemeli+'}'

with:

data: JSON.stringify({ 
    username: username, 
    name: name, 
    family: family,
    password: password, 
    email: email, 
    tel: tel, 
    codemeli: codemeli 
})

Now all your request parameters will be properly encoded. The JSON.stringify method is natively built into all modern browsers. But if you need to support some very legacy browsers you might need to include the json2.js script.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.