jQuery WebMethod Parse Error - c#

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.

Related

jQuery ajax passing null to controller in ASP .NET MVC

I am trying to send stringified array from view with $.ajax but I am constantly getting null in controller.
This is controller function:
[HttpPost]
public void SaveColumnsToDb(string data)
{
var a = data;
}
Console outputs:
str: (2) ['SerialNumber', 'MeasurementUnit']
JSON str: ["SerialNumber","MeasurementUnit"]
Whole function:
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i++) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '#Url.Action("SaveColumnsToDb", "AjaxSelect", new { area = string.Empty })',
type: 'POST',
data: JSON.stringify(columns),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
as a matter of fact, since you are using contentType: 'application/json; charset=utf-8', you are trying to send a json inside of the request body, so use this syntax
[HttpPost]
public void SaveColumnsToDb([FromBody] string[] data)
Changed the parameter name.
When we use an ajax request then we have to pass value in data and In the URL part, we have to give only the action name and controller name.
[HttpPost]
public void SaveColumnsToDb(string dataResponse)
{
var a = dataResponse;
}
$("#popup-saveBtn").click(function () {
var columns = [];
var parentElement = document.getElementById("tableColumns");
var childElements = parentElement.querySelectorAll("input[type=checkbox]");
// If checkbox is checked, push value to array
for (i = 0; i < childElements.length; i++) {
if (childElements[i].checked) {
columns.push(childElements[i].value);
}
}
/*var strColumns = columns.join(";");*/
console.log("str: ", columns);
console.log("JSON str: ", JSON.stringify(columns));
// Send data to AjaxSelectController
$.ajax({
url: '#Url.Action("SaveColumnsToDb", "AjaxSelect")',
type: 'POST',
data: { dataResponse: JSON.stringify(columns)},
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
I managed to make it work.
Changed data property in $.ajax().
data: JSON.stringify({ data: strColumns })
I am sending only csv string, e.g. "abc;abc;abc"
Controller is same.

Posting JSON object to asp.net server

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

Jquery $.ajax, msg is empty when I call a web service (WCF) method

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.

how to pass a value as a parameter while calling a jquery function

function getReportGroups() {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "ReportGroups.ashx",
data: {
'method': 'getReportGroups',
'projectId': '30390'
},
dataType: "json",
success: function (data) {
alert('inside success');
var i = 0;
groupName = [data[i].name];
while (data[i] != null) {
alert([data[i].name]);
alert([data[i].reportGroupId]);
$("#top-node").append("<li item-checked='true' item-expanded='true'><a href=# style=font-weight:bold>" + [data[i].name] + "</a>");
i++;
var id = [data[i].reportGroupId];
getReports(id);
}
},
error: function (result) {
alert("Error- Inside the error loop");
}
});
}
function getReports(id) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "ReportGroups.ashx",
data: {
'method': 'getReports',
'reportGroupId': id
},
dataType: "json",
success: function (data) {
alert('inside getReports success');
var i = 0;
groupName = [data[i].name];
while (data[i] != null) {
alert([data[i].name]);
i++;
}
},
error: function (result) {
alert("Error- Inside the error loop");
}
});
}
This is my code.
Here when i call the getReports(id) from the getReportGroups() with the parameter id, the id is passed as zero in the getReoprts() function. I don know whats the problem. i used an alert box to check whether the 'id' exist in the first one, it does.. I have a valid Id in the getReportsFunction. But i am getting the id as zero in the second. What am i doing wrong here ?
Problem looks like i++, you can use .each() to iterate through the data
$.each(data, function(idx, item){
alert(item.name);
alert([item.reportGroupId]);
$("#top-node").append("<li item-checked='true' item-expanded='true'><a href=# style=font-weight:bold>" + [item.name] + "</a>");
var id = [item.reportGroupId];
getReports(id);
})
Looks like you're incrementing i before calling var id = data[i].reportGroupId, where as you test the value on the first iteration (alert([data[i].reportGroupId]);).
Move i++ as the last statement of the while loop and see if this resolves your issue.

Pass paramater to webservice on ajax

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 + '"}',

Categories

Resources