I want to bind Ajax response to knockout but I don't know how to do it? can you help me?
delivery: function (postcode) {
var self=this;
$.ajax({
url: url,
data: {postcode: postcode},
type: 'POST',
dataType: 'json',
context: this,
beforeSend: function () {
$(document.body).trigger('processStart');
},
success: function(response) {
console.log(response);
var res = '';
for(var i=0; i < response.data.length; i++){
res = response.data[i]['date'];
$(".test").html(res).trigger('contentUpdated');
}
$(document.body).trigger('processStop');
},error: function(xhr) {
console.log("Error occured.please try again");
},complete: function () {
$(document.body).trigger('processStop');
}
});
}
I am trying to binding data inside knockout html table.
<td class="col col-carrier"
attr="'id': 'label_carrier_' + method.method_code + '_' + method.carrier_code"
text="method.carrier_title" />
<!-- Column with collapsible trigger -->
<td class="col">
<span class="test" data-bind="text: 'here i want to bind'"></span>
</td>
Related
I am new in ASP.NET Core. I just want to simply load a JSON file's data into a listbox.
Here is the controller class:
public class EmployeeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetEmpList()
{
var empList = new List<Employee>()
{
new Employee { Id=1, Name="Manas"},
new Employee { Id=2, Name="Tester"}
};
return Json(empList);
}
}
And here is the view:
<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
type: "GET",
url: "/EmployeeController/GetEmpList",
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++) {
ddlEmployees.append('<option> ' + data[i] + '</option >');
}
}
}); </script>
Assuming that you are successfully able to make requests to your API endpoint I think the part that needs to be updated is actually your jQuery in the view. Since you're returning a list as JSON, what you'll have in your data argument is an array of objects. So in order to populate the values of the <option> tag with the values in your JSON object, you'll need to access the JSON fields that you define in your Controller.
<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
type: "GET",
url: "/EmployeeController/GetEmpList",
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++) {
ddlEmployees.append('<option value="' + data[i].Id + '"> ' + data[i].Name + '</option >');
}
}
}); </script>
The naming convention for response json in asp.net core is camel case instead of pascal case.
You could add console.log(data) to check the response in Console panel(press F12 in browser). Then you will find the property name in response is camel case.
Change like below:
$.ajax({
type: "GET",
url: "/Employee/GetEmpList", //it should be Employee/xxx instead of EmployeeController/xxx
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++){
ddlEmployees.append('<option value="' + data[i].id + '"> ' + data[i].name + '</option >');
}
}
});
I am passing id of the product to button id and then through Ajax data, I'm sending that product id to the controller
for(var i=0;i<productsJSON.length;i++)
{
var td5 = document.createElement('td');
td5.innerHTML = "<br><button type='button' id="+product.id+"onclick='Addtocart() ' >Add To Cart</button><br>";
}
function Addtocart() {
var quantity = document.getElementsByName("quantity").item(0).value;
$.ajax({
type: "POST",
data: 'pid=' + this.id + '&quantity=' + quantity,
url: "ProductController",
success: function(content) {
console.log(content);
alert('done');
}
});
}
You have to use a JSON object.
Here I set data from an HTML form using the GET method.
$.ajax(
{
type: "GET",
data: $("#form").serialize(),
url: "url",
success: function(data)
{
# Code
},
error: function()
{
# Code
}
}
);
I have this knockout view
var ViewModel = function (data) {
if (data != null) {
ko.mapping.fromJS(data, { UsuarioPersonals: UsuarioPersonalMapping },
self);
}
var self = this;
self.UsuarioPersonals = ko.observableArray();
self.search_UsuarioPersonals = ko.observable('');
var UsuarioPersonalsUri = '/api/UsuarioPersonals/';
function ajaxHelper(uri, method, data) {
self.error(''); // Clear error message
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
self.error(errorThrown);
});
}
function getAllUsuarioPersonals() {
ajaxHelper(UsuarioPersonalsUri, 'GET').done(function (data) {
self.UsuarioPersonals(data);
});
}
self.filteredRecords = ko.computed(function () {
return ko.utils.arrayFilter(self.UsuarioPersonals(), function (rec) {
return (
(self.search_UsuarioPersonals().length == 0 || rec.Email().toLowerCase().indexOf(self.search_UsuarioPersonals().toLowerCase()) > -1)
)
});
});
var UsuarioPersonalsDetail = function (data) {
var self = this;
if (data != null) {
self.Id = ko.observable(data.Id);
self.Email = ko.observable(data.Email);
self.Password = ko.observable(data.Password);
}
}
var UsuarioPersonalMapping = {
create: function (options) {
return new UsuarioPersonalsDetail(options.data);
}
};
// Fetch the initial data.
getAllUsuarioPersonals();
};
ko.applyBindings(new ViewModel());
and html page where i want records be filtered by email field.
<div class="row">
<div class="col-md-3">
email: <input data-bind="value: search_UsuarioPersonals, valueUpdate: 'afterkeydown'" /><br />
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">Filtro</h2>
</div>
<table class="table">
<tbody data-bind="foreach: filteredRecords">
<!-- <tr><td> Nombre contiene: <input data-bind=" value:=" valueupdate: ="" /></td></tr>-->
<!--<tbody data-bind="foreach: filteredRecords">-->
<tr>
<td data-bind="text: Id"></td>
<td data-bind="text: Email"></td>
<td data-bind="text: Password"></td>
</tr>
</tbody>
</table>
</div>
</div>
what is wrong that the filtered results show correctly? So data get from server are filtered with Email field. Everytime page is loaded, all datafield are put in is right data-bind but when i write a value in the input field nothing happen.
When your ajax call returns you are setting UsuarioPeronals equal to the raw data. The data has no observable properties they are just text, so your filter function throws an error when it tries to use Email with parenthesis like it's an observable (... || rec.Email().toLowerCase()...).
function getAllUsuarioPersonals() {
ajaxHelper(UsuarioPersonalsUri, 'GET').done(function (data) {
self.UsuarioPersonals(data);
});
}
You'll need to use the same UsuarioPersonalMapping on it that you reference at the top of your viewmodel or loop through the data returned and create a new UsuarioPersonalsDetail for each one.
Looks like when computed is called, the self.UsuarioPersonals() does not have data. Can you use observableArray instead of computed ? or computed is the requirement?
i get the json response in different div
json response
{"success":"you have not inserted","error":{"name":["The name field is required."],"detail":["The detail
field is required."]}}
ajax code
function postdata(){
var name=$('#name').val();
var detail=$('#detail').val();
var token=$('#_token').val();
$('#post').val('Submiting...');
$.ajax({
type: 'GET',
url: 'posts',
data: "name="+ name + "&detail="+ detail,
success: function(data){
} });
}
get json respons message in this div
<div class="alert alert-info col-ssm-12" id="detail"></div>
<div class="alert alert-info col-ssm-12" id="name"></div>
get Values by .text() or .html()
function postdata(){
var name=$('#name').text();
var detail=$('#detail').text();
var token=$('#_token').val();
$('#post').val('Submiting...');
$.ajax({
type: 'GET',
url: 'posts',
data: "name="+ name + "&detail="+ detail,
success: function(data){
} });
}
Here is my JSON method in controller
public JsonResult GetNotificationForAll()
{
Int64 userid = Convert.ToInt64(Session["UserID"]);
string searchcriteria = string.Format("N.notificationfor ={0}", 1);
PODService.Notification[] notification = service.GetNotificationBySearchCriteria(searchcriteria);
return Json(notification, JsonRequestBehavior.AllowGet);
}
Here is my script code for JSON method:
var URL6 = "/Home/GetNotificationForAll";
$.getJSON(URL6, "", function (data) {
var x = { "padding-left": "10px" };
$.each(data, function (index, value) {
$("<td>"
+ value["Notification_Name"]
+ "</td>")
.appendTo("#Allnotification").css(x);
});
});
Here is my view:
<div id="Allnotification" style="color:White;float:left;margin-left:10px"> </div>
I want to show data without page refresh.
i have found the solution.
function NotificationForALL() {
$("#Allnotification").empty();
$.ajax({
type: "GET",
url: "#Url.Action("GetNotificationForAll", "Home")",
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function(index, element) {
var x = { "padding-left": "10px" };
$("<td>"
+ element["Notification_Name"]
+ "</td>") .appendTo("#Allnotification").css(x);
});
setTimeout(function(){NotificationForALL();}, 900000);
}
});
}
NotificationForALL();
Hope it will help to someone