I can't seem to invoke the c# webmethod from javascript. It seems that the problem is enter code herewith the parameters being transfered to the method.
C# webmethod:
//a method that invokes authentication
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Login(string UserName, string Password)
{
string result = null;
JavaScriptSerializer jsonSer = new JavaScriptSerializer();
try
{
TblUser LoginUser = new TblUser();
bool ans = LoginUser.Login(UserName, Password);
result = jsonSer.Serialize(ans.ToString());
return result;
}
catch
{
result = jsonSer.Serialize("noUser");
return result;
}
}
javascript:
//a function that grabs username and password
function ClientSideLogin() {
var UserName = $('#_txtUsername').val();
var Password = $('#_txtPassword').val();
Login(UserName, Password);
}
//a function to authenticate from client side
function Login(_UserName, _Password) {
// build a datastring in JSON
// only a string type should be passed with paranthesis
$(function () {
$.ajax({ // ajax call starts
url: 'WebServices.asmx/Login', // server side method
data: '{UserName:' + '"' + _UserName + '"' + ',Password:' + '"' + _Password + '"' + '}', // the parameters sent to the server
type: 'POST',
dataType: 'JSON', // Choosing a JSON datatype
contentType: "application/json; charset=utf-8",
success: function (data) // Variable data contains the data we get from serverside
{
if (data.hasOwnProperty('d')) {
resutls = $.parseJSON(data.d); // parse the answer to json format
}
else {
resutls = $.parseJSON(data);
}
var resObj = document.getElementById('result');
resObj.innerHTML = resutls;
}, // end of success
error: function (e) { // handle code in case of error
alert("קרתה תקלה בשרת, אנא נסה שוב מאוחר יותר" + e.responseText);
} // end of error
}) // end of ajax call
});
}
In your function you have
function Login(_UserName, _Password) {
$(function () {
$.ajax({ // ...
Try changing this to simply
function Login(_UserName, _Password) {
$.ajax({ // ...
You can't step into the ajax function (that's the async bit of it!) but you can do the following to help you debug:
function onSuccess(data) { ... }
...
$.ajax({
...
success: onSuccess,
...
});
and the same for error. You can then set breakpoints within these functions and they will hit.
Related
I'm returning the simple JSON output using a jQuery Ajax method from an aspx.cs page using [WebMethod] and the output is not returning properly below is my code
using System.Web.Services;
[WebMethod]
public static string Chart_Symbols()
{
string myJsonResponse = "";
try
{
myJsonResponse = "[{\"symbol\":\"AARTIIND\",\"full_name\":\"NSE:AARTIIND\",\"description\":\"AARTI INDUSTRIES LTD\",\"exchange\":\"NSE\",\"ticker\":\"AARTIIND\",\"TYPE\":\"stock\"}]";
}
catch (Exception ex)
{
throw ex;
}
return myJsonResponse;
}
From that [WebMethod], I'm getting this output:
This is my jQuery Ajax method:
//Calling Method
$(document).ready(function () {
var res = FetchingServiceData();
alert(res);
});
//Returning output using Ajax method
function FetchingServiceData() {
var res = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TV_Chart.aspx/Chart_Symbols",
dataType: "json",
data: "{}",
success: function (data) { },
async: false,
error: function (err) {
console.log("eror is ==> "+err);
}
}).responseText;//.then(res => res.json()).then(symbols => {
// console.log("chart_symbol :- " + JSON.parse(symbols));
// return JSON.parse(symbols);
//});
// res = res.replace("{\"d\":\"[{", "[{");
// res = res.replace("}]\"}", "}]");
// res = res.replace("\\", "");
// res = res.replace("\\", "");
// return JSON.stringify(res);
// return JSON.parse(res);
return res;
}
Once I execute the project Ajax method returning the output like this
{"d":"[{\"symbol\":\"AARTIIND\",\"full_name\":\"NSE:AARTIIND\",\"description\":\"AARTI INDUSTRIES LTD\",\"exchange\":\"NSE\",\"ticker\":\"AARTIIND\",\"TYPE\":\"stock\"}]"}
Image output:
But my output should come like this only:
var res = [{ "symbol": "AARTIIND", "full_name": "NSE:AARTIIND", "description": "AARTI INDUSTRIES LTD", "exchange": "NSE", "ticker": "AARTIIND", "TYPE": "stock" }];
Why am I not getting the correct format in the output from my Ajax method?
Can you suggest what my mistake is?
I'm assuming this point: using res = res.replace("",""); is not a good practice.
i have this jquery code, sending items to controller and download from controller, everything is fine
downloads is fine, i check response from in Chrome Network Tab is okay. but success function never run after process done. (i'm using async:false; already)
$(document).on('click', '#baslat', function (e) {
var token = $("#token").val();
var islemler = [];
var secililer = [];
$.each($("input[class='cc']:checked"), function () {
var islem = {};
islem.IslemTuru = $(this).attr("id");
islemler.push(islem);
});
$.each($("tr[class='sec']"), function () {
if ($(this).children('td:eq(1)').children("input[type='checkbox']").prop('checked')) {
var beyan = {};
beyan.Id = $(this).attr("id");
beyan.TahakkukId = $(this).data("id");
beyan.KisaKod = $(this).children('td:eq(2)').html();
beyan.BeyannameTuru = $(this).children('td:eq(4)').html();
beyan.Ay = $(this).children('td:eq(5)').html().substring(8, 10);
beyan.Yil = $(this).children('td:eq(5)').html().substring(11, 16);
secililer.push(beyan);
}
});
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string",
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});
});
The controller is here. I have to use Thread.Sleep (1000) in the method. because the server on which I want to download files wants 1 second to pass between each request.
public async Task<string> BeyanAl(List<Beyanname> secililer, List<Islem> islemler, string token)
{
bool indir = true;
bool yazdir = false;
bool gonder = false;
foreach (var islem in islemler)
{
if (islem.IslemTuru =="cbyazdir")
{
yazdir = true;
}
if (islem.IslemTuru == "cbgonder")
{
gonder= true;
}
}
foreach (var GelenBeyan in secililer)
{
string YolAdi = YolHazirla(GelenBeyan);
string DosyaAdi = DosyaAdiHazirla(GelenBeyan);
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Beyan", GelenBeyan.Id, "");
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Tahakkuk", GelenBeyan.Id, GelenBeyan.TahakkukId);
}
return "İndirildi";
}
here is chrome response screens
r1
r2
There is no 'string' data type in ajax datatypes make it json or text
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string", <-- make it json or text
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:
[HttpPost]
public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
{
if (pwd == null || repeatpwd == null)
{
ViewBag.Error = "Insira os campos obrigatórios";
}
else
{
if (pwd == repeatpwd)
{
changePwd_Entidades(Session["ID"].ToString(),pwd);
return Json(true,JsonRequestBehavior.DenyGet);
}
else
{
ViewBag.Error = "As palavras chave precisam de ser iguais";
}
}
return Json(false, JsonRequestBehavior.DenyGet);
}
Script:
<script>
$('.alt-btn').on('click', function () {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home")?pwd=' +
$('#Info_pwd').val() + '&repeatpwd=' + $('#Info_repeatpwd').val(),
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
});
I think you are using incorrect id to get value of password field.
And instead of sending both password to code better approach would be just compare your both password values at client side and if they both are same then parse those values to code side other wise ask user to input same password .
That would be better to Send the data in the data parameter while you're using POST method
var data = JSON.stringify({
'pwd': $('#Info_pwd').val(),
'repeatpwd':$('#Info_repeatpwd').val()
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("ChangePwdEnt", "Home"),
data: data,
error: function (e) {
console.log(e);
},
success: function (Changed) {
if (Changed) {
window.location = "Entidades";
} else if (!Changed) {
window.location = "LoginEntidades";
}
}
});
This is for using POST method. If you want to use GET method than it would be fine to pass data in query string.
I met the big one problem with jQuery autocomplete with source .asmx file
here's my code:
$("#enterprise_search").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Services/EnterprisePortal/wsGetFAQQuestions.asmx/GetQuestionsByWord",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "Word="+$('#enterprise_search').val(),
dataType: "json",
success: function (data) {
console.log('Data recieved');
response($.map(data.d, function () {
return {
label: item.Name + '(' + item.Value + ')',
value: item.Name
}
}))
},
error: function (xhr, msg) {
console.log('Database connect error: ' + msg);
}
});
},
minLength: 1,
select: function (e, ui) {
var result = item.Name;
var answer = item.Value;
$('#search-results').append('<p>' + result + ' : ' + answer + '</p>');
},
close: function () {
$("#enterprise_search").val('');
}
});
there is a method of c# or whatever it is (that code is not mine, just for you to take a look)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] //Specify return format.
public string GetQuestionsByWord(string Word)
{
//JavaScriptSerializer YourSerializer = new JavaScriptSerializer();
//return YourSerializer.Serialize(FAQsCOL);
Dictionary<string, string> FAQsCOL = clsFAQBLL.GetFAQCOLByWordInQuestionAnswer(Word);
//Dictionary<string, string> ReturnLinks = FAQsCOL.ToDictionary(m => string.Format("{0}?{1}={2}", clsParameters.clsPages.ENTERPRISE_PORTAL_FAQs, clsParameters.clsQueryString.FAQ_ID, m.Key), m => m.Value);
return JsonConvert.SerializeObject(FAQsCOL);
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)] //Specify return format.
public string GetQuestionByQuestionId(int FAQId)
{
Linq.General.FAQ CurrentFAQ = clsFAQBLL.GetFAQByFAQId(FAQId);
FAQ FAQ = new FAQ();
if (CurrentFAQ != null)
{
FAQ = new FAQ(CurrentFAQ.Question, CurrentFAQ.Answer);
}
return JsonConvert.SerializeObject(FAQ);
}
after all of these I get in console (search for '2'):
jquery-2.1.4.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in {"5":"שאלה - 17","11":"מהו הנוהל לגבי מתמחה אשר מנהלו מסרב לחתום על טופס ההרשמה לבחינה?","20":"מהו נוהל הזכאות לגשת לבחינות התמחות?"}
i tried to push data into array (search for '1'), that's the look: d
:
"{"2":"שאלה 2","3":"שאלה 2","4":"שאלה 2","11":"מהו הנוהל לגבי מתמחה אשר מנהלו מסרב לחתום על טופס ההרשמה לבחינה?","20":"מהו נוהל הזכאות לגשת לבחינות התמחות?"}"
can anyone help me with this? I've lost a lot of time for this sick thing
can't understand is it a mistake or something in webservice or in my jquery function
Replace
data: "Word="+$('#enterprise_search').val(),
with
data: {"Word": $('#enterprise_search').val() },
And again after couple of hours mind**ng gives me an answer by myself:
var searchValue = JSON.stringify($('#enterprise_search').val());
data: {Word:searchValue},
success: function (datas) {
console.log('Data recieved: ' + datas.d);
var data = JSON.parse(datas.d);
$.each(data, function (index, value) {
$('#search-results').append('p' + index + ': ' + value + '</p>');
});
}
hope helps someone, cause I'm not the best on this thing, but shall be ;)
i have this ajax call
function findPICKey() {
filter = document.getElementById('MainCT_dtvJobVac_PIC').value;
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: "{listuser:" + JSON.stringify(resultarr) + ", keyword:'" + JSON.strigify(filter)+ "'}",
dataType: 'json',
url: 'SvcAutoComplete.asmx/GetPICKey',
success: function (result) {
result = JSON.parse(result.d);
document.getElementById('<%= dtvJobVac.FindControl("PICKey").ClientID %>').value = result;
},
error: function (result) {
alert("error getting pic key");
}
})
}
web method
[WebMethod]
public string GetPICKey(List<BO> listuser, string keyword)
{
//List<BO> ListObj = new List<BO>();
//ListObj = (List<BO>)Session["ListPIC"];
//ListObj = listuser;
//string key = string.Empty;
//for (int i = 0; i < ListObj.Count; i++)
//{
// if(ListObj[i].label == keyword)
// {
// key = ListObj[i].value;
// break;
// }
//}
//return key;
return "";
}
for some reason my web method not called, i put a break point, but it does not triggered, what i do wrong here? btw resultarr is an object.
Just checking, but you know your second stringify is spelt wrong?
"JSON.strigify" :)
if you call webservice from localhost, you should check url
eq:
http://localhost/HenryChunag/SvcAutoComplete.asmx
url should be :
url: '/HenryChunag/SvcAutoComplete.asmx/GetPICKey'
I think problem is in
data: "{listuser:" + JSON.stringify(resultarr) + ", keyword:'" + JSON.strigify(filter)+ "'}",
it should be
data: {listuser:"+ JSON.stringify(resultarr) +" , keyword:" + JSON.strigify(filter)+ "},
or
data: {listuser:JSON.stringify(resultarr) , keyword:JSON.strigify(filter)},