How to use ajax to call a boolean web method - c#

I want to use an ajax call to check if Boolean is true or false.
here is my web method:
[WebMethod]
public Boolean Login(string uname, string password)
{
if (ValidateUser(uname, password))
{
FormsAuthentication.Authenticate(uname, password);
return true;
}
return false;
}
and here is my ajax call but its not working
$(document).ready(function () {
$('#btnLogin').click(function () {
var username = "test"
var password = "1234"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "wsLogin.asmx/Login",
data: "{uname: '" + username + "'" + ",pwd: '" + password + "' }",
dataType: "Json",
success: function (success) {
alert("Boolean True");
},
error: function (error) {
alert("Boolean False");
}
});
});
});
I am trying to create a login so I am using a Boolean to check if the user is authenticated

Unfortunately ajax seems to .toString() the answer so what was a boolean becomes a "True" or "False" if you return a Json data structure instead like
return Json(new { Error = true, ErrorMessages = new []{e.Message} });
the values will be truly boolean.

I had the same problem.
I realised that the error: function (error) {} never gets called, even when my webmethod returned false.
What's actually happening is that as long as the webmethod does not produce any errors itself (like exceptions), then the error function will never fire! The webmethod will always be a 'success'!
So place your true/false logic inside the success function:
$(document).ready(function () {
$('#btnLogin').click(function () {
var username = "test"
var password = "1234"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "wsLogin.asmx/Login",
data: "{uname: '" + username + "'" + ",pwd: '" + password + "' }",
dataType: "Json",
success: function (result) {
if(result == "true")
alert("Boolean True");
else
alert("Boolean False");
},
error: function (error) {
error = error; //do nothing
}
});
});
});

try this:
$(document).ready(function () {
$('#btnLogin').click(function () {
var username = "test"
var password = "1234"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "wsLogin.asmx/Login",
data: "{uname: '" + username + "'" + ",pwd: '" + password + "' }",
dataType: "Json",
success: function (data) {
if(data)
alert("Boolean True");
else
alert("Boolean False");
},
error: function (error) {
alert("Error");
}
});
});
});

Related

How can I call an ASP.Net string function with jQuery AJAX?

I have a string function ASP.Net Webform. I want to call this function using AJAX.
That function returns a string value from database with a month index
protected string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
var dataValue = { "month": 1 };
$.ajax({
type: "POST",
url: "Homepage.aspx/BringDatas",
data: dataValue,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
}
});
Give it a try:
Code Behind:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
ajax call
$.ajax({
type: 'GET',
url: 'Homepage.aspx/BringDatas',
data: '{"month": 1}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (response) {
alert("Response: " + response.d);
},
error: function (response) {
}
});
This is javascript side
<script type="text/javascript">
$(document).ready(
function () {
$("#Gonder").click(
function () {
$.ajax
({
type: "POST",
url: "Homepage.aspx/OrnekPost",
data: "{'parametre':'1234'}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (output) {
alert("Response: "+ output);
}, error: function () {
alert("hata var");
}
});
});
})
</script>
Codebehind.cs code
[ScriptMethod]
[WebMethod(EnableSession = true)]
public static string OrnekPost(string parametre)
{
return parametre + " değeriyle post işlemi gerçekleştirildi.";
}

Call cs function with data in js using ajax

I want to access cs function from js function in aspx page after the user click on Delete button. and send id to the cs function.
I try the below codes:
js
function deleteClick(ID) {
'<%Session["ID"] = "' + ID + '"; %>';
var x = '<%= Session["ID"] %>';
alert(x);
$.ajax({
type: "POST",
url: "AddPI.aspx/deleteClick",
//data: ' {ID:"' + ID + '"}',
data: JSON.stringify({ ID: "' + ID + '" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Success");
},
failure: function (response) {
alert("Error");
}
});
}
cs
public void deleteClick(String ID)
{
Session["ID"] = Request.Params["ID"];
var id = "";
id = Session["ID"].ToString();
DialogResult myResult;
myResult = MessageBox.Show("Are you sure?", "Delete Confirmation",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (myResult == DialogResult.OK)
{
errorbox.Visible = false;
//connect to database and delete
}
}
the problem is the id can't be passed!
EDIT:
i solve the problem by change the cs function to static and edit the below field:
data: "{ ID: '" + ID + "'}",
that's it.
Now the problem is how to change the visibility of aspx div in a static cs function?
errorbox.Visible = false;
i got: Ann object reference is required for the non-static field....
i try call js on success
success: setVisibility,
and in the js:
$("#errorbox").hide();
but it does not works!
//Js Code
function deleteClick(ID) {
alert(ID);
$.ajax({
type: "POST",
url: "Default.aspx/deleteClick",
data: '{ID: "'+ID+'" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response,a,a2) {
alert("Not Done");
}
});
}
//c# Code
[System.Web.Services.WebMethod]
public static string deleteClick(string ID)
{
//Your Code
return null;
}
Noting your first issue is solved by you which is awesome! :)
and you have another problem in which you need to change the visibility of a div on error occurrence. Well you change the visibility of div errorbox to true as default value
errorbox.Visible = true;
and on your script section, hide this div using jquery:
$(function(){
$('[id$=errorbox]').hide(); //this will auto-run after page is completely loaded.
});
make little changes to your cs function such as:
public string deleteClick(String ID)
{
Session["ID"] = Request.Params["ID"];
var id = "";
id = Session["ID"].ToString();
DialogResult myResult;
myResult = MessageBox.Show("Are you sure?", "Delete Confirmation",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (myResult == DialogResult.OK)
{
errorbox.Visible = false;
//connect to database and delete
return "true"; //if successful
}
return "false"; //if not successful
}
and then if any error occurs on your ajax response(success/error) simply just do this in your ajax:
success: function (response) {
if(response.d == "true")
{
alert('success');
}
else{
$('[id$=errorbox]').show();
}
},
error: function (response) {
$('[id$=errorbox]').show();
}

Ajax error calling web method

I am trying to set the date in a Bootstrap datetime picker based on drop down list selection change. I am using a web method (C#) to return "start date" given a "certificate ID".
I tried using "text" data type instead of "json" but keep getting "Cannot convert object of type System.String to type System.Collections.Generic.IDictionary"
I searched for this error type and could not find something that would resolve this issue.
$("#ddlCertificate").change(function () {
....
debugger
setStartDate($("#ddlCertificate").val());
});
function setStartDate(certItemID) {
var param = JSON.stringify(certItemID, null, 2);
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: param,
}).done(function (result) {debugger
$("#tbStartDate").val(result.d);
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
alert(textStatus + ' - ' + errorThrown);
});
}
Web Method:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string GetCertItemStartDate(string certID)
{
int iCertItemID = int.Parse(certID);
DateTime dtStartDate = CertItem.GetCertItemStartDate(iCertItemID);
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dtStartDate);
return JSONresult;
}
The problem was the way the parameter was being passed. In ajax call, I had:
data: param,
and had to change it to:
$("#ddlCertificate").change(function () {
....
var certID = "{ 'certID': '" + $('#ddlCertificate').val() + "'}";
setStartDate(certID);
});
function setStartDate(certItemID) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: certItemID,
}).done(function (result) {
var startDate = JSON.parse(result.d);
setStartDate(new Date(startDate));
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown);
});
}

JSON-data to WebMethod using jQuery returning errors

I'm trying to send a json list populated with the id's from the 'data-seq' attribute only when the 'value' == true.
I have tried out a lot solution but it keeps getting me error messages, the most common are "there is no parameterless constructor for the type string" when using string[] or "string is not supported for deserialization of an array" when using string as code-behind parameter in the WebMethod.
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var obj = {
id: $(this).attr("data-seq")
};
json.push(obj);
});
json = JSON.stringify({ jsonList: json });
console.log(json); // {"jsonList":[{"id":"38468"},{"id":"42443"},{"id":"42444"}]} (the right id's are getting stored)
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: json,
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
// Code-Behind
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
// string: string is not supported for deserialization of an array
// string[]: there is no parameterless constructor for the type string
}
You are just sending IDs so send them as comma-separated string like this:
function sentData() {
var json = [];
$('.btn[value="true"]').each(function () {
var id = $(this).attr("data-seq")
json.push(id);
});
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/getList",
dataType: "json",
data: '{jsonList: "' + json + '" }',
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
console.log('bad, ' + errorThrown + ", " + jqXHR.responseText + ", " + textStatus);
},
success: function(json){
//do something with the result
}
});
return false;
}
And Code-Behind:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public static void getList(string jsonList)
{
List<string> ListOfIDs = jsonList.Split(',').ToList();
}

How to pass parameter(email ID) to a c# function from Jquery Ajax call?

I am trying to call a Web Method of service from a Jquery Ajax call.
Method accepts 3 parameter from the front end and search for the record in the DB.
I am not able to concatinate those 3 parameter properly in the Ajax call :
The Web Method is :
public bool FindRecord(string Fname, string Lname, string Email)
{
string SQL = "SELECT * FROM contactsSource WHERE (first_name ='" + Fname + "') AND (last_name = '" + Lname + "') AND (email_address_work = '" + Email +"')";
OleDbDataReader reader = DataAccess.GetData(SQL);
if (reader.HasRows)
{
return true;
}
else
{
return false;
}
}
and the Ajax call I am trying is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
var Fname = $('#Fname').val();
var Lname = $('#Lname').val();
var email = $('#Email').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"Fname":"' + Fname + '", "Lname":"' + Lname + '", "Email":' + email + '}',
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});
//$('.secondary').show(500);
});
});
</script>
But I am keep on getting 500 Internal Server error :
{"Message":"Invalid JSON primitive: (Email ID that I am passing).","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
Your email parameter should be enclosed in double quotes, otherwise it will not be parsed properly as a JSON string value. The corrected syntax should be:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"Fname":"' + Fname + '", "Lname":"' + Lname + '", "Email":"' + email + '"}',
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});
You are constructing your data object wrong. Do this instead:
data: {Fname: Fname, Lname: Lname, Email: Email }
No need for quotes..
Try:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {Fname: Fname, Lname: Lname, Email: email},
url: "WebService.asmx/FindRecord",
dataType: "json",
success: function(result) {
alert(result.d);
},
error: function(result) {
alert("Due to unexpected errors we were unable to load data");
}
});

Categories