Thanks to my previously asked question, I have successfully shown a new Textbox after a users enters text in a previous TextBox.
Now, I would like to only show the new TextBox after the text in the original TextBox has been validated.
The validation will make sure the data in the original TextBox is not in the database.
The text boxes are in an Ajax Update Panel. Unfortunatly, I can not use AutoPostBack events, because it effectively resets the JavaScript, even when using function pageLoad()
.
I would like to use the JavaScript to validate against the database, and so far used this code:
JavaScript on Text.aspx
<script type="text/javascript">
function pageLoad() {
$('#<%: txtRegisterEmail.ClientID %>').on('blur', function () {
$.ajax({
type: "POST",
url: "Test.aspx/CheckEmail",
data: "{Email: '" + ('#<%: txtRegisterEmail.ClientID %>').value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response);
}
});
});
}
function OnSuccess(response) {
$('#<%: txtRegisterEmailConfirm.ClientID %>').slideDown();
}
//'input[name$="txtRegisterEmailConfirm"]'
</script>
Test.aspx.cs
[System.Web.Services.WebMethod]
public static bool CheckEmail(string Email)
{
int counter = 0;
const string strSql = "SELECT memberEmail FROM vwGetMemberDetails";
using (SqlCommand sqlComm = new SqlCommand(strSql, DataConn.Connect()) { CommandType = CommandType.Text })
{
using (SqlDataReader rdr = sqlComm.ExecuteReader())
{
while (rdr.Read())
{
counter = counter + 1;
}
}
}
return counter > 0;
}
The only thing this code does is show the text box (seemingly without validation).
How can I make this work?
Related
I have a text box that I am trying to have autocomplete with values from a database. The code is, however, not doing anything when I begin typing in the text box. Does anyone have any idea how to fix this? The Scripts are in the head of the page.
<asp:TextBox placeholder="Search by job title" runat="server" CssClass="search" ID="searchTitle"></asp:TextBox>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script>
$(function () {
$("#searchTitle").autocomplete({
source: function (request,response) {
var param = { posting_jobPosition: $("#searchTitle").val() };
$.ajax({
url: "jobseekerHome.aspx/GetTitles",
data: JSON.stringify(param),
type: "post",
contentType: "application/json; charset=utf-8",
datafilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) { return {value: item }}))
},
});
},
minlength: 1
});
});
</script>
[WebMethod]
public static List<string> GetTitles(string posting_jobPosition)
{
string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(CS);
List<string> Titles = new List<string>();
string query = string.Format("SELECT posting_jobPosition FROM BusinessJobPosting WHERE (posting_jobPosition LIKE '%{0}%' AND isActive = true)", posting_jobPosition);
OleDbCommand oleCom1 = new OleDbCommand(query, Connection);
Connection.Open();
OleDbDataReader reader = oleCom1.ExecuteReader();
while (reader.Read())
{
Titles.Add(reader[0].ToString());
}
Connection.Close();
return Titles;
}
Thanks guys :)
One possible reason that I see is the ID. Change the id as:
$("#<%=searchTitle.ClientID%>").autocomplete({
related: Accessing control client name and not ID in ASP.NET
I am trying to retrieve a list from C# code to an aspx page using ajax.
this is the ajax function:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: successRetireveGenders,
failure: function (response) {
alert("Error");
}
});
function successRetireveGenders(dataValues) {
alert(dataValues); // displayed [object object]
// but i actually have 2 rows result
alert(dataValues.data); //alert with "undefined"
alert(dataValues.d); //alert with "undefined"
// i try to put loop from 0 to response.d.length
for (var i = 0; i < dataValues.length; i++) {
alert(dataValues.length); //alert with "undefined"
alert(dataValues.d.length); //alert with "undefined"
}
I am always seeing an alert with message:
undefined
c# code:
[System.Web.Services.WebMethod]
public static List<ParticipantGender> getGenderCount()
{
List<ParticipantGender> ListOfParticipantGender = new List<ParticipantGender>();
var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("getGenderCount", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
while (rdr.Read())
{
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
});
}
return ListOfParticipantGender;
}
ParticipantGender class:
public class ParticipantGender
{
public string gender;
public string cnt;
public ParticipantGender()
{
//
// TODO: Add constructor logic here
//
}
public ParticipantGender(string gender, string cnt)
{
this.gender = gender;
this.cnt = cnt;
}
}
EDIT:
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: '{}',
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
var callback = function (data, textStatus, xhr) {
alert("hi"); // not alerted
alert(data + "\t" + textStatus); // not alerted
};
EDIT:
i got in the console:
jsapi:23 A parser-blocking, cross site (i.e. different eTLD+1) script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 jsapi:23 A parser-blocking, cross
site (i.e. different eTLD+1) script,
https://www.google.com/uds/api/visualization/1.0/40ff64b1d9d6b3213524485974f36cc0/format+en,default+en,ui+en,corechart+en.I.js,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message. See
https://www.chromestatus.com/feature/5718547946799104 for more
details. google.loader.f # jsapi:23 fontawesome-webfont.woff2:1 Failed
to load resource: the server responded with a status of 404 (Not
Found)
You should serialize the List<ParticipantGender> to JSON. You can install package Newtonsoft.Json which provides a lot of features.
For your case
using System.Configuration;
using Newtonsoft.Json;
[System.Web.Services.WebMethod]
public static string getGenderCount()
{
var connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var ListOfParticipantGender = new List<ParticipantGender>();
using(var conn = new SqlConnection(connStr))
{
conn.Open();
using(var cmd = new SqlCommand("getGenderCount", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using(var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read()) {
ListOfParticipantGender.Add(
new ParticipantGender
{
cnt = rdr.GetValue(0).ToString(),
gender = rdr.GetValue(1).ToString(),
}
);
}
}
}
}
}
var json = JsonConvert.SerializeObject(ListOfParticipantGender);
return json;
}
Define the Callback function with necessary parameters and assign it to the $.ajax success event.
Also, there is no such event failure for $.ajax instead use error
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
};
Assign this callback to the success event
$.ajax({
type: 'POST',
url: 'admin.aspx/getGenderCount',
contentType: 'application/json',
dataType: 'json',
data: {},
success: callback,
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
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();
}
I'm trying to implement jquery - textbox autocomplete. for this setup a web service.
[WebMethod]
public List<Condition> GetCondition(string term)
{
List<Condition> listCondition = new List<Condition>();
string cs = ConfigurationManager.ConnectionStrings["db5"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spSelCondition", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listCondition.Add(new Condition { ConditionID = rdr["ConditionID"].ToString(), ConditionName = rdr["ConditionName"].ToString() });
}
return listCondition;
}
}
public class Condition
{
public string ConditionName { get; set; }
public string ConditionID { get; set; }
}
WebService works perfectly fine. To populate the textbox with jquery autocomplete this javascript I've written.
<script type="text/javascript">
$(document).ready(function () {
$('#txtCondition').autocomplete({
source: function (request, response) {
$.ajax({
url: 'ibs_ws.asmx/GetCondition',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ term: request.term }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
}
});
})</script>
When I access the webservice it takes the #term as parameter and returns the result with ConditionID and ConditionName in xml formate. But on the webform when I give type anything in the textbox it alerts with [object object].
What could be the problem.
--
Thanks & Regards
May be it will help you. try this
I think you need to use $.map(data.d, function (value, key) {}). here is the example need to update your success code like below then you can get value inside object.
success: function (data) {
response($.map(data.d, function (value, key) {
return {
ConID: value.ConditionID,
ConNAme: value.ConditionName,
}
}))
},
AS you said your service returns conditionID and Name so i used these variable you can match what it returns exactly.
I'm using Asp.Net with C#. I want to add Database names to DropDownList at Runtime. Here is the code.
Code Behind:
[WebMethod]
public void GetDdlList()
{
if (!String.IsNullOrEmpty(txtServer.Text.ToString()))
ServerName = txtServer.Text.ToString();
if (!String.IsNullOrEmpty(txtUnm.Text.ToString()))
UserName = txtUnm.Text.ToString();
if (!String.IsNullOrEmpty(txtPwd.Text.ToString()))
Pwd = txtPwd.Text.ToString();
SqlConnection conn = new SqlConnection("Data Source=" + ServerName + ";User ID=" + UserName + ";Password=" + Pwd);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT name FROM sys.databases";
cmd.CommandType = CommandType.Text;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ddlDbnm.Items.Add(rdr.GetString(0).ToString());
}
conn.Close();
}
Script:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript">
$(document).ready(function () {
$('#<%= ddlDbnm.ClientID %>').click(function () {
PageMethod.GetDdlList();
//alert('hi');
})
});
</script>
When I write GetDdlList() code on button click, it executes successfully. But I don't want to use button click. Instead I want this code to be executed when I click on DropDownList. In above example nothing is happening when I click on Dropdownlist.
You can get the click event of dropdownlist in jquery and then make an ajax call to your method. The following is the code the get click event of the dropdownlist:
$(document).ready(function () {
var isClickToLoad = true;
$('#<%= ddlDbnm.ClientID %>').click(function () {
if (isClickToLoad == false) {
//The following line is not allowing the selection changed value to persist
//But commenting it out will call the server side code just once
//i.e. when first time the dropdownlist is clicked
//You need to handle it
isClickToLoad = true;
return;
}
isClickToLoad = false;
$('#<%= ddlDbnm.ClientID %>').empty();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetDdlList",
data: '{ }',
dataType: "json",
success: function (msg) {
var options = "";
$.each(msg.d, function (index, value) {
options = options + "<option>" + value + "</option>";
});
$('#<%= ddlDbnm.ClientID %>').html(options);
}
});
})
});
The following is the webmethod code:
[WebMethod]
public static List<string> GetDdlList()
{
//This can be your call to database. Hard-coded here for simplicity
List<string> lst = new List<string>();
lst.Add("aaa");
lst.Add("bbb");
return lst;
}
The link here details out how you can use jquery ajax in your code.
Hope this helps
You already have a click event in built with Visual Studio for the ComboBox. Right click on Combox and select properties. In Properties, click Event button (Lightening symbol) and find the event "Click" in it and double click on this even which would automatically create the click event. And you can add the above code to this event and try running it. This should help u in achieving your target. Try this and let me know if this doesnt work for you.
You can use this js to dynamic dropdownlist:
HTML:
<select>
<option>Select Something</option>
<option> </option>
<option> </option>
<option> </option>
</select>
JavaScript:
$(document).ready(function () {
var isClickToLoad = true;
$("select").click(function(e) {
if (isClickToLoad == false){
isClickToLoad = true;
return;
}
isClickToLoad = false;
$("select").empty().html("<option>Loading options</option>");
setTimeout(function() {
$.ajax({
type: "POST",
url: 'your url',
traditional: true,
dataType: "json",
data: {},
success: function(resp) {
$('select').empty();
if (resp.length > 0) {
var listItems = [];
for (var i = 0; i < resp.length; i++) {
listItems.push('<option value="' +
resp[i].Value + '">' + resp[i].Text
+ '</option>');
}
$('select').append(listItems.join(''));
}
}
});
$("select :nth-child(1)").attr("selected", "selected");
}, 500);
});
});
demo