Success callback function JQUERY AJAX not working - javascript

I am trying to fetch password from database when username is provided .I am getting the result in POSTMAN, but the success callback function is not getting fired, even the error callback is also not working
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery/jquery-3.5.1.min.js"></script>
<script src="jquery/getpassword.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="dirtext" runat="server" ></asp:TextBox>
<asp:Button ID="dirsubmit" runat="server" Text="Button" OnClick="dirsubmit_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Given below the javascript file getpassword
$(document).ready(function () {
$('#dirsubmit').click(function () {
var x;
var objuser = {
name: $('#dirtext').val(),
};
var param = {
user: objuser
};
$.ajax({
type: "POST",
url: "WebForm4.aspx/GetPassList1",
data: JSON.stringify(param),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hi");
console.log(response);
var result = JSON.parse(response.d);
x = result;
},
error: function (response) {
console.log("error");
}
});
console.log(x);
});
});
Given below is the function GETPASSLIST1
[System.Web.Services.WebMethod]
public static string GetPassList1(User user)
{
using (var db = new userdetailsDBContext())
{
var queryStud = db.UserDetails.Where(s => s.name == user.name)
.Select(s => new { s.pass });
return JsonConvert.SerializeObject(queryStud);
}
}
This is the result I got on postman which indicates that api is working fine still the success or the error callback is not getting fired
{
"d": "[{\"pass\":\"$2a$11$iUGNxBof.6eka5XXSg7M1OR7sxy/enYK7wzF7TlSaaoJulxNcP0Um\"}]"
}
If I remove .click event then the success callback is working but after using .click event it doesn't work

Related

Javascript autocomplete not working in ascx

I have a autocomplete in a grid-view in a ascx file but the autocomplete is not working in the ascx file. I have made several similar autocomplete in other page that work. Why is it that the autocomplete does not work in my ascx file. I have a hypotheses why it does not work but I am unsure how to fix it here it is
I think that the problem is with the following url in the javascript
url: "contratoGerencia.aspx/getSupplierAndComponente"
However I dont know how I should change it don get it to work with the ascx file.Also I found a solution here https://www.codeproject.com/Questions/757769/How-to-Call-Ascx-page-form-JavaScript-Funnction-Of that is almost what I want the only problem is that I also have a textbox in my situation.
Any help would be very appreciated. I hope the following information will help you.
Here is my ascx (ComponentesControler.ascx) code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="../css/autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../scripts/autocomplete.js" ></script>
<asp:TextBox CssClass="gridContractAndComponente" ID="txtContractComponenteFooter" Text="" runat="server" TextMode="MultiLine" Rows="1" />
Here is my ascx.cs (ComponentesControler.ascx.cs) code
[WebMethod]
public static List<string> getSupplierAndComponente(string prefixText)
{
string lv_numero_contrato;
List<string> numeros_contrato = new List<string>();
connectionStringBuilder builder = new connectionStringBuilder();
String connString;
connString = builder.builder.ConnectionString;
string selectStatement = " SELECT numero_contrato FROM erp_contratos ";
using (MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = selectStatement;
cmd.Parameters.AddWithValue("#searchText", prefixText);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
lv_numero_contrato = reader.GetString(reader.GetOrdinal("numero_contrato"));
numeros_contrato.Add(lv_numero_contrato);
}
}
conn.Close();
}
}
return numeros_contrato;
}
Here is the aspx page (contratoGerencia.aspx) were I use the ascx file
<div id="ComponentesSection" class="menusection">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Always" >
<ContentTemplate>
<TWebControl5:WebControl5 ID="Header8" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Here is my javascript file (autocomplete.js)
$(document).ready(function () {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
The problem is in the name of your parameter entered in AJAX, your method expects to receive a parameter named prefixText and not containedText.
Change
data: {'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
with
data: {'prefixText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
The issue can be triggered by the UpdatePanel like explained here:
jQuery $(document).ready and UpdatePanels?
So modify your autocomplete.js like this:
$(document).ready(function() {
SearchSupplierAndComponente();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
See if the console error goes away.

Can't get jQuery and web service to play nice

I've built a simple Bootstrap login form in an ASP.NET WebForms app, like so:
<%# Page Title="" Language="C#" MasterPageFile="~/Main.master" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript">
$(document).ready(function () {
$('#signInBtn').click( function () {
if ($('#MemberName').val() == "" || $('#Password').val() == "") {
e.preventDefault();
return false;
}
var $btn = $(this);
$btn.button('loading');
var formData = {};
formData['MemberName'] = $('#MemberName').val();
formData['Password'] = $('#Password').val();
var json = JSON.stringify({ Member: formData });
$.ajax({
url: "members.asmx/ValidateLogin",
timeout: 30000,
type: 'POST',
data: json,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
var response = JSON.parse(data.d);
alert(response);
},
error: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(jqXHR.responseText);
alert(obj);
}
})
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMain" Runat="Server">
<div id="frm">
<div class="form-inline form-group-sm">
<div class="input-group">
<label for="MemberName" class="sr-only">Email Address :</label>
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="email" required id="MemberName" placeholder="Email Address" class="form-control">
</div>
<div class="input-group">
<label for="Password" class="sr-only">Password :</label>
<input type="password" required id="Password" placeholder="Password" class="form-control">
</div>
<button id="signInBtn" class="btn-sm btn-primary" autocomplete="off" data-loading-text="Wait...">Login</button>
</div>
</div>
</asp:Content>
It connects to a web service, with the following code:
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Script.Services;
using Newtonsoft.Json;
using MCV.Data;
[WebService(Namespace = "http:/myproject.temp.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Members : System.Web.Services.WebService
{
public Members()
{ }
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ValidateLogin(Member NewMember)
{
string name = NewMember.MemberName;
SignInResponse r;
try
{
bool status = MemberDB.SignIn(NewMember.MemberName, NewMember.Password);
if (status)
r = new SignInResponse("1", "OK");
else
r = new SignInResponse("0", "ERR");
}
catch (Exception ex)
{
r = new SignInResponse("-1", ex.Message);
}
return JsonConvert.SerializeObject(r);
}
}
This is not complicated code. The web service simply calls a method in another class to validate the user's email and password and returns a JSON string containing a custom class with the result of the validation.
The problem is, the code fails silently. It doesn't appear to fail, because the Chrome console shows no errors. I added a breakpoint in the web service code to see what it was doing, but the breakpoint is never hit. I don't know where the error is, but it's driving me loopy.
Any thoughts on this?
Two issues:
You're not passing through the NewMember parameter correctly from $.ajax
Pay attention to the spelling of the .asmx file, in your javascript you call it members.asmx/ValidateLogin but in the C# code behind it's called Members with a capital M.Make sure that the case matches.
I just made a change to correctly build up the NewMember from javascript and made sure that the .asmx file in my solution is called members.asmx and it's working now:
$('#signInBtn').click(function () {
if ($('#MemberName').val() == "" || $('#Password').val() == "") {
e.preventDefault();
return false;
}
var json = {
"MemberName": $('#MemberName').val(),
"Password": $('#Password').val()
};
$.ajax({
url: "members.asmx/ValidateLogin",
timeout: 30000,
type: 'POST',
data: JSON.stringify({ NewMember: json }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
var response = JSON.parse(data.d);
alert(response);
},
error: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(jqXHR.responseText);
alert(obj);
}
})
});

Error in Autcomplete TextBox

I need an auto complete textbox. I tried the following code segment:
<input type="text" id="tbx_srchByFn" class="autosuggest" disabled="disabled" value="fieldname" runat="server"
onclick="this.value=''" />
jquery
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "DDL_Home.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('tbx_srchByFn').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
.cs file
using System.Web.Services;
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("constr"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Name from Register where Name LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Name"].ToString());
}
return result;
}
}
}
when I type on text box i didn't get the output.but when I remove runat="server" it works. I just need that in server so that I can take the textbox value from serverside
when I remove runat="server" it works.
I think postback happening in your code. so you must rebind SearchText() function. Add the following javascript in your code.
Try this code :
var prm_lp = Sys.WebForms.PageRequestManager.getInstance();
//Re-bind for callbacks
prm_lp.add_endRequest(function () {
SearchText();
});

Postback event on text changed event

I want to postback on every keypress/textchanged event in textbox but my javascript is not running. Am i missing something...????
My Html textbox is this:
<asp:TextBox ID="Txt_Search" runat="server" AutoCompleteType="Disabled"
onkeypress="Postback();" OnTextChanged="Txt_Search_TextChanged" AutoPostBack="true">
</asp:TextBox>
My Javascript code is this:
function Postback() {
__doPostBack('<%= Txt_Search.ClientID %>', '');
};
My on textchanged event is this:
protected void Txt_Search_TextChanged(object sender, EventArgs e)
{
FolderStructure.Nodes.Clear();
Searchtxt();
}
I create sample projects ASP.NET WebForms and AJAX.
I Suggest you can use AJAX process .NET Generic Handler File. Please you research about Generic Handler file.
Before create Generic Handler file "Search.ashx" and Paste above the code.
public void ProcessRequest(HttpContext context)
{
var search = HttpContext.Current.Request.Form["term"];
//Dummy Data
List<string> searchList = new List<string> { "Red", "Orange", "Ping", "Blue", "White", "Black" };
string result = string.Empty;
if (!string.IsNullOrEmpty(search))
{
searchList = searchList.Where(x => x.ToLower().Contains(search.ToLower())).ToList();
if (searchList != null && searchList.Count() > 0)
{
foreach (var item in searchList)
{
result += "<li>" + item + "</li>";
}
}
}
else
{
result="<li> Not Found </li>";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
and Create Your Search Page, YourFile.aspx, my file name Search.aspx.
ASPX Page Code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication7.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtSearch" class="js-search" value="Search" />
<div class="searchResult">
<ul>
</ul>
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<script>
$(function () {
$(".js-search").on('keyup', function () {
var term = $('.js-search').val();
if (term.length > 2) {
sendSearchRequest({ "term": term });
}
});
function sendSearchRequest(value) {
var datas = $.ajax({
type: "POST",
url: '/Search.ashx',
cache: false,
async: false,
data: value,
success: function (term) {
$('.searchResult').empty();
$('.searchResult').append(term);
}
});
}
});
</script>
</body>
</html>
This example when all three letters entered send ajax request search.ashx file and contains search term and get result on search page.
I hope that helps.
Modify code as below and check
__doPostBack('Txt_Search', '');
here is demo for dynamic search in asp.net.
Your textbox should be:
<asp:TextBox ID="PopertyName" placeholder="Property Name" href="#"
propertyid="" runat="server" class="dropdownAnchor"
autocomplete="off" onkeydown="SearchProperty()"></asp:TextBox>
here we will call a function named searchProperty() onkeydown event.
so, your ajax should be,
function SearchProperty() {
$.ajax({
url: '<%=Page.ResolveUrl("~/Dashboard/NewDashboard.aspx/GetProperty") %>',
data: "{ 'prefix': '" + $("#PopertyName").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//Your code to bind result that received from your back end.
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
};
these function will call a GetPoprty() method on newDashboard.aspx.cs file.
so my back end method is,
[WebMethod]
public static List<Model.Property> GetProperty(string prefix)
{
// Here you get your text in prefix
}

AJAX Call Is Not Working With The Controller Action

Salaamun Alekum
My AJAX Call Is Not Calling The Controller Action In ASP.NET MVC Web Applicaiton Project
Bellow Is My AJAX Call In Javascript And Next Is Controller's Action
AJAX Call
var requestUrl = '/Home/GetCurrentUser';
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
The Controller Action
[SharePointContextFilter]
public JsonResult GetCurrentUser()
{
CurrentUserModel um = new CurrentUserModel();
try
{
Microsoft.SharePoint.Client.User spUser = null;
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title, user => user.Email, user => user.LoginName);
clientContext.ExecuteQuery();
um.Name = spUser.Title;
um.Email = spUser.Email;
um.LoginName = spUser.LoginName;
}
}
SharePointBoxOnline.Common.User u = UserManager.Instance.GetUserByEmail(um.Email);
if (u != null)
{
um.ClientId = u.FK_Client_ID;
um.UserId = u.User_ID;
}
}
catch (Exception e)
{
SharePointBoxOnlineAppWeb.Classes.LogsManager.LogException(e.Message, e.StackTrace, System.Web.HttpContext.Current.Request.Url.ToString(), "Added logging functionality to store the exception information in the Database", DateTime.Now);
}
return Json(um, JsonRequestBehavior.AllowGet);
}
Errors Results In AJAX Are
error.description
Invalid character
status
parsererror
xhr.responseText
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
<link href="/Content/css?v=MDbdFKJHBa_ctS5x4He1bMV0_RjRq8jpcIAvPpKiN6U1" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>An unexpected error has occurred.</h2>
<p>Please try again by launching the app installed on your site.</p>
</div>
</div>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Internet Explorer","requestId":"673b269bf2c74e39a9496d69f3e0b62e"}
</script>
<script type="text/javascript" src="http://localhost:14069/4b2e31c8e2cf413facce9558ed0cb3ff/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
Thank You Stackoverflow And Members Of Stackoverflow Please Let Me Know If You Require Further Details
Thank You
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
});

Categories

Resources