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 ;)
Related
I have some trouble to send an array of string using ajax to a C# controller.
I tried many things but i can't make it works.
Here is my C# controller :
[HttpPost]
[Route("getavailabilities")]
[Authorize]
public IActionResult GetAvailabilities(string[] data)
{
return StatusCode((int)HttpStatusCode.OK, new
{
data = ""
});
}
Then my ajax call :
function apiExecuteRequest(callback, uri, type, data) {
$.ajax({
url: uri,
type: type,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: (apiReply) => {
callback(apiReply);
},
failure: (xmlHttpRequest, textStatus, errorThrown) => {
callback({ isSuccess: false, error: textStatus + " " + errorThrown, message: xmlHttpRequest.responseJSON });
},
error: (xmlHttpRequest, textStatus, errorThrown) => {
callback({ isSuccess: false, error: textStatus + " " + errorThrown, message: xmlHttpRequest.responseJSON });
}
});
}
function apiExecuteAuthenticatedRequestAsync(callback, uri, type, data) {
apiGetTokenAsync((token) => {
$.ajaxSetup({
beforeSend: (xhr) => {
xhr.setRequestHeader("Authorization", "bearer " + token);
}
});
apiExecuteRequest(callback, uri, type, data);
});
To get my array i use :
var data = this.values2.map(function (item) {return item.ItemId;})
apiExecuteAuthenticatedRequestAsync((response) => {
...
}, apiUrl + 'dashboard/getavailabilities', "POST", data);
What i get is everytime Null.
When i set the parameter to object or dynamic i get : {object}.
I really need your help, and thank you for any advice and help you would provide me.
As you know that the dataType of the request is application/json. So you need to convert the data to Json String using JSON.stringify like so:
var data = this.values2.map(function (item) {return item.ItemId;})
apiExecuteAuthenticatedRequestAsync((response) => {
...
}, apiUrl + 'dashboard/getavailabilities', "POST", JSON.stringify(data));
I'm trying to pass some data (parameter) from client side (html) to the server side (C# code-behind) to a method, this is done using AJAX in JSON format, but I'm getting the following error:
Unknown Web Method
my AJAX code is:
var jsonObj = { "sCriterion": sCriterion };
$.ajax({
type: "POST",
url: "NewToken.aspx/GetSelection",
data: jsonObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert(data);
alert("We returned: " + result);
}
});
and this is my code-behind method:
[WebMethod]
private static string GetSelection(string selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
var jsonObj = json.Serialize("proceeded");
return jsonObj;
}
The method should be public static to work. Not private !
[WebMethod]
public static string GetSelection(string selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
var jsonObj = json.Serialize("proceeded");
return jsonObj;
}
Your GetSelection method must be public, but you set it private.
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.
I have the following ajax call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/LoadCount.aspx/GetCounts",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
alert(myObj.length);
for (var i = 0; i < myObj.length; i++) {
alert(myObj[0]);
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I am getting undefined when I alert the length
Here's my Method in my LoadCount.aspx
[WebMethod]
public static string ObtenerContador()
{
List<MenuItem> menu =(List<MenuItem>)HttpContext.Current.Session["MenuItems"];
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (MenuItemAMostrar item in menu)
{
dic.Add(item.ControlID,1);
};
return new JavaScriptSerializer().Serialize(dic); //or any other suggested serialization method
}
this is what I am getting in the success function:
{"MenuCLESAAsignar":1,"MenuOCGestores":1,"MenuOcAAutorizar":1,"MenuOcAAutorizarBanco":1,"MenuOCGestoresObservadas":1,"MenuCLESActivos":1,"MenuParametros":1,"MenuCLESConAddendaAAprobarSup":1,"MenuPendienteAprobacion":1,"MenuConsultaCLES":1}
The question is, how do I deserialize that dictionary in my ajax success function?
Once deserialized, how do I populate it, obtaining the data?
thanks!
As somebody else mentioned, you just use JSON.parse() to parse the data.
From there it just creates an object, and you can access the data with ..
Like so:
http://jsfiddle.net/SJGLF/1/
var myData = JSON.parse(jsonData);
for(var i in myData)
{
console.log(i + " = " + myData[i]);
}
Are you looking for this?
success: function (data)
{
var myObj = JSON.parse(data.d);
},
I have some JavaScript that calls a function to repopulate a drop down list. There are 2 calls that populate 2 different drop down lists. The both work fine in local Dev. On the server only one works. The one Errors out. I remote debugged and the call reaches the function and the function returns the proper results. Its after it leaves the function that the error occurs. The application is asp.net mvc 3 the server is windows server 2008 iis7.
How can i narrow down what is causing the issue.
<script type="text/javascript">
function getSects(abbr) {
$.ajax({
url: "#Url.Action("SectionSwitch", "Assets")",
data: { abbreviation: abbr },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
// var test = JSON.parse(data);
//alert(test);
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.sectionNum + "\">" + item.sectionname + "</option>";
});
$("#Asset_Section_SectionKey").html(items);
}
});
}
function getDivs(abbr) {
$.ajax({
url: "#Url.Action("DivisionSwitch", "Assets")",
data: {abbreviation: abbr},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function (data2) {
// var test = JSON.parse(data);
//alert(test);
var items = "";
$.each(data2, function(i, item) {
items += "<option value=\"" + item.DivisionKey + "\">" + item.DivisionDescription + "</option>";
});
$("#Asset_Section_Division_DivisionKey").html(items);
}
});
}
$(document).ready(function(){
$("#Asset_Section_Division_Department_DepartmentKey").change(function () {
var abbr = $("#Asset_Section_Division_Department_DepartmentKey").val();
getDivs(abbr);
});
$("#Asset_Section_Division_DivisionKey").change(function () {
var abbr = $("#Asset_Section_Division_DivisionKey").val();
getSects(abbr);
});
});
</script>
Its the function getDivs that is throwing the error. Here are the functions:
public ActionResult DivisionSwitch(int abbreviation)
{
var newdivision = from f in db.Divisions
where f.DepartmentKey == abbreviation
select f;
return Json(newdivision);
}
public ActionResult SectionSwitch(int abbreviation)
{
var newsection = (from t in db.Sections
where t.DivisionKey == abbreviation
select new sectionInfo { sectionNum = t.SectionKey, sectionname = t.SectionDesciption });
return Json(newsection);
}
Change your error properties on your ajax methods to take 3 parameters (jqXHR, textStatus, errorThrown) and alert the errorThrown and textStatus:
error: function (jqXHR, textStatus, errorThrown) {
alert("Error, status: " + textStatus + " error: " + errorThrown);
},
Set up an error handler and see what it has to say
$( document ).ajaxError(function(event, jqxhr, settings, exception) {
console.log(jqxhr);
console.log(exception);
});
The error part of your $.ajax can accept three parameters of type jqXHR, textStatus, errorThrown.
The first parameter is an object of type jqXHR, the other two are strings. You could use jqXHR.responseText to see the error.
$.ajax({ // Some settings
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
// or
console.log(jqXHR);
}
According to jQuery web site, their example suggests following:
$.ajax({ // your settings
}).done(function(data, textStatus, jqXHR) {
// Handle success
}).fail(function(jqXHR, textStatus, errorThrown) {
// Handle error here
});
For more information have a look at jQuery.ajax() and read the Depreciation section.
I appreciate all the help but i decided to rewrite what was being returned similar to what the working call was returning. Apparently the server had a problem with what was being returned.
public ActionResult DivisionSwitch(int abbreviation)
{
var newdivision = from f in db.Divisions
where f.DepartmentKey == abbreviation
select f;
return Json(newdivision);
}
public ActionResult SectionSwitch(int abbreviation)
{
var newsection = (from t in db.Sections
where t.DivisionKey == abbreviation
select new sectionInfo { sectionNum = t.SectionKey, sectionname = t.SectionDesciption });
return Json(newsection);
}
I have now changed to code to this:
public ActionResult DivisionSwitch(int abbreviation)
{
var newdivision = (from f in db.Divisions
where f.DepartmentKey == abbreviation
select new DivisionInfo { DivisionNum = f.DivisionKey, Divisionname = f.DivisionDescription });
return Json(newdivision);
}
I just created a new class to store the result in and narrow it down to the two feilds required.
public class DivisionInfo
{
public int DivisionNum { get; set; }
public string Divisionname { get; set; }
}