Unknown web method When Making AJAX Call to WebMethod with ASP.NET - asp.net

I'm kinda new to using AJAX call to a WebMethod. I feel my Web Method logic is but maybe someone could help out here. I do get an unknown web method error when I log the AJAX response to the console. Below is my Web method and AJAX call code.
$("#btnLogin").click(function () {
email = $("#txtEmailAddress").val();
password = $("#txtPassword").val();
//Create the login info object
var loginInfo = {};
//Set the object properties and value
loginInfo.Email = email;
loginInfo.Password = password;
//Make the ajax call
$.ajax({
type: "POST",
dataType: 'json',
url: '<%=ResolveUrl("identicate.aspx/ValidateUsersToken") %>',
data: '{loginInfo:' + JSON.stringify(loginInfo) + '}',
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d == null || data.d == undefined)
{
alert("Username or password not correct = " + data.d);
console.log(data);
console.log(loginInfo);
console.log(this.url);
}
},
error: function (data) {
console.log(data);
console.log(loginInfo);
console.log(this.url);
alert(data.d);
}
});
});
And here's my web method
[WebMethod]
public static String ValidateUsersToken(iloginmodel loginInfo)
{
//Variable to hold the user email address
String email = string.Empty;
//Get the connection string from config file
String connectionString = iDbConfiguration.GetConnectionString();
//Create the command text
String commandText = "select Email, Password from VUser where Email = #Email & Password = #Password";
//Create database connection object and open it
using(SqlConnection loginConnection = new SqlConnection(connectionString))
{
//Set command paramters
SqlCommand loginCommand = new SqlCommand(commandText, loginConnection);
//Set command type to text
loginCommand.CommandType = System.Data.CommandType.Text;
//Add parameter to command
loginCommand.Parameters.AddWithValue("Email", loginInfo.Email);
loginCommand.Parameters.AddWithValue("#Password", loginInfo.Password);
//Open the database connection
try
{
loginConnection.Open();
SqlDataReader loginReader = loginCommand.ExecuteReader();
if(loginReader.HasRows)
{
HttpContext.Current.Response.Write(loginReader.ToString());
while (loginReader.Read())
{
if (loginReader.HasRows)
{
email = loginReader["Email"].ToString();
}
}
}
}
catch(SqlException sqlEx)
{
HttpContext.Current.Response.Write(sqlEx.Message);
}
finally
{
loginConnection.Close();
}
}
return email;
}

Related

Getting SqlException when passing parameters from client-side (React) but not when passing them at server-side

I have an ASP.NET Core app project, SQL Server in the backend and React as the frontend.
When I pass the parameters (must be 1 or 0) to SetGameResults method through Swagger UI (browser) the database accepts the parameters and the table is filled.
But when I pass the parameters through the React client-side to ASP.NET, I get this error:
Inner Exception: Procedure or function 'Set_Game_Result' expects parameter '#user1_res', which was not supplied.
Controller.cs:
[HttpPost]
[Route("SetGameResults")]
public string SetGameResults(byte? user1, byte? user2)
{
if (!(user1 >= 1 && user2 >= 1)) // it passes this condition -
{
DataTable table = new DataTable();
string sqlDataSource = _configuration.GetConnectionString("tictaktoedb1");
SqlDataReader myReader;
try
{
using (SqlConnection myCon = new SqlConnection(sqlDataSource))
{
myCon.Open();
using (SqlCommand myCommand = new SqlCommand("Set_Game_Result", myCon))
{
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#user1_res", user1);
myCommand.Parameters.AddWithValue("#user2_res", user2);
myReader = myCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
if (table.Rows.Count > 0)
{
var JsonResoltString = JsonConvert.SerializeObject(table);
return JsonResoltString;
}
return "No data sent and table returned empty";
}
}
}
catch (SqlException ex)
{
return "Inner Exception: " + ex.Message;
}
catch (Exception ex)
{
return $"Outer Exception: " + ex.Message;
}
}
return "No data sent";
}
React Native
let data= {
us1: gameResult.us1Win,
us2: gameResult.us2Win,
};
const fetchResponse = await fetch(URL, {
body: JSON.stringify(data),
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json; charset=UTF-8',
},
});
const data = await fetchResponse.json();
Be glad for some explanations about that, thanks.

Internal error 500 in ASP.Net after AJAX request

this code working in aspx, but this code in not working in mvc project..
error: POST http://localhost:1208/AWD/Login.asmx/logi 500 (Internal Server Error)
var Email = $("#uwd").val();
var pwd = $("#pwd").val();
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/AWD/Login.asmx/logi",
data: "{'username':'" + Email + "','password':'" + pwd + "'}",
dataType: "json",
success: function (response) {
var obj = response.d;
alert(obj);
if (obj == "01") {
alert("login ok");
}
else {
alert("login no");
}
},
error: function (result) {
alert("Error");
}
});
[WebMethod]
public static string logi(string username,string password)
{
string result = null;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand ilogin = new SqlCommand("select *from login where email='" + username + "' and password='" + password + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(ilogin);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
result = "ok";
return result;
}
else
{
result ="no";
return result;
}
}
Seems its not valid JSON string. try use following:
data: '{"username":"'+ Email + '","password":"' + pwd + '"}'.
first try Restart your IIS
and pleas post your ASP code to check it i think you post parameter to get page or you don't use the authentication attributes
and the url you use is /logi !! is that right
i think wrong url it is /login

ASP.NET: Relative Path with Root Operator('~') in Client side

I have implemented a web page with asp.net.
It has some ajax function.
in ajax function, Get a image path from server side webMethod.
The image path consist of root operator, for example "~/Images/Icons/SendEmail.png".
In Client side, I want to set image path to img element.
How can I set the image from this relative path?
Here is my code snippet.
Please refer this and give me some advices. Thank you in advance.
Clien side
function DrawImage() {
$.ajax({
type: 'POST',
url: '../Management/GetImage',
data: '{Index: "' + Index + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (resp) {
if (resp.d == null) {
return;
}
var ImagePath = resp.d;
var image = document.createElement('img');
image.src = ImagePath; // e.g. "~/Images/Image.png"
$(imageDiv).append(image);
},
error: function (msg) {
alert("Failed to Image: " + msg.statustext);
}
});
}
Server Side WebMethod
[WebMethod]
public static string GetImage(string Index)
{
string conStr = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(conStr);
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Select_ImagePath";
command.Parameters.AddWithValue("#Index", Index);
string imgPath = "";
try
{
conn.Open();
SqlDataReader dataReader = command.ExecuteReader();
if (dataReader.Read())
{
imgPath = (string)dataReader["Image_Path"]; // e.g. "~/Images/Image.png"
}
}
catch (Exception err)
{
}
finally
{
conn.Close();
}
return imgPath;
}
I solved this problem by just implementing some function in javascript like below.
function ConvertRelPathToAbsPath(path)
{
var absPath ="";
if (path.length > 0)
absPath = window.location.protocol + '//' + location.host + path.substr(1);
return absPath;
}

Binding Lable from webmethod using ajax

Hi guyes i am trying to read data from webmethod and pass the value to my lable in aspx page. for this i take a use of Ajax and webmethod. my problem is when i am not able to bind data on success to my lable controle.
my .asmx page.
public static string str;
[WebMethod]
public string GetEmployeeDetail(string name)
{
str = name;
Get(str);
string daresult;
daresult = Get(str);
return daresult;
}
[WebMethod]
public string Get(string str)
{
List<string> rst = new List<string>();
using (SqlConnection con = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
rst.Add(string.Format("{0}", dr["practice_short_name"]));
}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(rst);
}
}
}
and here is my ajax call function in aspx page.
function fun() {
var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");
$(ddlpsn).change(function () {
var s = $(this).val();
$.ajax({
type: 'POST',
url: 'AutoCompleteService.asmx/GetEmployeeDetail',
data: '{name: "' + s + '" }',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
//i think i need to do some changes in here but not getting what to do.
$('#lblpriority').text(data.val);
},
error: function (error) {
console.log(error);
}
});
});
};
You need to change data.val to data.d. Data returned from WebMethod is contained in d property if you have not explicitly defined your own property for returned data.
$('#lblpriority').text(data.d);
You need to make your WebMethod static in order to called by ajax.

Sending mail is not working on my site

I have a site online, its not finished..
my problem is at the bottom "contact-us" forum.
its not sending any mail..
*in my local host it is working and i have no idea what is the different
java script code for sending the mail:
function sendEmail_click() {
if (Page_ClientValidate()) {
// $("#LoadingImage").show(); //Show loading image
var settings = {
'data': getData(),
'url': "Handlers/SendMail.ashx",
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8'
};
sendEmail(settings);
};
}
function getData() {
var data = {
'firstName': $('#txt_fName').val(),
'lastName': $('#txt_lName').val(),
'phone': $('#txt_phone').val(),
'bName': $('#txt_bName').val(),
'fromMail': $('#txt_email').val(),
'Message': $('#txt_message').val(),
'checkBox': $('#chk_ad').prop('checked')
};
return data;
}
function showOrHideLoadingImage(id, action) {
if (action == "show") {
$("#" + id).show();
} else {
$("#" + id).hide();
}
}
function sendEmail(settings) {
var success = false;
showOrHideLoadingImage("LoadingImage", "show");
$.ajax({
type: "POST",
contentType: settings.contentType,
data: settings.data,
url: settings.url,
dataType: "json",
success: function (data) {
$('#checkMark').css('display', 'inline').fadeOut(20000); //Show check mark image+text
$(".contact_input").each(function () {
$(this).val("");
})
success = true;
},
error: function (data) {
$('#xMark').css('display', 'inline').fadeOut(12000); //Show xMark image+text
success = false;
}
}).always(function () {
showOrHideLoadingImage("LoadingImage", "hide");
});
return success;
}
Handler:
public void ProcessRequest (HttpContext context) {
//add try catch
// Loads parameters into variables
string firstName = context.Request.Form.Get("firstName");
string lastName = context.Request.Form.Get("lastName");
string phone = context.Request.Form.Get("phone");
string bName = context.Request.Form.Get("bName");
string senderEmail = context.Request.Form.Get("fromMail");
string message = context.Request.Form.Get("message");
string chkBox_ad = context.Request.Form.Get("checkBox");
bool mailSent = Mail.SendEmail(firstName, lastName, bName, phone, senderEmail, message, chkBox_ad);
context.Response.ContentType = "text/plain";
if (mailSent)
{
context.Response.Write("true");
}
else
{
context.Response.Write("false");
}
}
Send mail function:
public static bool SendEmail(string firstName, string lastName, string bName, string phone, string senderEmail, string message, string chkBox_ad)
{
chkBox_ad = chkBox_ad == "true" ? "..." : "...";
// Email sending
string eBody = "...";
eBody += "...";
eBody += "...";
eBody += "...";
eBody += "...";
eBody += "...";
MailMessage MyMailMessage = new MailMessage("XXX#gmail.com", "XXX#gmail.com", "smbJob", eBody);
MyMailMessage.IsBodyHtml = true;
try
{
SmtpClient SMTPServer = new SmtpClient();
SMTPServer.Send(MyMailMessage);
return true;
}
catch
{
return false;
}
}
I am not sure if this is the exact code you need but it should get you going in the correct direction. Make sure you are using the correct using directive as well.
System.Net.Mail.MailMessage mail =
new System.Net.Mail.MailMessage("xxx#gmail.com", "xxx#gmail.com");
try
{
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.Credentials = new System.Net.NetworkCredential()
{
UserName = "someemail#address.com",
Password = "password"
};
client.EnableSsl = true;
}
catch
{
display some error from here
}
for anyone having that issue, I managed to solve it:
1) this is the right web.config setting(replace "info#yourDomainName.com" with your "goDaddy" email address
<system.net>
<mailSettings>
<smtp from="info#yourDomainName.com">
<network host="relay-hosting.secureserver.net" port="25"/>
</smtp>
</mailSettings>
As I understand, "goDaddy" dont allow sending mails from third-party accounts, like gmail(after live chatting with them), dont have to write user name & passowrd and its not through SSL.
your from address should be your "goDaddy" email address

Resources