Angular js Button click - javascript

I have created a button which on click gives an ajax call and the server response obtained through ajax is binded to table using angular js. The issue is according to me on first click of the button itself the data must appear on the webpage.But this happens on second click of the button.I am able to sort and filter data properly but the problem is i need to click button two times separately before it fetches the table
<script>
var fooddata = angular.module("fooddata", []);
fooddata.controller("myCtrl", function ($scope) {
$scope.binddata = function () {
$.ajax({
type: "POST",
url: "ASSIGN.aspx/OnDataFetch",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
);
</script>
<body>
<div id="id001"></div>
<div ng-app="fooddata" ng-controller="myCtrl">
// enter code here
<button ng-click="binddata()">Data Fetch</button>
<div>Sort by:
<select ng-model="sortExpression">
<option value="food_id">Food id</option>
<option value="type">Type</option>
<option value="priority">Priority</option>
</select>
</div>
Filter By Any:
<div><input type="text" ng-model="search" /></div>
<table border="1" cellpadding="10">
<tr><td>Food id</td><td>Type</td><td>priority</td></tr>
<tr ng-repeat="items in foods.d | orderBy:sortExpression | filter:search">
<!-- <td ng-repeat="cell in items">{{cell}}</td> -->
<td>{{items.food_id}}</td>
<td>{{items.type}}</td>
<td>{{items.priority}}</td>
</tr>
</table>
</div>
</body>

You problem is, you are using $.ajax. which won't running digest cycle resultant the binding will not update on html/scope. You must use $http instead of $.ajax, If you use $http angular will run digest cycle when the ajax completed.
Code
$http({ //<-- make sure you have added $http dependency on controller
method: "POST",
url: "ASSIGN.aspx/OnDataFetch",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).
success(function(response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
}).
error(function(response) {
alert(response.d);
})
Use jQuery ajax while angular provided you $http is problematic
and considered as bad practice.

Define you controller like this:
fooddata.controller("myCtrl", function ($scope, $http) {
And then do this do run ajax
$scope.binddata = function(){
var request = $http({
method: "post",
url: "yourAjaxFile.php",
data: {
//data
},
//contentType,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
$scope.foods = data;
});
}

In case of Async calls like $.ajax(), the angular scope is no longer updated on inside events. So you need to do $apply manually to apply the updates or you can go forward with any of the other solutions provided by others. They too work well.
<html><head><script>
var fooddata = angular.module("fooddata", []);
fooddata.controller("myCtrl", function ($scope) {
$scope.binddata = function () {
$.ajax({
type: "POST",
url: "ASSIGN.aspx/OnDataFetch",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
if(!$scope.$$phase)
$scope.$apply();
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
);
</script>
<body>
<div id="id001"></div>
<div ng-app="fooddata" ng-controller="myCtrl">
enter code here
<button ng-click="binddata()">Data Fetch</button>
<div>Sort by:
<select ng-model="sortExpression">
<option value="food_id">Food id</option>
<option value="type">Type</option>
<option value="priority">Priority</option>
</select>
</div> Filter By Any:
<div><input type="text" ng-model="search" /></div>
<table border="1" cellpadding="10">
<tr><td>Food id</td><td>Type</td><td>priority</td></tr>
<tr ng-repeat="items in foods.d | orderBy:sortExpression | filter:search">
<!-- <td ng-repeat="cell in items">{{cell}}</td> -->
<td>{{items.food_id}}</td>
<td>{{items.type}}</td>
<td>{{items.priority}}</td>
</tr>
</table>
</div>
</body>
</html>

Related

Passing Table data from view to controller not working

I am trying to send the data of my table with dynamic values to the controller.
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td class="AutoId">#item.AutoID <input type="hidden" name="AutoID" value="#item.AutoID" /></td>
<td class="hove" name="text"> <b>#item.Text</b><br /><label></label></td>
<td class="Active">#item.Active</td>
<td id="oBy" name="OrderBy">#item.OrderBy</td>
</tr>
}
}
above is the table structure
I am using below ajax call to send one field for example...
<script>
$(document).ready(function () {
alert("Test 1");
$("#btnSave").click(function (e) {
alert("Test 2");
$.ajax({
type: "POST",
url: '#Url.Action("LookupManagementUpdate", "Admin", new { Area = "Admin" })',
data: $(".hove").val(),
dataType: 'json',
async: false,
success: function (response) {
Success = true;
},
error: function (response) {
},
});
});
});
</script>
Below is my controller code
public string LookupManagementUpdate(string text)
{
return "answer"+Request["text"]+text;
}
I tried using both Request and parameter method to fetch the data but it does not display the table data.
This is a c# mvc ado.net based project
try using Ajax.BeginForm and ajaxOptions Onsuccess

ajax jQuery auto reload data when browser page refresh

how can i use ajax jquery to autoreload data from selected field related data to input field? it's only working when i am using $("#id_books").change(function()! but i want to load data when browser page refresh or on page load....
create-form.html
<select name="books" class="form-control" id="id_books">
<option value="1" selected="">haxer</option>
<option value="2">django</option>
<option value="3">HCV</option>
<option value="4">python</option>
<option value="5">CBC</option>
</select>
<div class="form-group col-sm-2 text-center">
<input class="form-control" type="text" name="price" id="priceData" readonly>
</div>
<script>
$("#id_books").load(function () {
var id = $(this).val();
$.ajax({
url: `http://localhost:8000/report/${id}`,
data: { 'id': id },
dataType: 'json',
success: function (response) {
if (response != null) {
$('#priceData').val(response.price);
}
}
});
});
</script>
Try using $(document).ready(), which will fire on page load. e.g:
$(document).ready(function() {
alert("Page has loaded!");
});
You'll most likely need to refactor your code as $(this).val(); won't work (as 'this' is no longer '#id_books')
I've not tested the following (but it should give you an idea), try the following:
<script>
$(document).ready(function() {
loadData()
});
$("#id_books").change(function () {
loadData()
});
function loadData()
{
var id = $("#id_books").val();
$.ajax({
url: `http://localhost:8000/report/${id}`,
data: { 'id': id },
dataType: 'json',
success: function (response) {
if (response != null) {
$('#priceData').val(response.price);
}
}
});
}
</script>

Post Data from MCV is not calling JS function

Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);

MVC Javascript table reload issue

I have a table that is being populated dynamically, and a reload script that refreshes it ever 60 seconds.
<script type="text/javascript" language="javascript">
window.setInterval(function () {
$('#divGrid').load('Home/Index #divGrid>table');
}, 60000);
</script>
I also have a Javascript that calls a partial view on table row click:
<script type="text/javascript" language="javascript">
function showOpenTrData() {
$('#OpenTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetails/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
function showClosedTrData() {
$('#ClosedTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetailsClosed/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
I had it at first without an onclick function but then upon reload it would stop working so I changed it to onclick function, however first time after reload I have to double click the row and after that for the period of 60 seconds till next reload its all fine, after it reloads I have to double click the first time again. Its driving me up the wall.
Please help!
HTML
<table class="table" id="OpenTickets" style="overflow-y:scroll;width:70%;float:left; margin-top:-25px; display:block;">
<tbody>
#foreach (var item in Model.ticketModel.OrderByDescending(x => x.ticket.ID).Where(x => x.ticket.StatusID == 1))
{
<tr onclick="showOpenTrData()">
<td class="columnID" id="ticketID">
#Html.DisplayFor(modelItem => item.ticket.ID)
</td>
<td class="columnSummary">
#Html.DisplayFor(modelItem => item.ticket.Summary)
</td>
<td class="columnAssignee" id="ajaxTest">
#if (item.ticket.Assigned_to_UserID == null || item.ticket.Assigned_to_UserID == 0)
{
#Html.Label("Unasigned")
}
else
{
#Html.DisplayFor(modelItem => item.assignedUser.First_name)
<text> </text>
#Html.DisplayFor(modelItem => item.assignedUser.Last_name)
}
</td>
<td style="font-size:11px; width:10%" class="columnUpdated">
#if ((item.ticket.updated_at == null))
{
#Html.DisplayFor(modelItem => item.ticket.Created_at)
}
else
{
#Html.DisplayFor(modelItem => item.ticket.updated_at)
}
</td>
</tr>
}
</tbody>
</table>
i got it - if anyone else struggles here is the breakdown.
.load method renders any javascript useless as its not part of the same instance any more, hovever on click is a solution but how do you get the object reference?
you pass this in the on click function.
onclick="showTableData(this)"
then you can use the passed event to acquire data from it
cheers
The basic problem here is that you are mixing onclick=... with jQuery bindings .click(...). It is possible to use both on the same page but it becomes confusing and is harder to maintain: Pick one.
The easiest thing (based on your current code) is to kill the jQuery bindings. Try this:
<script type="text/javascript" language="javascript">
function showOpenTrData(ptr) {
$.ajax({
url: 'Home/TicketDetails/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
function showClosedTrData(ptr) {
$.ajax({
url: 'Home/TicketDetailsClosed/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
</script>
Each time the showOpenTrData or showClosedTrData was running, it was adding another jquery bind. If you open your console and check the networks tab you'll see that the ajax functions are then being run multiple times with one click (after the second click).
If you want to just use jQuery, then use this:
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#OpenTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetails/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
$('#ClosedTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetailsClosed/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
Also, delete the onclick=... section in the html or you'll get javascript errors because it is looking for a function that doesn't exist.
EDIT:
I added in the ticketId you needed.

How to get value to the controller from view

I am struggling hard to get value to my controller. Please can some one suggest a way to get value to controller from view. Application is in .Net3.5 and MVC 2 for .Net3.5
The view with jquery and controller is:
The jquery and the html is:
<tr>
<td style ="width: 313px">
<label for="Product Code"> Product
Code
</label>
<select id ="prodList" style = "width:150px">
<option value ="GL ">GL </option>
<option value ="Property" selected="selected">Property </option>
<option value ="Package" >Package </option>
<option value ="Island" >Island </option>
</select>
</td>
<td style="width: 313px"><input type ="button" id="addProd" value ="Add Product" /></td>
</tr>
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.min-vsdoc.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#addProd").click(function() {
//alert("here");
var selectedID = $("#prodList").val();
alert("me 1" + selectedID);
$.ajax({
url: "/WorkFlowTest/ProductSubmission/",
type: 'POST',
data: { productID: $("#prodList").val() },
contentType: 'application/json; charset=utf-8',
success: function(data) {
//alert(data.success);
alert("success");
},
error: function() {
alert("error");
}
});
});
});
</script>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ProductSubmission(string productID, ViewModels.WorkFlowTestViewModel SubmissionModelView)
{
SubmissionModelView.selectedProd = prodSelected ;
return View("Submission", SubmissionModelView);
}
In the jquery function the alert has the selected value, but
for the SubmissionModelView has all properties null and the productId is null too.
Though in browser console I get Source {"productId":"Property"} , but I can not understand why my post does not get any value in the Action ProductSubmission.
Can any one help , I just need the controller to get the selected option value on Post or even a text value on Post. I am not able to get any value from view to controller and my model has also all properties null in POST. Please help
You should convert the object to JSON string by using the JSON.stringify function.
$.ajax({
url: "/WorkFlowTest/ProductSubmission/",
type: 'POST',
data: JSON.stringify({ productID: $("#prodList").val() }),
contentType: 'application/json; charset=utf-8',
success: function(data) {
//alert(data.success);
alert("success");
},
error: function() {
alert("error");
}
});

Categories