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

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>

Related

Fetching JSON data on Ajax button click in .net core

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);
});
});
});

Ajax call in razor code refreshes the page

I'm populating a folder structure using TreeView in .cs file, rendering it in the view.cshtml. When an item is clicked, I call a js function which makes an ajax call to the web api, gets the file content and supposed to display the result in a TextArea or Div.
The result comes back from web api, and displays it in the textarea momentarily and disappears. I guess it's refreshing the page. But I'm not sure how to prevent it. I have done similar stuffs before, didn't behave so. I'm sure I'm missing something, but I can't tell what I'm missing.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form>
<div style="width: 100%; overflow: hidden;">
<div style="width: 600px; float: left;">
<ul>
#foreach (var node in Model.Nodes[0].ChildNodes)
{
<li>#node.Text</li>
<ul>
#foreach (var f in node.ChildNodes)
{
<li>#f.Text</li>
}
</ul>
}
</ul>
</div>
<div id="divLog" style="margin-left: 620px;overflow:auto;"><textarea id="txtLog" rows="10" cols="50"></textarea></div>
</div>
</form>
<script>
function getLog(fileref) {
var baseURL = window.location.protocol + '//' + window.location.host + '#Url.Content("~")';
var apiUrl = baseURL + "/api/logapi?fileref=" + fileref;
document.getElementById("txtLog").innerText = "";
$(document).ready(function () {
$.ajax({
url: apiUrl,
type: "GET",
success: function (data, textStatus, jqXHR) {
document.getElementById("txtLog").innerText = data;
//document.getElementById("txtLog").innerHTML = data;
//$("#txtLog").val(data);
alert(data);
}
});
});
}
</script>
Maybe another solution for any people coming here. I had the same issue in my Razor pages project when trying to call an Ajax function from a form. The page would call the correct page handler and return the Json result, however the page would always refresh, and the success part in the ajax call would not be called. What worked FOR ME was to REMOVE the form element and replace it with a div. Now the Ajax call returns correctly for me.
<div id="first" class="section"> //WHEN THIS WAS FORM THE PAGE REFRESHED
<div class="section">
#Html.HiddenFor(m => m.PersonId)
#Html.HiddenFor(m => m.ProviderId)
#Html.AntiForgeryToken()
<div class="container2">
<input type="radio" name="group1" id="radio-1" checked="checked">
<label for="radio-1"><span style="font-size:16px;" class="radio">I want to recieve all Emails (personal and marketing)</span></label>
</div>
<button onclick="setPreferences()" class="btn btn-save">Save <i class="fa fa-save"></i></button>
</div>
</div>
And the ajax:
$.ajax({
url: '/UserPreferences?handler=SetPreferences',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(model),
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (response) {
console.log(response);
}
});
I used button instead of anchor link, it works as expected, it doesn't refresh the screen.
<style>
.btn1 {
background-color: transparent;
border: hidden;
}
</style>
<li><input type="button" id="a" value="#f.Text" onclick="getLog('#f.Value')" class="button btn1"></li>
First, remove the Ajax call from the document ready function:
function getLog(fileref) {
var baseURL = window.location.protocol + '//' + window.location.host + '#Url.Content("~")';
var apiUrl = baseURL + "/api/logapi?fileref=" + fileref;
document.getElementById("txtLog").innerText = "";
$.ajax({
url: apiUrl,
type: "GET",
success: function (data, textStatus, jqXHR) {
document.getElementById("txtLog").innerText = data;
//document.getElementById("txtLog").innerHTML = data;
//$("#txtLog").val(data);
alert(data);
}
});
}
Secondly, replace the empty href attribute of the anchor link by href="javascript:;" or href="#".

Pass ASP MVC3 textbox value to Ajax call

I have a simple ASP MVC3 #Html.TextBox that I'm using to input search criteria. However, I need to append the value to the URL in an Ajax call as a query string. How would I go about this? Below is the HTML in the view:
<div class="editor-field">
#Html.TextBox("searchString")
<span onclick='GetCompName(searchString);'>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
And here is the Ajax
function GetCompName(searchString) {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + searchString + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
I will also want to output the returned value into another text box. If anyone knows how to do that that would be really helpful as well. Thanks!
the basic problem with your code is the searchString in onclick='GetCompName(searchString); always gonna be literally "serchString", you must specified the parameter in base the value in the input, like this $('.searchbox').val()
keep your javascript unobstructive.
HTML code
<div class="editor-field">
#Html.TextBox("searchString", null, new { #class = "serachbox" })
<span class="searchbox-trigger">
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
Set de handler for the event span click
$(document).ready(function() {
$('.searchbox-trigger').click(GetProgramDetails);
});
and your ajax request
function GetProgramDetails() {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + $('.searchbox').val() + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}

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);
}
});
}

How do i fire validation message on Button click instead of Submit button

I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)
you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.
I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>

Resources