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

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

Related

Partial View loading using javascript : Possible XSS by HP FORTIFY

I have a js function , which Fortify identified as XSS vulnerable as below. Can you suggest any solution for this since the method is intensively used in my app.
I am here trying to call a partialview in ajax and the result html am appending to a specified dom div
My function look like the below
function loadPartialViewToDiv(div, obj, api) {
try {
const myUrl = new URL(window.location.origin + api); // always local URL only
$.ajax({
url: myUrl ,
data: obj,
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
if (data != undefined && data != null) {
$('#' + div).html(data);
}
}
});
} catch (e) {
('#' + div).html('Error');
}
}
The dynamic DOM element id was the issue ($('#' + div).html(data); ), we fixed it using two methods
giving a static id. $('#abcd').html(data);
OR
change as $('#' + div).text($(data));

Database Not Showing Data in Json Ajax

This is my view file Book.cshtml script section. The problem coming is that it not fetching my data from my database.
Instead it is giving a error:
alert("Failed! Please try again.")
If I truncate the data from the database it shows ONLY the heading "BOOK ID" "BOOK NAME" "BOOK SERIAL NUMBER" "BOOK AUTHER" "BOOK PUBLISHER NAME"
$(document).ready(function () {
// This is for Get All Data
$("#btnAllBook").click(function () {
$.ajax({
url: "#Url.Action("GetAllBook","Books")",
data: "",
type: "GET",
dataType: "json",
success: function (data)
{
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
// this will use for Get Data based on parameter
$("#btnSearch").click(function () {
$.ajax({
url: "#Url.Action("GetBookWithParameter", "Books")",
data: { prefix: $('#txtSearch').val() },
type: "GET",
dataType: "json",
success: function (data) {
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
function loadData(data) {
// Here we will format & load/show data
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Book ID</th>');
thead.append('<th>Book Name</th>');
thead.append('<th>Book Serial Number</th>');
thead.append('<th>Book Auther</th>');
thead.append('<th>Book Publisher</th>');
tab.append(thead);
$.each(data, function (i, val) {
// Append database data here
var trow = $('<tr></tr>');
trow.append('<td>' + val.BookID + '</td>');
trow.append('<td>' + val.BookName + '</td>');
trow.append('<td>' + val.BookSerialNumber + '</td>');
trow.append('<td>' + val.BookAuther + '</td>');
trow.append('<td>' + val.BookPublisher + '</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#UpdatePanel").html(tab);
};
});
Looking into the documentation on http://api.jquery.com/jquery.ajax/, the callback error is called because the request failed. Then, I suggest you to check if the url #Url.Action("GetAllBook","Books") is returning the right string of the url, maybe you are trying to request in a url that doesn't exists.
Another point, being about a GET request, I suggest you to check opening in a browser if this URL that you are trying to return data, is returning the JSON data expected as you need to append to the HTML.

Knockout applyBindings does not applyBinding

I have just started to use knockout.js and am stuck when trying to show JSON data.
My HTML is
<p>Dealer Location: <input id="dealerlocation" data-bind="value: DealerLocation" /></p>
<p>Contact Report Date: <input id="crdate" data-bind="value: CRDate" /></p>
My Script Block is
function viewAction() {
var self = this;
self.DealerLocation = ko.observable("");
self.CRDate = ko.observable("");
};
var viewActionModel = new viewAction();
function GetActionByID() {
$.ajax({
type: "POST",
url: "/ws/someservice.asmx/GetAction",
data: "{pacid: '" + $('input[id$=hidActionID]').val() + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
var action = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$.each(action, function (index, axn) {
viewActionModel.DealerLocation = axn.DealerLocation;
viewActionModel.CRDate = axn.CRDate;
});
}
});
}
$(document).ready(function () {
GetActionByID();
//alert(viewActionModel.DealerLocation);
ko.applyBindings(viewActionModel);
});
Note: If I uncomment alert then applyBinding works otherwise it does not.
What is missing here???
Ragards.
This is a wrong way to assign observables.
viewActionModel.DealerLocation = axn.DealerLocation;
viewActionModel.CRDate = axn.CRDate;
Do it like this.
viewActionModel.DealerLocation(axn.DealerLocation);
viewActionModel.CRDate(axn.CRDate);
By doing what you do now you are replacing observables with regular variable. It was working with alert because this replacement took place before binding and knockout just picked up your regular variables. Read more about observables.

Calling Java SOAP webservice in HTML page

I am new to HTML development.
I am developing a mobile application using phonegap- HTML5.
I want to call a web service which is written in JAVA returning SOAP message.
I am calling my webservice using XmlHttp reguest but which on execution returns null data and status as 0.
So, my question is how can I call webservice in an HTML page?
What should I do to call Java SOAP webservice from HTML page?
Please any help is appreciated.
Please suggest any method soon.
Thanks in advance.
You need to make a soap request in a js file.
In your js file you should have something like this:
function sendSOAPRequest(webServiceMethod, params, callbackMethod, isAsynchronous, callContext)
{
//Get the token from local storage
var token = window.localStorage.getItem("token");
//Get the soap envelope with given parameters
var soapEnvelope = getEnvelopeFromParam(webServiceMethod, params);
//Send the soap request
$.ajax({
url: "https://www.zzz.com/yyy/soap",
type: "POST",
dataType: "xml",
data: soapEnvelope,
context: callContext,
complete: callbackMethod,
async: isAsynchronous,
timeout: 60000,
contentType: "text/xml; charset=\"utf-8\"",
beforeSend: function (xhr) {
xhr.setRequestHeader('SOAPAction', 'http://zzz.com/yyy/uuu/Iooo/' + webServiceMethod);
xhr.setRequestHeader('Authorization', token);
}
});
}
function getEnvelopeFromParam(webServiceMethod, parameters)
{
var soapEnvelope = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><' + webServiceMethod + ' xmlns="http://zzz.com/yyy/uuu">';
$.each(parameters, function(key, value) {
if(value)
{
soapEnvelope += '<' + key + '>' + value + '</' + key + '>';
}
else
{
//Send a null value
soapEnvelope += '<' + key + ' i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>';
}
});
soapEnvelope += '</' + webServiceMethod + '></s:Body></s:Envelope>';
return soapEnvelope;
}
this is a method to call webservice. You have the specify the right adresses corresponding to your server.
Now include this js file in your html
<script type="text/javascript" src="myFile.js"></script>
Now you have to call your js function from your html page (for exemple)
sendSOAPRequest("myfunction", params, endFunction, true, this);
And you have to define the endFunction
function endFunction(xmlHttpRequest, status)
{
//Work with xmlHttpRequest and check status
}

Calling service from 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/