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
Related
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;
}
I am php developer and recently switched to asp, I want to send data to web services and get there but I am unable to come up with a solution.
In php if you want to access data for back-end process purpose we simply use
.Serialize(); method,
for example:
<form id="loginForm">
<input class="form-control" name="UserEmail" placeholder="Email" type="email" required=""/>
</form>
and in Jscript function we will serialize the form, e.g:
var data = $("#loginForm").serialize();
and in process side I can call it by inputs name, But in asp.net I am unable to do the same, I might be missing something or does asp.net do not support such approach at all? I do not know please programmers help me out.
You should use Id property and use stingify() method instead of serialization.
HTML
<input class="form-control" Id="UserEmail" placeholder="Email" type="email" required=""/>
JS
function YesFunction() {
var email= $("#UserEmail").val();
var d= [];
d.push(email);
var jsndta = JSON.stringify({ d: d});
$.ajax({
type: "POST",
url: "wbservices/SearchSchoolInfoAndInventory.asmx/Searchschoolbesicinfo",
data: jsnDta,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var rtnData = r.d; //all returned data...
var respDta = [];
$.map(rtnData, function (item, index) {
var j = [
item.status,
item.msg,
];
respDta.push(j);
});
$.each(respDta, function (key, value) {
var status = value[0];
var msg = value[1];
if (status == true) {
table.html(msg);
} else {
}
}); //1st out loop ends here...
},
error: function (jqXHR, textStatus, errorThrown) {
// $("#responseMovDetails").html(jqXHR + textStatus + errorThrown);
alert("error while loading Purchases Head" + jqXHR + textStatus + errorThrown);
}
});
}
Now create a class and create two public variables and call both variables by creating class object in web service class.
public class RequestResponse
{
public bool status { get; set; }
public string msg { get; set; }
}
[WebMethod]
public List<RequestResponse>ActivatePBudget(List<string> d)
{
RequestResponse r = new RequestResponse();
List<RequestResponse> list = new List<RequestResponse>();
string Email= d[0].ToString();
//establish connection. I have established connection in separate class.
DbCon dbcon = new DbCon();
string constr = dbcon.dbconnection();
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string CheckEmail = "select * from Table_Name where Email= #m";
SqlCommand getcmd= new SqlCommand(CheckEmail,con);
getcmd.Parameters.AddWithValue("#m", Email);
SqlDataReader reader=getbhidcmd.ExecuteReader();
if(reader.Read())
{
r.status = true;
r.msg = "Valid User Or Redirect user to another page";
list.Add(r);
reader.Close();
}
else
{
reader.Close();
r.status = false;
r.msg = "Invalid Email";
list.Add(r);
}
}
catch (Exception ex)
{
r.status = false;
r.msg = "Invalid Email" + ex.ToString();
list.Add(r);
}
finally
{
con.Close();
}
return list;
}
HTML+JS+ WEB-SERVICE
JS:
<script type="text/javascript">
function getProject() {
var data = "";
var strUser = "<%=nowUser%>";
$.ajax({
type: 'post',
url: '<%=AppRoot%>main/BackWebservice.asmx/LoadProjects',
async: true,
dataType: 'json',
data: { strAdmin: strUser },
success: function (result) {
var json = eval(result); //数组
var optionstring = "";
$.each(json, function (index, item) {
//循环获取数据
var name = json[index].Name;
var idnumber = json[index].ID;
optionstring += "<option value=\"" + idnumber + "\" >" + name + "</option>";
});
$("#userProject").html("<option value=\"" + 0 + "\"'>所有项目</option> " + optionstring);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
</script>
WEB-SERVICE
[WebMethod]
public void LoadProjects(string strAdmin)
{
List<Project> mProjects = new List<Project>();
string stuJsonString = "";
bool bManager = false;
using (SqlConnection connection1 = new SqlConnection(Cfg.SqlServer))
{
connection1.Open();
string mstrsql1 = "SELECT * FROM ShuiUser where 账号='" + strAdmin + "'";
using (SqlCommand CMD1 = new SqlCommand(mstrsql1, connection1))
{
SqlDataReader DR1 = CMD1.ExecuteReader();
while (DR1.Read())
{
if (DR1["管理"].ToString() == "1")
{
bManager = true;
}
}
DR1.Close();
}
connection1.Close();
}
using (SqlConnection connection2 = new SqlConnection(Cfg.SqlServer))
{
connection2.Open();
string mstrsql2 = "";
if (bManager)
{
mstrsql2 = "select * from ShuiProject";
}
else
{
mstrsql2 = "select a.* from ShuiProject a,ShuiUser b where a.[编号]=b.[项目] AND b.[账号]='" + strAdmin + "' ";
}
using (SqlCommand CMD2 = new SqlCommand(mstrsql2, connection2))
{
SqlDataReader DR2 = CMD2.ExecuteReader();
while (DR2.Read())
{
Project mProject = new Project();
mProject.ID = Convert.ToInt16(DR2["编号"]);
mProject.Name = DR2["名称"].ToString();
mProjects.Add(mProject);
}
DR2.Close();
}
connection2.Close();
}
stuJsonString = JsonConvert.SerializeObject(mProjects);
//主要是下面的两句 The most important two sentences
Context.Response.Write(stuJsonString);
Context.Response.End();
}
ASPX:
<form runat=”server” id="loginForm">
<asp:Textbox runat=”server” cssClass="form-control" id="UserEmail" placeholder="Email" TextMode=”email” required=""/>
</form>
On Codebehind(.cs):
using Newtonsoft.Json;
var obj=new {
Email= UserEmail.Text.Trim()
};
var j=JsonConvert.SerializeObject(obj);
I have assumed that you are working on webforms.
you must used jsonp in asp
$.ajax({
url: 'you path',
datatype: 'jsonp',
data: {....}
});
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;
}
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.
I am trying use a datatable from a web service method. I can see return value when it's a string data.
This my code and it returns an alert hatada : null
$.ajax(
{
type: 'POST',
url: 'http://localhost:40764/HastaTahlilUyariServisi.asmx/Hello',
data: "{_sTcKimlikNo: '111111111111', _iKlinikKodu:121212, _bAy:12, _iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(ajaxCevap) {
alert('basarili: ' + ajaxCevap); //$('#dv').html(ajaxCevap.d);
},
error: function(xhr, status) {
alert("hatada:" + xhr.responseXML);
},
beforeSend: function() {
alert('gonderilecek');
},
afterSend: function() {
alert('gonderildi');
},
complete: function(xhr, status) {
if (status == 'success')
alert('success' + $.httpData(xhr));
}
}
and this is my webservice method:
[WebMethod]
public DataTable Hello(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
DataTable dt = new DataTable();
dt.Columns.Add("ad");
DataRow rw = dt.NewRow();
rw[0] = _sTcKimlikNo + " " + _iKlinikKodu + " " + _bAy + " " + _iYil;
return dt;
}
How can i see datatable from webservice method?
Thanks in advance.
No Serialization problem, just name your datatable and that will solve the problem.
public DataTable LineChrt() {
string query = "select m.class,sum(m.plannedvisits)" +
"plannedvisits,sum(m.actualvisits) actualvisits from vw_MTD_TgtVsAct_Calls1 m " +
"where 1=1 and m.class in ('A','B','C') and m.month = 6 " +
"group by m.class";
string constr = System.Configuration
.ConfigurationSettings.AppSettings["PocketDCR"];
DataTable data = new DataTable();
SqlDataAdapter LCData = new SqlDataAdapter(query,constr);
LCData.Fill(data);
data.TableName = "ChartData";
return data;
}
I don't think you can return a DataTable from a web service due to serialisation problems. This Microsoft article suggests returning a DataSet instead:
Problems using an XML Web service that returns a DataTable