i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
Related
The following code is working perfecting after publishing to my localhost. So I copied the files from my localhost and put them on the server. Now it's saying it cannot find the web method. The project is an MVC project and what's not working is an separate aspx page added to the project directory. So, I don't know if this has something to do with IIS. Any ideas would be greatly appreciated.
[WebMethod]
public static string LoadPatients(string phone, string user)
{
//SOME STUFF HERE THAT WAS EXCLUDED//
var sb = new StringBuilder();
for (var x = 0; x < Callerdt.Rows.Count; x++)
{
var addr = Callerdt.Rows[x]["Street"].ToString() + " " + Callerdt.Rows[x]["city"].ToString() + ", " + Callerdt.Rows[x]["State"].ToString() + " " + Callerdt.Rows[x]["ZipCode"].ToString();
sb.AppendFormat("<div class='tabs'><table>" +
"<tr><td class='title'><label>Name:</label></td><td>{0}</td></tr>" +
"<tr><td><label>DOB:</label></td><td>{1}</td></tr>" +
"<tr><td><label>Address:</label></td><td>{2}</td></tr>" +
"<tr><td><label>SSN:</label></td><td>{3}</td></tr>" +
"<tr><td><label>Z Number:</label></td><td>{4}</td></tr>" +
"</table></div><br/>", Callerdt.Rows[x]["Name"].ToString(), Callerdt.Rows[x]["DOB"].ToString(), addr, Callerdt.Rows[x]["SSN"].ToString(), Callerdt.Rows[x]["ZNUM"].ToString());
}
ret = sb.ToString();
return ret;
}
<script type="text/javascript">
$(document).ready(function () {
var p = document.getElementById('pn').value, u = document.getElementById('user').value, er = document.getElementById('error').value;
if (!(er == "true")) {
$("#loading").show();
$.ajax({
type: "POST",
url: 'CallerPopup.aspx/LoadPatients',
data: JSON.stringify({ phone: p, user: u }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#tabs').append(data.d);
},
complete: function () {
$("#loading").hide();
}
});
}
});
</script>
In my case, adding IgnoreRoute to RegisterRoutes() got me going. Now the aspx.cs "static" hosted [webmethod] loads ... url: 'LearnKO.aspx/FetchStudents',
aJax was throwing a 404 - Not Found on any page.aspx/webmethod call.
ie. the fix:
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
I was setting up http://www.c-sharpcorner.com/UploadFile/1492b1/learning-knockout-part-1-introduction-to-knockout-js-and-cr/ in an MVC project instead of the recommended empty ASP.NET... my bad.
I have a Web service WCF and I call the methods of my Wcf with Jquery ajax.
When I tested with a method without parameter, it works well.
But when I call a method with parameter, it doesn't work.
The problem is that in my success in $.ajax, msg is empty.
Here is my javaScript code :
function getStatistic3() {
var response;
var allstat3 = [];
var allyearstat3 = [];
var kla = $('#Select1').val();
kla = kla.replace("'", "\\'");
if (kla) {
$.ajax({
type: 'GET',
url: 'http://localhost:52768/Service1/Statistic_3',
data: "klant='" + encodeURIComponent(kla) + "'",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
allyearstat3[0] = [response.Items[0].YearStart, response.Items[0].YearStart + 1, response.Items[0].YearStart + 2, response.Items[0].YearStart + 3, response.Items[0].YearStart + 4];
fillDataTable3(allstat3, allyearstat3);
if (bool3) {
$('thead tr th:eq(0)').replaceWith(function () {
return $("<td />").append($(this).contents());
});
$('thead th').attr('scope', 'col');
bool3 = false;
}
$('table').visualize({ type: 'line' });
},
error: function (e) {
alert("error loading statistic 3");
}
});
}
}
I tested all with an .asmx Web service and all works well.
I have this error when I call the method :
TypeError: response.Items[0] is undefined
Msg is empty :
I think that I have a problem when I pass the parameter in ma $.ajax.
I cant for the life of me figure out why my data being returned is empty. In fiddler i see the json
d=[{"response":[{"h":"h1"},{"h":"h1"}] }]
in fiddler there is a 200 status on the row where i see the json, but no other rows after that one ( maybe its not returning? ). This is the code i am using
$('.SomeLink').click(function () {
var sfn = $('#ID1').val();
var sfp = $('#ID2').val();
var sfi = $('#ID3').val();
var gid = $('#ID4').val();
$.ajax({
type: "POST",
cache: false,
url: '/AjaxHandler.aspx/GetNewHtml',
contentType: "application/json; charset=utf-8",
data: "{'a':'" + sfn + "','b':'" + sfp + "','c':'" + gid + "','d':'" + sfi + "'}",
dataType: "json",
success: function (data) {
alert(data.response[0].h); //acts like a syntax error/no alert box
alert(data); // [object Object]
alert(data.response); // undefined
alert(data.response.count); //acts like a syntax error/no alert box
},
error: function (e) {
alert("Error: " + e.responseText);
}
});
});
AjaxHandler.aspx
[System.Web.Services.WebMethod()]
public static string GetNewHtml(string a, string b, string c, string d)
{
List<Samp> samp = new List<Samp>()
{
new Samp{h = "h1"},
new Samp{h = "h1"}
};
return Serialize(new { response = samp });
}
private static string Serialize(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
Samp Class
public class Samp
{
public string h = "";
}
This is my first time using jquery ajax with asp.net so im sure im missing something that is probably relatively simple. Im using .Net 4.0 , jquery 1.7.1 , iis 7.5
Try data.d for your return object:
alert(data.d);
its tripping over the quotes around the property names. try string indexes.
try
data["response"][0]["h"]
returns h1
I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',
I seem to be having issues calling a WebMethod from jQuery, I am using this article as my starting point:
http://www.misfitgeek.com/2011/05/calling-web-service-page-methods-with-jquery/
JS
function WebMethod(fn, paramArray, successFn, errorFn)
{
//----------------------------------------------------------------------+
// Create list of parameters in the form: |
// {'paramName1':'paramValue1','paramName2':'paramValue2'} |
//----------------------------------------------------------------------+
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//----------------------------------------------------------------------+
// Call the WEB method |
//----------------------------------------------------------------------+
$.ajax({
type: 'POST',
url: 'ContractView.aspx' + '/' + fn,
contentType: 'application/json; charset=utf-8',
data: paramList,
dataType: 'json',
success: successFn,
error: errorFn
});
};
I am passing into this method like this:
$(".editableField").keydown(function(e) {
WebMethod('PriceContract',
[
'AQ', aq.val(),
'SOQ', soq.val()
], updateTextFields, failed);
});
C# (Note these are test methods, ignore the logic..)
[WebMethod]
public static ContractsListPricing PriceContract(string AQ, string SOQ)
{
ContractsListPricing clp = new ContractsListPricing();
// clp.Aq = nAQ * 2;
// clp.Soq = nSOQ * 2;
return clp;
}
When debugging the JS the paramList seems to be correct JSON (or so I believe):
{"AQ":"140000","SOQ":"1169"}
This is resulting in a parseerror and I'm unsure why.
Any help appreciated.
Thanks
Oh no, please never build JSON manually by using string manipulation as you did. That's absolutely horrible. Take a look at this article.
Here's the correct way:
function WebMethod(fn, paramArray, successFn, errorFn) {
var paramList = { };
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
paramList[paramArray[i]] = paramArray[i + 1];
}
}
$.ajax({
type: 'POST',
url: 'ContractView.aspx' + '/' + fn,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramList),
dataType: 'json',
success: successFn,
error: errorFn
});
}
Notice the usage of the JSON.stringify method to properly JSON encode the paramList object. This method is natively built into modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.