While implementing AJAX call users find problem what to return and how to handle it.
The below example shows, web method which is returning a string in both the cases whether insertion occurs or error is being generated by the program.
[WebMethod]
[ScriptMethod]
public static string InsertDetails(User user)
{
string status = null;
try
{
UserRepository repobj = new UserRepository();
user = repobj.GetPrefernceId(user);
user = repobj.InsertData(user);
status = "Records inserted successfully";
}
catch (Exception ex)
{
status = ex.Message;
}
return status;
}
To handle this, message i have made two methods in which on success and on error i will get string
Ex:
function InsertDetails() {
var user = {};
user.Username = $("[id*=txtUserName]").val();
user.Password = $("[id*=txtPassword]").val();
user.Email = $("[id*=txtEmail]").val();
user.Contact = $("[id*=txtContact]").val();
user.Address = $("[id*=txtAddress]").val();
user.Preference = $("[id*=txtPreference]").val();
$.ajax({
type: "POST",
url: "RegisterUser.aspx/InsertDetails",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
window.location.reload();
},
error: function (response) {
alert("Some error occurred","Error Description"+response.d);
window.location.reload();
}
});
return false;
}
So by defining these two methods i get the returning message and display message according to the return type.
0 Comment(s)