I am using json result to populate the textbox and I can see the values are returned to Razor view using alert. But I am unable to bind them to textbox.
in my layout.cshtml i am loading the jquery files.
![This is in the header section of my layout page][1]
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/jquery-ui")
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/Site")
This is my index file,
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
any help is greatly appreciated.
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
async : false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
try the async:false in ajax
You haven't posted your data response, but if it is an array of strings, the following should do it.
success: function (data) {
response(data);
},
Since you've already provided the data in the format that it needs (a label and a value), you don't have to map the data. Just pass it directly into the response.
Related
I need to get the elements that come during search in alphabetical order.
This is my code:
<input type="text" id="refNumber" class="floatLabel" asp-for="ReferenceNumber" required>
Here's my code in jQuery:
//autocomplete
$("#refNumber").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("GetProspectsName", "PlacementRequest")",
/* url: "/PlacementRequest/GetAllProspects",*/
dataType: "json",
data: {
searchText: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.fullName + '-(' + item.referenceNumber + ')',
value: item.referenceNumber,
data: item
};
}));
}
});
},
minLength: 1,
select: function (event, ui) {
prospectDetails(ui.item.data.id);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
This is how my autocomplete appears at the moment.
Step1:
I have defined my script as: on home.aspx page:
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
headers: { "Content-Type": "application/json" },
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Step2:
Call to the script function from button: it's on home.aspx page:
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Step3:
Defined Web method at home.aspx.cs page:
[System.Web.Services.WebMethod]
public static string GetData(string name)
{
return "Welcome";
}
I am getting:
JavaScript runtime error: Unable to get property 'd' of undefined or
null reference
You have to stringify your data:
data: JSON.stringify({ name: "Mobile" })
And use ajax like this:
$.ajax({ ... });
Full script updated:
function ShowCurrentTime() {
$.ajax({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: JSON.stringify({ name: "Mobile" }),
contentType: "application/json",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Try this and tell me if it work :
<script type = "text/javascript">
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);},
failure: function() {
alert("Fail");}
});
}
</script>
Using Selectize.js, I am able to retrieve data from the server but nothing appears in the drop down on the callback. Maybe it is the format of the data?
On the server, I'm using System.Web.Script.Serialization.JavaScriptSerializer to serialize a datatable (C#) and return the JSON object.
At a loss as to why the data isn't rendering.
Code:
<div class="sandbox">
<label for="select-movie">Movie:</label>
<select id="select-movie" class="movies" placeholder="Find a PO..."></select>
</div>
<script class="show">
$('#select-movie').selectize({
valueField: 'ID',
labelField: 'PO',
searchField: 'PO',
create: false,
options: [],
render: {
option: function (item, escape) {
return '<div>' + item.PO + ' ' + escape(item.PO) '</div>';
}
},
load: function (query, callback) {
if (!query.length) return callback();
var dataString = JSON.stringify({
prefixText: query
});
$.ajax({
type: "POST",
url: "Default.aspx/GetUsers",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: dataString,
error: function () {
callback();
},
success: function (msg) {
alert(msg.d);
callback(msg.d);
}
});
}
});
</script>
Data returned from server:
{
"d":"[
{
\"ID\":1,
\"PO\":\"PO/REQ Number\"
},
{
\"ID\":262,
\"PO\":\"this po\"
},
{
\"ID\":264,
\"PO\":\"Test po\"
},
{
\"ID\":267,
\"PO\":\"Test PO 1\"
}
]"
}
The data returned from server (msg.d) is a String. It must be an Array.
You should check your Default.aspx/GetUsers method to return it.
Is it possible to add the following jQuery DataTable?
$('#myDataTable').dataTable({
});
to this query?
$(document).on('click', '#PlayStatisticeight', function (e) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
$('#myDataTable').dataTable({
});
$(function () {
$("#PartialViewTopPlayedTracksList").load('#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")');
});
},
error: function (xhr, textStatus, exceptionThrown) {
var json = $.parseJSON(xhr.responseText);
if (json.Authenticated) {
window.location.href = '/UnAuthorizedUser/UnAuthorizedUser';
}
else {
window.location.href = '/UnAuthenticatedUser/UnAuthenticatedUser';
}
}
});
});
I don't know how and if it is possible to do so? any help is highly appreciated :)
Yes, just call it once the new partial has been added to the DOM, in the success callback function.
success: function (data) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
});
},
you can initialize datatable, after the partialview is appended on the view in the ajax call complete function like this:
success: function (data) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
$('#myDataTable').dataTable({ });
});
}
i have been facing an issue in my loginscreen of my application which is developed with mvc3 and jquery, as i am writing the code for checking login credentials in controller and and that controller event is firing by clciking the buttoon click which is developed using jquery. i would like to navigate someo other page('/Customer/CollaborationPortal') when the login credentials are correct, else i want display message box stating that "credentials are wrong" and this is my code.
JQuery Code
$("#btnGo").click(function (e) {
var RegData = getRegData();
if (RegData === null) {
console.log("Specify Data!");
return;
}
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
Console.Log("success");
error: function () {
//aler('Login error');
Console.Log("error");
}
}
});
});
function getRegData() {
var UserName = $("#txtUserName").val();
var Password = $("#txtPassword").val();
return { "UserName": UserName, "Password": Password };
}
});
Controller Code
public ActionResult IsLoginExsit(BAMasterCustomerDO loginData)
{
if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty (loginData.Password))
{
bool result = Businesss.Factory.BusinessFactory.GetRegistration().IsLoginExist(loginData.UserName, loginData.Password);
if (result)
{
System.Web.HttpContext.Current.Session["UserName"]=loginData.UserName;
return RedirectToAction("/Customer/CollaborationPortal");
}
else
{
ViewData["message"] = "Registration failed";
return View();
}
}
return View();
}
and also it is not entering into "success" and "error" code.
Thanks in advance.
you have specified the error callback inside success callback, move it outside like:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
console.log("success");
},
error: function () {
//alert('Login error');
console.log("error");
}
});
You have error function inside of success function....
This it's what you must have:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
Console.Log("success");
},
error: function () {
//aler('Login error');
Console.Log("error");
}
});
If I were you, I'd return a JSON object to the client like this:
Success:
{
'error' : false,
'redirect' : '/Customer/CollaborationPortal',
'message' : ''
}
Error:
{
'error' : true,
'redirect' : false,
'message' : 'Please do this or that'
}
My jQuery would be:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
if (response.error)
{
alert(response.message);
return;
}
window.location.pathname = response.redirect;
}
});