Whenever I enter a value in the textbox and click on the "Save" button, I want to check if that value already exists in the database. If it does, then I need to display an alert saying "Value already exists". To achieve this, I am using Ajax Javascript along with an asp:Button ("Save") click event:
Ajax Javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("[id*=btnBar]").bind("click", function () {
alert("helloooo");
var chk = {};
chk.requestID = $("[id*=lblGuidId]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBar]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "Demo.aspx/SaveUser",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var val = data.isUserInserted;
alert(val);
if (val == true) {
alert("Barcode No. alredy exist");
window.location.reload();
}
else {
alert("Barcode No. does not exist");
}
},
error: function (data) {
alert("error" + data);
},
});
return false;
alert("End click");
});
});
</script>
HTML code:
<asp:Label ID="lblGuidId" runat="server" Text='<%# Bind("RequestID") %>'></asp:Label>
<asp:TextBox ID="txtBarcodeNumber" runat="server" MaxLength="11" Width="230px" Text='<%# Bind("BarcodeNo") %>' Display="None" OnTextChanged="TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="btnBar" runat="server" Text="Save"/>
c# Code:
public class Check
{
public Guid? requestID { get; set; }
public string barCode { get; set; }
}
[WebMethod]
[ScriptMethod]
public static bool SaveUser(Check chk)
{
bool isUserInserted = false;
string strcon = ConfigurationManager.ConnectionStrings["MasterDB"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
using (SqlCommand cmd = new SqlCommand("Invoice.usp_tbl_Request_Select_CheckDuplicateBarcode_Test", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@RequestID", chk.requestID);
cmd.Parameters.AddWithValue("@BarcodeNo", chk.barCode);
cmd.Connection = con;
con.Open();
isUserInserted = Convert.ToBoolean(cmd.ExecuteScalar());
con.Close();
}
return isUserInserted;
}
However, every time it goes into the else part, even when the data exists in the database. My goal is to show the alert "already exist" if the C# WebMethod bool isuserInserted
returns true, and "does not exist" if it returns false.
Please let me know what might be missing in my code.
Note that this is my first time working with Ajax Javascript.