Carlo Adap Carlo Adap - 3 months ago 21
ASP.NET (C#) Question

Ajax jquery passing multiple parameters web services

<script type="text/javascript">
$('#btnregister').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "fetchusers.asmx/RegUsers",
data: "{ username: '" + $("#txtuser").val() + "name: '" + $("#txtname").val() + "'}",
dataType: "json",
success: function (data) {
alert("Successfully register");
$("#btnregclose").click();
}
});
});
</script>

<div id="registration">
<fieldset>
<legend>Registration Form</legend>
<input id="txtuser" type="text" placeholder="Username" /><br />
<input id="txtname" type="text" placeholder="Name" /><br />
<input id="txtpass" type="password" placeholder="password" /><br />
<input id="txtconfirmpass" type="password" placeholder="confirm password" /><br />
<input id="btnregister" type="button" value="Register" />
<input id="btnregclose" type="button" value="close" />
</fieldset>
</div>


[WebMethod]
public string RegUsers(string username, string name)
{
string response = username + name;

return response;
}


I'm a beginner in Ajax Jquery and I'm doing exercise to improve my knowledge about it. My problem is when I click #btnregister it's not working. I think there's a problem in the parameters I passed on the ajax but I don't know what is it.

Answer

try this :

 $(document).ready(function () {
        $('#btnregister').click(function () {
            var obj = { username: $("#txtuser").val(), name: $("#txtname").val() };
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "fetchusers.asmx/RegUsers",
                data: JSON.stringify(obj),
                dataType: "json",
                success: function (data) {
                    alert("Successfully register");
                    $("#btnregclose").click();
                }
            });
        });
    });

this worked in my local enviroment.