What I missed in my AJAX Code? - javascript

When user select any value from drop down, then Ajax has to call server and return some values through JSON object.
Here is my Ajax code
//AJAX Security
$('#ddlSecurityLevel').change(function () {
if ($('#ddlSecurityLevel').val() !== 'None') {
$.ajax({
type: 'POST',
url: 'AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=1&ReportName=TotalSales',
contentType: 'application/json; charset=utf-8',
data: 'json',
//dataType: JSON.stringify(Data),
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
//alert("hello");
alert(result.d); // output UNDEFINED
}
function AjaxFailed(result) {
alert("Error");
alert(result.status + ' ' + result.statusText);
}
}
});
Asp.net C# code
public class GetResult
{
public string removedReportName { get; set; }
public string removedColumnNames { get; set; }
public string removedFilterNames { get; set; }
}
public partial class AjaxSecurity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string securityLevelOrUser = Request["securityLevelOrUser"].ToString();
if (securityLevelOrUser.Equals("SecurityLevel"))
{
string jsonString = js.Serialize(getResultBySecurityLevel(Request["SecurityKey"], Request["ReportName"]));
Response.Write(jsonString);
}
else
{
}
}
private GetResult getResultBySecurityLevel(string securityLevel,string reportName)
{
GetResult getResult = new GetResult();
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ReportHide,RColumnName,RFilterName FROM SecurityLevelDetails WHERE SecurityLevel=#SecurityLevel and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#ReportName", reportName);
cmd.Parameters.AddWithValue("#SecurityLevel", securityLevel);
con.Open();
SqlDataReader rd=cmd.ExecuteReader();
while(rd.Read())
{
getResult.removedReportName = rd["ReportHide"].ToString();
getResult.removedColumnNames = rd["RColumnName"].ToString();
getResult.removedFilterNames = rd["RFilterName"].ToString();
}
}
return getResult;
}
}
When I run my Asp.net code with following parameter, It returns values in browser
URL
http://localhost:55047/AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=4&ReportName=TotalSales
Response.Write
{"removedReportName":"1","removedColumnNames":"ItemLookupCode,Department","removedFilterNames":"ExtendedDescription,DepartmentName"}
But the output alert is Undefined

Comment data:'json' and Remove d from alert(result.d);
To access the data in js alert you can write like this,
function AjaxSucceeded(result) {
if(result!=null)
{
alert(result[0].removedReportName +"," result[0].removedColumnNames);
}
}
In your Page_Load method, you need to clear out the output and write your own,
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
Please check this link, this is what you need

Related

how to fix 'captcha validation is required' error in c#

After checking the i'm not a robot checkbox on validation, there's a java script alert "localhost:12345 says null" then when i click "OK" on the alert then go to click the submit button, still says "Captcha validation is required" even after i validated.
This is for my contact us page, validation won't work even after i got new keys which initially i thought were the problem.
C#
public partial class _default : System.Web.UI.Page
{
classes.Common xCommon = new classes.Common();
classes.Email xEmail = new classes.Email();
protected static string ReCaptcha_Key = "6LczL3QUAAAAAGnY8hnA-hgRjHV0q---------";
protected static string ReCaptcha_Secret = "6LczL3QUAAAAADWlVe0IKVERdq----------";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Contact_Submit_Click(object sender, EventArgs e)
{
xEmail.ContactUs_Email(txt_Contact_Name.Text, txt_Contact_Email.Text, txt_Contact_No.Text, ddl_Branch.SelectedItem.ToString(), ddl_Division.SelectedValue,ddl_Type.SelectedValue,txt_Contact_Message.Text, ddl_Branch.SelectedValue);
ltr_MessageReturn.Text = xCommon.Return_Message("contactus", "");
btn_Contact_Submit.Visible = false;
}
[WebMethod]
public static string VerifyCaptcha(string response)
{
string url = "https://www.google.com/recaptcha/api/siteverify?secret=" + ReCaptcha_Secret + "&response=" + response;
return (new WebClient()).DownloadString(url);
}
}
}
JavaScript
var onloadCallback = function () {
grecaptcha.render('dvCaptcha', {
'sitekey': '<%=ReCaptcha_Key %>',
'callback': function (response) {
$.ajax({
type: "POST",
url: "default.aspx/VerifyCaptcha",
data: "{response: '" + response + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var captchaResponse = jQuery.parseJSON(r.d);
if (captchaResponse.success) {
$("[id*=txtCaptcha]").val(captchaResponse.success);
$("[id*=rfvCaptcha]").hide();
} else {
$("[id*=txtCaptcha]").val("");
$("[id*=rfvCaptcha]").show();
var error = captchaResponse["error-codes"][0];
$("[id*=rfvCaptcha]").html("RECaptcha error. " + error);
}
}
});
}
});
};
</script>
I expect the validation to pass after a user has selected all the required images to pass validation, and then submitted. but the output still says validation required.

Bind datatable with jQuery

I am trying to populate a datatable with data from SQL database. I have the following C# code which does return the correct number of records.
public class myClass
{
public int CenterID { get; set; }
public string CenterName { get; set; }
public string LicenseKey { get; set; }
public DateTime ExpiryDate { get; set; }
public string YearID { get; set; }
public DateTime Date { get; set; }
}
[WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static List<myClass> Bind()
{
SqlConnection con = new SqlConnection(
WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
con.Open();
List<myClass> newClass = new List<myClass>();
SqlDataReader rdr = null;
SqlCommand cmd = new SqlCommand("zCenterDetails_get", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
newClass.Add(new myClass
{
CenterID = Convert.ToInt32(rdr["CenterID"]),
CenterName = rdr["CenterName"].ToString(),
LicenseKey = rdr["LicenseKey"].ToString(),
ExpiryDate = Convert.ToDateTime(rdr["ExpiryDate"]),
YearID = rdr["YearID"].ToString(),
Date = Convert.ToDateTime(rdr["Date"]),
});
}
con.Close();
return newClass;
}
The thing that I am struggling with is binding the data with AJAX. This is what I've tried so far but I know it is not correct. Please assist me to get my data into the datatable as I am new to datatables. Thanks
This is what I have so far:
function Bind() {
$.ajax({
type: "GET",
url: "WebForm1.aspx/Bind",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#datatable').DataTable({
data: data,
columns: [
{ 'data': 'CenterID' },
{ 'data': 'CenterName' },
{ 'data': 'LicenseKey' },
{ 'data': 'ExpiryDate' },
{ 'data': 'YearID' },
{ 'data': 'Date' }
]
});
}
});
}

How To access and display the data from database using ajax jquery asp.net mvc

I Am trying to fetch the data from database and display it in the page using ajax and jquery. Am new to this platform so can anyone help me
Model:
public class EmployeeModel
{
public int EmpId { get; set; }
public string EmpName { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
Controller :
private static readonly string connectionString = ConfigurationManager.ConnectionStrings["ConnStringDb1"].ConnectionString;
public ActionResult GetUser()
{
return View();
}
public JsonResult GetAllUser(int EmpId)
{
List<EmployeeModel> employee = new List<EmployeeModel>();
string query = string.Format("Select * From Employee", EmpId);
SqlConnection connection = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
employee.Add(
new EmployeeModel
{
EmpId = int.Parse(reader["EmpId"].ToString()),
EmpName = reader.GetValue(0).ToString(),
Age = int.Parse(reader["Age"].ToString()),
Salary = int.Parse(reader["Salary"].ToString())
}
);
}
}
return Json(employee, JsonRequestBehavior.AllowGet);
}
}
ajax:
#{
ViewBag.Title = "Home Page";
var EmployeeModel = (List<second_day.Models.EmployeeModel>)Model;
}
<div id="id"></div>
<div id="firstName"></div>
<div id="lastName"></div>
<p id="getEmployee">Get Employee</p>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('p#getEmployee').click(function () {
GetEmployeeUsingAjax();
});
});
function GetEmployeeUsingAjax() {
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data:{"EmpId":EmpId},
dataType: 'json',
success: function (data) {
console.log(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
Here i Need to fetch the data when its success else through error if it doesnt
Am new to this platform can anyone help me
function GetEmployeeUsingAjax() {
var EmpId = 2;
$.ajax({
type: 'GET',
url: '#Url.Action("GetAllUser")',
data: { "EmpId": EmpId },
dataType: 'json',
success: function (data) {
alert(data);
//$('#id').text(emp.employee.Id);
//$('#firstName').text(emp.employee.FirstName);
//$('#lastName').text(emp.employee.LastName);
},
error: function (emp) {
alert('error');
}
});
}
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
// your code
}
plus string.Format("Select * From Employee where empid = {0} ",EmpId)
Please Check Below code :
var var EmpId = 2;
var abc = {
"EmpId": EmpId
};
$.ajax(
{
url: '/ControllerName/GetAllUser/',
type: "GET",
async: false,
dataType: "json",
contentType: "application/json;",
data: JSON.stringify(abc),
success: function (result) {
alert(data);
}
});
And Action Should Be :
[HttpGet]
public JsonResult GetAllUser(int EmpId)
{
}
Happy !!

ModelAndView("/authenticationError"); not working

after getting request from ajax to controller i am not able to move to next page through ModelAndView("/authenticationError.jsp");
controller code
#RequestMapping(value = "/ProcessReject,method = RequestMethod.POST" )
public ModelAndView Reject(#RequestParam(value = "StatusComments") String StatusComments,
#RequestParam(value = "ruleIndex") String ruleIndex,
#RequestParam(value = "country") String country,
HttpSession session) throws Exception {
ModelAndView mav ;
System.out.println("StatusComments "+ StatusComments);
System.out.println("ruleIndex "+ ruleIndex);
System.out.println("country "+ country);
String quicklookid = (String) session.getAttribute("quicklookid");
//rejectRuleBusinessLogic.reject(ruleIndex, country, quicklookid, StatusComments);
mav = new ModelAndView("/authenticationError.jsp");
return mav;
Ajax code
function showRejectStatusMsg(value1, value2)
{
$.ajax({
type: "POST",
cache: false,
url: "ProcessViewRule.ncr",
data:"ruleIndex=" +value1 +"&country="+value2,
success: function(response) {
},
error : function(e) {
alert('Error in response...' + e);
}
});
jsp code -
<a href="javascript:showRejectStatusMsg(<c:out value='${List.ruleindex}'/>, '<c:out value="${List.country}"/>')" id="rejectLink" class="navlink" >Reject</a>))
You are doing it wrong..You need to write .jsp and can set the view as
mav.setViewName("list");
Basically
new ModelAndView("welcomePage", "WelcomeMessage", message);
is shorthand for
ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);

My jquery ajax call is not working when I call web services which retrieves data from database

I am new working with jquery ajax calls in fact my first time and, I am running into a issue here my web service is working but for some reason when I try to call it from jquery ajax the data is not retrieve.
Please I've been working the whole day on this and I need to finish it tonight.
My web method is this :
public Didyoumean SayHello(string search)
{
Didyoumean Didyoumean = new Didyoumean();
string cs = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand ("USP_DidYouMean",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#search",search);
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Didyoumean.SearchInput = reader["detail"].ToString();
}
reader.Close();
con.Close();
}
return Didyoumean;
}
my Didyoumean class is this:
public class Didyoumean
{
public string SearchInput { get; set; }
}
my ajax call is this (the error is most likely to be here)
function bla() {
var SearchInput = document.getElementById("#locationSearchInput").value;
var DataObject = { search: SearchInput };
$.ajax({
type: "POST",
url: "/kiosk/EmailCoupon.asmx/SayHello",
data: JSON.stringify({dataObject}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.tags_select a').html(data.d);
},
error: function () {
$('.tags_select a').html("<p>no suggestion</p>")
}
});
}
and finally my html
<input id="Button1" type="button" value="button" onclick="bla()"/>
<div class="tags_select">
Basically what I am trying to do is depending on the data in my database the application give suggestions for spelling errors.
note: do not pay attention to the name of the functions and methods this is just a test.
Your service might be like this
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Didyoumean SayHello(string search)
{
Didyoumean didyoumean = new Didyoumean();
didyoumean.searchInput = "result of " + search;
return didyoumean;
}
}
and your javascript is
function test() {
var SearchInput = "test";
$.ajax({
type: "POST",
url: "/WebService1.asmx/SayHello",
data: JSON.stringify({search:SearchInput}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var didYouMean = data.d;
alert(didYouMean.searchInput);
},
error: function (e) {
console.log(e);
}
});
}

Categories