value is undefined in emberjs nested view - javascript-framework

i have a script handlebar..
<script id="ownerItem" data-template-name='ownerItem' type="text/x-handlebars">
{{value.UserName}} <button {{action "remove" on="click"}}>Remove</button>
</script>
And its view..
ResAdmin.ownerView = Ember.View.extend({
templateName: 'ownerItem',
remove: function() {
var selectedRest;
selectedRest = ResAdmin.adminController.get('selectedRestaurant');
alert(value.RestaurantOwnerID);
return $.ajax({
url: '/api/RestaurantOwner/' + value.RestaurantOwnerID,
cache: false,
type: 'delete',
data: {
RestaurantID: selectedRest.RestaurantID,
MethodOverride: 'delete'
},
dataType: 'jsonp',
success: function(data) {
return ResAdmin.adminController.getRestaurantList();
}
});
}
});
and in some other view i am using this view like
{{#each ResAdmin.adminController.selectedRestaurant.Owners}}
{{view ResAdmin.ownerView valueBinding="this" content="this"}}
{{/each}}
but i am getting error(value is not defined) when user click on remove button of my nested view...can anybody help me ??

value is a property of the ownerView so you need to qualify it with this.get('value')
e.g.
this.get('value').RestaurantOwnerId

Related

On success, div is loading only once through AJAX

I am trying to reload the table on every successful quantity change and row deletion in add to cart using ajax. But the table is getting reloaded only once after that no change is being observed.
Here is the code:
<script type="text/javascript">
$(".update-cart").change(function (e) {
e.preventDefault();
var ele = $(this);
$.ajax({
url: '{{ route('update.cart') }}',
method: "patch",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id"),
quantity: ele.parents("tr").find(".quantity").val()
},
success: function (response) {
$("#cart").load(" #cart");
//alert("This is working");
}
});
});
$(".remove-from-cart").click(function (e) {
e.preventDefault();
var ele = $(this);
if(confirm("Are you sure want to remove?")) {
$.ajax({
url: '{{ route('remove.from.cart') }}',
method: "DELETE",
data: {
_token: '{{ csrf_token() }}',
id: ele.parents("tr").attr("data-id")
},
success: function (response) {
$("#cart").load(" #cart");
}
});
}
});
Button id b1 can be clicked only once, id b2 can be live clicked.
function why(e) {
e.preventDefault();
alert("You clicked " + e.target.id);
$("#myDiv").html('<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>');
}
$("#b1").click(why);
$(document).on("click", ".button", why);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
<button id="b1" type="button">Click Me!</button><button id="b2" class="button" type="button">Click Me!</button>
</div>

Ajax success function not receiving data ASP.NET MVC

I can add the data to the database correctly, but Ajax success function is not working. I always get the error function :
View:
<div id="dvform">
<!-- some data-->
<input type="submit" value="submit" id="btnsubmit" />
</div>
<script>
$(document).ready(function () {
$("#btnsubmit").click(function () {
addAppointment();
});
});
function addAppointment (){
$.ajax({
type: 'POST',
url: '/FuelerAppointments/Create',
contentType: 'application/json; charset=utf-8',
dataType: "html",
data: $("dvform").val(),
success: function (data) {
swal("Done!", "The appointment was saved successfully!", "success");
},
error: function (data) {
swal("Error deleting!", "Please try again", "error");
},
});
}
Controller :
[HttpPost]
public ActionResult Create(FuelerAppointment fuelerAppointment)
{
return Json(fuelerAppointment, JsonRequestBehavior.AllowGet);
}
First you should change dataType: "html", to dataType: "json",
and create FuelerAppointment object before the $.ajax():
var fuelerAppointment = {};
fuelerAppointment.Name = $("#Name").val();
and then the data in ajax method
data: '{fuelerAppointment: ' + JSON.stringify(fuelerAppointment) + '}',
For more information check this link Using AJAX In ASP.NET MVC
change dataType: "html" to dataType: "json"
and in data properties should you write like this
var model = {
prop1: prop1Value,
prop2: prop2Value,
...
};
data: {fuelerAppointment: model}
Or
data: JSON.stringify({
fuelerAppointment: {
prop1: prop1Value,
prop2: prop2Value,
...
}
})
Notes: the fuelerAppointment object should behave a sem proprieties in C# class

MVC Razor Ajax call from button click

I'm struggling to get a button click to invoke an Ajax function which then posts to a controller action. Cannot even get a simple message to work (nothing happens when button is clicked). Clearly, I'm missing something fundamental. What is it?
The Ajax script in my Razor form:
<script type="text/javascript">
$('#UseShipAddr').click(function () {
$.ajax({
url: "#(Url.Action("UseShippingAddress", "Checkout"))",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});
</script>
The button that I want to use to invoke the Ajax function:
<input type="button" value="Use Shipping Address" id="UseShipAddr" />
The action in CheckoutController:
// Ajax POST: /Checkout/UseShippingAddress/5
[HttpPost]
public ActionResult UseShippingAddress(int id)
{
return Content("It worked!");
}
Please try this code.
$(document).ready(function(){
$('#UseShipAddr').click(function () {
$.ajax({
url: "Checkout/UseShippingAddress",
type: "POST",
data: { id: 50 },
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
});

jQuery-ui Autocomplete display results wrong

I am using jQuery-ui autocomplete to create a search field with a remote data source. Everything works and I get results, however the results does not display in a list below the textfield like it is supposed to. The results are put in a list and gets displayed at the bottom of the page.
Here is my code:
<script>
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request,response)
{
$.ajax({
url: "<?php echo $this->webroot; ? >portfolios/ajax_clients_dropdown/"+request.term+".json?callback=ajax_clients_dropdown?",
// dataType: "text",
async: false,
//jsonp: "callback",
jsonpCallback: "ajax_clients_dropdown",
success: function(data)
{
var fin = [];
for(a=0;a<10;a++)
{
fin[a]= data[a].value;
}
console.log(fin);
response(fin);
console.log("success");
},
appendTo: "#autocomplete",
position: {'my': 'left top', 'at': 'left top', 'of': '#autocomplete'},
error: function(response){console.log("Fail");}
});
}
});
});
</script>
<div class = "ui-widget" id="container">
<label for ="autocomplete">Clients</label>
<input id = "autocomplete" style ="" autocomplete = "on">
</div>
It doesn't matter weather I do the appendTo with #container or #autocomplete, it does nothing.
Here is the result that's supposed to be displayed:
["3434a62c bf592581", "a3ee7766 7894a7e0", "ea41d8ec 4e7df334", "919f6fac 96d4cdf0", "24ecac17 bfbed443", "f0270fc4 a2659300", "ea803fac 94b43df4", "5337467f 1a41e158", "fc54b844 0a19b69e", "a7393c7b aaea998b"]
Does anyone have an idea why this is happening?
I think that there might be a few issues here. If you just want the default behaviour for displaying, then you shouldn't need to mess with appendTo or position. Try the following:
<script>
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request,response) {
$.ajax({
url: "<?php echo $this->webroot; ?>portfolios/ajax_clients_dropdown/"+request.term+".json?callback=ajax_clients_dropdown?",
// dataType: "text",
async: false,
//jsonp: "callback",
jsonpCallback: "ajax_clients_dropdown",
success: function(data) {
var fin = [];
for(a=0;a<10;a++)
{
fin[a]= data[a].value;
}
console.log(fin);
response(fin);
console.log("success");
},
error: function(response){console.log("Fail");}
});
}
});
});
</script>
<div class="ui-widget" id="container">
<label for="autocomplete">Clients</label>
<input id="autocomplete" style="" autocomplete="on">
</div>
Except for the data source, which you say is working, this should be the same as what I have here.
Edit: This answer doesn't fix the problem, see comments for details.
Your appendTo and position properties have been assigned to the AJAX request, not to the autocomplete call. It's easier to see with the indentation fixed.
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request,response) {
$.ajax({
url: "<?php echo $this->webroot; ?>portfolios/ajax_clients_dropdown/"+request.term+".json?callback=ajax_clients_dropdown?",
// dataType: "text",
async: false,
//jsonp: "callback",
jsonpCallback: "ajax_clients_dropdown",
success: function(data) {
var fin = [];
for(a=0;a<10;a++)
{
fin[a]= data[a].value;
}
console.log(fin);
response(fin);
console.log("success");
},
error: function(response){console.log("Fail");}
});
},
appendTo: "#autocomplete",
position: {'my': 'left top', 'at': 'left top', 'of': '#autocomplete'}
});
});
For those of you who have this issue, first make sure you go here:
https://jqueryui.com/autocomplete/
And you are referencing the correct css and jquery files. Next, this was my issue in ASP.NET MVC 4. I created a bundle, using
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/core.css", .....
but when I referenced it in my layout page, instead of calling #Styles.Render("~/Content/themes/base/css") I was calling #Scripts.Render("~/Content/themes/base/css").
This caused
<script src="/Content/themes/base/jquery-ui.css"></script>
to be inserted rather than
<link href="/Content/themes/base/jquery-ui.css" rel="stylesheet"/>
so for those of you running into this situation using MVC, that could be it, or you may just not be referencing the correct css and js files properly.

Refresh jQuery datatable table

Been plenty of questions about this but I never found one that worked for me. I have a plain and simple HTML table whos body is being filled with rows from an AJAX call.
Then I want to update the table with DataTable plugin but it does not work.
I have a HTML table that looks like this:
<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In my jQuery pageload
$(document).ready(function(){
var oTable = $('#myTable').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
And finally my on dropdownlist change function
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
var oTable = $('#myTable').dataTable(); // Nothing happens
var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
The append and so on has been modified to shorten it down, etc so do not focus too much on it.
Basically the question is how to update the table, I can do my AJAX and add new data to the table fine, but the datatable plugin does not update with it.
I've tried other things like
.fnDraw(false);
But it does nothing
While I get an JSON error from
fnReloadAjax()
Any clues on just how to refresh the table?
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
$('#myTable').dataTable().fnDestroy();
$('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
DEMO
I Know this is an old post, but I've just investigated about the problem and I find the easiest way to solve it in DataTable man pages: https://datatables.net/reference/api/ajax.reload%28%29
All you need to call table.ajax.reload();
var table = $('#product_table').DataTable({
"bProcessing": true,
"serverSide": true,
responsive: true,
"ajax": {
url: get_base_url + "product_table", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function () {
$("#employee_grid_processing").css("display", "none");
}
}
});
//call this funtion
$(document).on('click', '#view_product', function () {
table.ajax.reload();
});
I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}
From version 1.10.0 onwards you can use ajax.reload() api.
var table = $('#myTable').DataTable();
table.ajax.reload();
Keep in mind to use $('#myTable').DataTable() and not
$('#myTable').dataTable()

Resources