Fetching JSON data on Ajax button click in .net core - ajax

I am new to Ajax. Trying to fetch JSON data returned from Get webAPI from controllers but on button click nothing rendering on View.
This is how my view look like
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
var id = $(this).attr(id);
$.ajax({
url: '/api/employee', type: "GET", dataType: "json",
data: { id: id },
success: function (data) {
ulEmployees.empty();
$.each(data, function (index, val) {
var fullName = val.FirstName + ' ' + val.LastName;
ulEmployees.append('<li>' + fullName + '</li>')
});
}
});
});
$('#btnClear').click(function () {
ulEmployees.empty();
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="Get All Employees" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees"></ul>
</body>
</html>
This is the JSON data returned by webapi
Can anyone help me what went wrong here? Thanks in advance.

Below should work:
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
var id = $(this).attr('id');
fetch('/api/employee?id=' + id)
.then((resp) => resp.json())
.then(function(data) {
ulEmployees.empty();
$.each(data, function (index, val) {
var fullName = val.firstName + ' ' + val.lastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
})
.catch(function(error) {
console.log(error);
});
});
});

Related

How to call an action method upon selection from the <select> dropdwon in ASP.NET Core 6 MVC?

I created a dropdown using the <select> HTML element. Now I want to call an action after user makes a selection from the list.
<select name="ddAircraft" id="ddAircraft" class="form-control form-select-sm form-select"
asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
I would also like to know if user enter a value in a input box. Then I want to run a Javascript method. How I can do that?
I tried to do onClick but I am getting usual error.
It would help if you could show the details of your error,
I Tried with the codes below:
#{
var sel = new List<SelectListItem>()
{
new SelectListItem(){Text="1",Value="1" },
new SelectListItem(){Text="2",Value="2" },
new SelectListItem(){Text="3",Value="3" }
};
}
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Privacy";
})
});
</script>
<script>
$(function () {
$('#input').change(function () {
window.location.href = "Privacy";
})
});
</script>
<input id="input" value=""></input>
<select id="selectlist" asp-items=sel></select>
The result:
To pass the selected item value ,you could try :
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Home/Privacy?sel=" + $(this).val();
})
});
</script>
The result:
if you want to make a post request, you could try with ajax as below:
<script>
$(function () {
$('#selectlist').change(function () {
var sel = $(this).val();
var input = document.getElementById("input").value;
$.ajax({
url: "Home/Test",
contentType: "application / json; charset = utf - 8",
type: "post",
data: JSON.stringify({
sel: sel,
input: input
}),
datatype: "json",
success: function (data) {
console.log(data);
}
})
})
});
</script>
The result:

SOAP webservice call to a method using jquery ajax that sends 2 parameters, how to catch the responses in a loop

I have a SOAP webservice created in c# (hosted on localhost) called soapService.aspx . It has a method called displayClass(String id, String theDate)
it returns. This returns following json
[{"lesson_id":2,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":"11:22","end_time":"14:22 ","notes":"test test","payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":3,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":4,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3}]
I found this using web service invoke method given on the web service description page.
I want to catch the response using ajax.
So far I wrote this
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data:instructorInput,
contentType:"application/json; charset:utf-8",
success:function(msg){
//process the msg
}
});
}
});
1) How do I invoke the web service method by passing parameters
2) How do i display all these json data in a table? Please help
Edit : Tried to post
data: "{'id': '" + instructorInputID + "','theDate': '" + instructorInputDate + "'}",
THis is the response I get from console
XMLHttpRequest cannot load http://localhost:18324/soapService.asmx/displayClasses. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:17182' is therefore not allowed access.
EDIT Two :
complete code : Still Error.. msg not defined
<pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#findClassBtn").click(function () {
displayClass();
});
function onSuccess(msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "soapService.asmx/displayClasses",
type: "POST",
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: onSuccess(msg)
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="Label1" runat="server" Text="Add Your Id"></asp:Label>
<p>
<asp:TextBox ID="instructorIdText" runat="server"></asp:TextBox>
</p>
<asp:Label ID="Label2" runat="server" Text="Add date (dd/mm/yyyy)"></asp:Label>
<p>
<asp:TextBox ID="instructordateText" runat="server"></asp:TextBox>
</p>
<asp:Button ID="findClassBtn" runat="server" OnClick="findClassBtn_Click" Text="Find Classes" />
<p>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</p>
</form>
<table id="table">
</table>
<pre>
Error: msg is not defined.
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: function (msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
</table>

How ajax working on wame server?

Hi all I am first time starting to learn ajax from website w3schools, and I follow the step by step I'm trying to get an AJAX example working but i'm unable to get it working. could you help me please ? thanks you.
And here is my code
ajax.php
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You can use ajax like this,
<script>
function loadDoc() {
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value e
load_progress(e);
}, false);
return xhr;
},
type: "GET",
url: "ajax_info.txt",
success: function(msg) {
//when success //200 ok
document.getElementById("demo").innerHTML = msg;
},
error: function(jqXHR, textStatus, errorThrown) {
//when error
}
});
}
</script>

ng-grid in from tag with run at server in aspx page

i am calling the ajax function on click of button it returns the json data and i am passing the data to the main.js script file(controller) its getting the data and binding the data to the ng-grid, the question here is whne i put the ng-grid in the from tag it does not dispaly the data
<script type="text/javascript">
$(document).ready(function () {
$("#mybutton").click(function () {
var scope = angular.element(document.getElementById("wrap")).scope(); // to get access all the varibales defined in the contoller
scope.$apply(function () {
$.ajax({
type: "POST",
url: "Website/Nggrid.asmx/GetDataForNgGrid",
success: function (result) {
// console.log(result);
var fd = JSON.parse(result); //parsing the json string
scope.updateMessage(fd);
alert("hi");
},
error: function (xmlhttprequest, Status, thrownError) {
alert(thrownError.toString());
alert(thrownError);
}
});
});
});
});
</script>
this is the function i am calling when the user clicks on button
<body ng-controller="MyCtrl">
<%--<form id="form1" runat="server">--%>
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
<%-- </form>--%>
</body>
this is the main.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope) {
$scope.myData = [];
$scope.updateMessage = function (_s) {
$scope.myData = _s;
// $scope.Enable = true;
};
$scope.gridOptions = {
data: 'myData',
columnDefs: [
{ field: 'Status', displayName: 'Status', width: "*" }
]
};
});
my question is here that when i put ng-grid in the from tag it wont show the data, please give the suggestion on this
<form id="form1" runat="server">
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
</form>

passing model from view to controller using jquery

I have a view
#using staffInfoDetails.Models
#model staffInfo
<link href="../../Content/myOwn.css" rel="stylesheet" type="text/css" />
#{staffInfo stf = Model;
}
<div id="education1">
#using (Html.BeginForm("addNewEdu","Home",FormMethod.Post))
{
#Html.HiddenFor(x=>x.StaffId)
<table>
<tr>
<th>Country</th>
<th>Board</th>
<th>Level</th>
<th>PassedYear</th>
<th>Division</th>
</tr>
<tr>
#Html.EditorFor(x => x.eduList)
</tr>
<tr>
#*<td><input type="submit" value="create Another" id="addedu"/> </td>*#
#*<td>#Html.ActionLink("Add New", "addNewEdu", new { Model })</td>*#
</tr>
</table>
}
<button id="addedu">Add Another</button>
</div>
I want to pass the model staffInfo to controller using jquery as below
<script type="text/javascript">
$(document).ready(function () {
$("#addedu").live('click', function (e) {
// e.preventDefault();
$.ajax({
url: "Home/addNewEdu",
type: "Post",
data: { model: stf },//pass model
success: function (fk) {
// alert("value passed");
$("#education").html(fk);
}
});
});
});
</script>
the jquery seems to pass only elements not whole model so how can I pass model from the view to the controller so that I don't have to write the whole parameters list in jquery
u can give ID to the form by using this
#using (Html.BeginForm("addNewEdu", "Home", FormMethod.Post, new { id = "addNewEduForm" }))
{
}
Then in the script
<script type="text/javascript">
$('#addedu').click(function(e) {
e.preventDefault();
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: $("#addNewEduForm").serialize(),
success: function(data) {
}
});
}
});
</script>
As I can see you trying to submit form with AJAX? Look at serialize function.
$('#addedu').click(function(e) {
e.preventDefault();
var form = $('form');
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(r) {
}
});
}
});
You can get your values with getElementById then send your action:
$(document).ready(function () {
var select = document.getElementById('...');
$.ajax({
type: "get",
url: "get_street_name",
data: { a: select },
success: function (data) {
$('#result').html(data);
}
});
}

Resources