Calling service from Html - html

i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration that will help me to acheive that??
thanks in advance

JQuery:
function AddLocation(ParentID) {
$.ajax({
type: "POST",
url: "../server.asmx/Save",
data: "{'ID':'0','ParentID':'" + ParentID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var item = document.createElement('option');
item.value = data.d.split("$")[0];
item.text = name;
//do stuff
}
});
}

jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.
function loadData()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'methodurl',
success: methodSuccedded,
error: methodFailure
});
}
function methodSuccedded()
{
//do your logic.
}
function methodFailure()
{
//do your logic.
}

You can do so, using AJAX, and get the response from the server as an JSON object.
var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
var url = "Service1.svc/ajaxEndpoint/";
url = url + "Sum2Integers";
var body = '{"n1":';
body = body + document.getElementById("num1").value + ',"n2":';
body = body + document.getElementById("num2").value + '}';
// Send the HTTP request
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
// Create result handler
xmlHttp.onreadystatechange= function X()
{
if(xmlHttp.readyState == 4)
{
result.innerText = xmlHttp.responseText;
}
}
Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.
See these links for reference:
http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx
http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx

The below link is a pretty decent method from my experience.
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

Related

IformFile in the action controller takes the value as null, value is pass to the action controller using ajax request

I am trying to get the value passed from the ajax request into one of the method in the controller but IFormFile files is null every time.
Here is my ajax request :
uploadFile: function (field, value)
{
var me = this;
var view = me.getView();
var fileuploadControl = me.lookupReference('ImportFile');
var file = fileuploadControl.fileInputEl.el.dom.files[0];
var param = new FormData();
param.append('files', file);
var ajax = Ext.Ajax.request(
{
url: './../XYController/ImportCSVFile',
data: param,
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: { 'accept': '*/*' },
processData: true,
success: function (response, options) {
var result = JSON.parse(response.responseText);
if (mask) {
mask.destroy();
}
Ext.Msg.alert("File Upload Successful");
}
});
},
And this is my Action Controller :
[HttpPost]
[Route("XYController/ImportCSVFile")]
public IActionResult ImportCSVFile(IFormFile files)
{
if(files!=null)
{
//do something
}
}
For file upload , The contenttype needs to be set to false along with the processData option. Otherwise jQuery will not see this as a file upload :
processData: false,
contentType: false,
See code samples from here , that should be same no matter use ExtJS or other Jquery wrapper library .

how to pass serialize data and stringified data together in ajax

I have a ajax function where i am passing two objects:
1) serialize form data object
2) complex object
Ajax function:
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var ViewModel = $("#OffsetBookForm").serialize();
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOrder")",
data: JSON.stringify({ 'OffsetCommonObj': ViewModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
And My ActionMethod:
public ActionResult CreateOrder(EstimationOffsetViewModel OffsetCommonObj,
OffsetCostCalculation obj)
{
// do something here..
}
My problem is, the first object in action method i.e-"OffsetCommonObj" is getting null. What am I doing wrong in the code? Please Help..Thanks.

Not able to get external API data through JQuery

I am trying to get external REST API data through JQuery, but it returs undefined. But when I use my local REST API url, it works. Can anybody explain whats is the problem. Any code sample will be appreciated.
This how i am accessing external Rest API via JQuery.
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies' + '/' + id,
type: 'GET',
dataType: 'jsonp',
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert("company" + x + '\n' + y + '\n' + z);
}
});
}
result is XML so you need to set dataType: "text/xml" and then parse it:
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
I tried to test this but I got: is not allowed by Access-Control-Allow-Origin that is same-origin restriction so make sure you have access to this API or you will have to do it on the server using CURL in PHP for example.
Your are getting id variable in the function you showed in your question, but you are no using it,
if you want to send it add:
,data:{ id:id }
Request should look something like this:
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies',
type: 'GET',
data:{ id:id },
dataType: "text/xml",
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
WriteResponse(data);
},
error: function (x, y, z) {
alert('error');
}
});
}

JSON parsing from cross domain using jquery ajax

Im trying to parse json from cross domain but im getting error like 405 (Method Not Allowed) in jquery plugin (im using latest plugin only from google) Any solution or suggestions will be great help for me.
Thanks
Basha
Here is my code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://myurl.com/webservice&callback=?",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "jsonp",
data: "{}",
Accept: "",
beforeSend: setHeader,
success: OnGetAllMembersSuccess,
error: OnGetAllMembersError,
});
});
function setHeader(req) {
req.setRequestHeader("Authentication", "Basic credentials");
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("Accept", "application/json");
}
function OnGetAllMembersSuccess(data, status) {
alert(status);
$.each(data.result, function(key, value) {
$("#result").append(key+" : "+value);
$("#result").append("<br />");
});
}
function OnGetAllMembersError(request, status, error) {
alert(status);
}
While using jsonp as dataType, you need to bind a call back function in the server side..
for example, if you need a json response like {"id":"myId"}, at the server side it should be return like "mycallback({"id":"myId"})";
Also you need to write that function in client side too.
function mycallback(json)
{alert(json);}

Unable to recieve JSON from Webmethod using $.getJSON or Ajax call

I have some JSON objects that I want to process on Client Side, but My WebMethod that I specified does not want to fire.
Here is the Ajax and GetJson methods i used in my Client Side Script:
GetSJON
$(document).ready(function() {
$(document).ready(function() {
//attach a jQuery live event to the button
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
});
Here is the Ajax
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Both of these Methods Call StockPlacementOptions which is my WebMethod that look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
If I can just get the JSON web Method to fire on $(document).ready event, I will be able to process and work with the data from there. I have also tried looking at a diffrent jQuery library like KnockoutJS with it's data processing capability, also no luck.
I am using ASP Webforms on Framework 4 with Html5 Markup.
Any advice will be greatly appreciated.
Why are you using two document.ready() handlers at your client side getJson and ajax
$(document).ready(function() { // <-------you can remove this handler
$(document).ready(function() {
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
}); // <-------you can remove this handler
although i am not sure this could be the issue but try this one if this helps.
I got it fixed by using a combination of KnockoutJS and ajax.
By utilizing the knockoutJS mapping model, I am able to manipulate the returned JSON anyway i want :)
Here is my Jquery that does the Mapping and obtains JSON from server.
<script type="text/javascript">
//Declareing Viewmodel For KnockoutJS
var viewModel;
//Using Mapping Plugin for Knockout JS
function bindModel(data) {
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}
//Onload ObtainJSON
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx/StockPlacementOptions",
// Current Page, Method
data: {},
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
I also changed the Webmethod slightly to obtain the result i wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
And That's it :D
Thanks for all the help