Facing error in ajax - asp.net

i get error message [object Object] - error - Internal Server Error when using ajax to call asp.net web method. i wan to get list of object from the server with the ajax.
ajax code
var Packages;
$.ajax({
type: "POST",
async: false,
url: "http://localhost:54954/WebSite/B/Setting/Packages.asmx/GetAllPackage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Packages = response.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.toString() + ' - ' + textStatus + ' - ' + errorThrown);
}
});
web method code
public class Package
{
public float PackageId;
public string Code;
public string Name;
}
[WebMethod]
public List<Package> GetAllPackage() {
List<Package> PackageList =new List<Package> {};
for (int i = 1; i <= 100; i++)
{
var temp = new Package();
temp.PackageId = i;
temp.Code = "Code " + i;
temp.Name = "Name" + i;
PackageList.Add(temp);
}
return PackageList;
}
may i know which part i had make the mistake??

Several places.. for starters your WebMethod does not return JSON
I suggest reading this: - What are some simple and fast ways to retieve session variables using javascript or jquery?

Related

How to handle FormData AJAX post (file with additional params) with asp.net WebMethod

Having trouble handling a jQuery AJAX post of FormData to an ASP.net 4 Web service WebMethod.
<input id="ipt_file" type="file" />
<a href='#' onclick="UploadFile();" data-role='button'>Upload</a>
var UploadFile = function () {
var file_object = $('#ipt_file')[0].files[0];
var form_data = new FormData();
form_data.append('job_id', '123456');
form_data.append('job_name', 'xyx');
form_data.append('job_file', file_object);
var xhr_upload = $.ajax({
type: "POST",
headers: { "Cache-Control":"no-cache", "Content-Type":"multipart/form-data" }, // also tried without these
url: "../MyServices.asmx/Upload",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function (msg) {
if (typeof (msg) === "object") {
var _upload = $.parseJSON(msg.d);
alert(_upload.status + ': ' + _upload.msg);
};
}
});
};
public class FileUploadRequest
{
public string job_id { get; set; }
public string job_name { get; set; }
public HttpPostedFile job_file { get; set; }
}
[WebMethod]
public string Upload(FileUploadRequest x)
{
string str_response = string.Empty;
if (x.job_file.ContentLength > 0)
{
str_response = "{\"status\":1,\"msg\":\"" + x.job_id + ", " + x.job_name + ", " + x.job_file.FileName + "\"}";
}
else
{
str_response = "{\"status\":0,\"msg\":\"FAIL"\}";
};
return str_response;
}
Must not be handling the FormData object parameter properly; here I instantiated a custom class, but all I get back from the server is 500 errors (also tried a generic object x). Also tried handling it as HttpRequest object as I've seen on some postings, to no avail. Not concerned about IE 9 incompatibility in this case; just want to see single file upload or at least a FormData object with key/value pairs properly received by an asmx WebMethod.
I did get it to work with the following code, in case anyone wants to see it:
var upload_file = $('#ipt_file')[0].files[0];
var upload_filename = upload_file.name;
var upload_maxsize = 10485760;
var upload_projectname = "test";
var form_data = new FormData();
form_data.append('session_id', this.sessionID());
form_data.append('project_name', upload_projectname);
form_data.append('file_name', upload_filename);
form_data.append('file_size', upload_file.size);
form_data.append('file', upload_file);
if (upload_file.size < upload_maxsize) {
var xhr_upload = $.ajax({
type: "POST",
headers: { 'Cache-Control': 'no-cache' },
url: "../services/upload.ashx",
data: form_data,
processData: false,
contentType: false,
dataType: "json"
}
})
.done(function (xhr_data) {
...
})
.fail(function (jqXHR, textStatus, errorThrown) {
...
})
.always(function () {
...
});
.NET will not allow the multipart/form-data for the content-type:
JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks
There is a built-in validation layer of protection that ASP.NET
enforces for both GET and POST based ASP.NET AJAX web methods, which
is that regardless of the HTTP verb being used, ASP.NET always
requires that the HTTP Content-Type header is set to the value
application/json. It this content type header is not sent, ASP.NET
AJAX will reject the request on the server.

Pass large data using jquery.ajax

I am using asp.net and jQuery 1.6
In my function I am required to pass html tags as a data parameter to my server side method written in C#. In my Database the column has Blob datatype.
I am able to submit data successfully upto 528b but If I submit large data... I'm not able to send at server side.
When I pass small data it works and a row inserted. But If I pass data around 17Kb then this doesn't go to the sever side, but prompt me an undefined error in jquery.
Following is Ajax Code:
$.ajax({
type: "POST",
url: "Post.aspx/savePost",
data: "{Title:'" + Title + "',Html:'" + Html + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});
Following is C# code
[System.Web.Services.WebMethod]
public static string savePost(string Title,string Html)
{
string retMsg = "Not Saved";
Post bp = new Post();
int count = 0;
count = bp.mySavePost(Title,Html);
if (count > 0)
{
retMsg = "Post Save Successfully.";
}
return retMsg;
}
protected int mySavePost(string Title, string Html)
{
int count=0;
try
{
string rawQuery = "INSERT INTO temp_posts (Title,HTML)"
+ " VALUES(?Title,?HTML)";
cmd = new MySqlCommand();
cmd.CommandText = rawQuery;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("?Title", MySqlDbType.VarChar).Value = Title;
cmd.Parameters.Add("?Html", MySqlDbType.Blob).Value = Html;
count = c.insertData(cmd);
}
catch(Exception ex){}
}
Please guide me with you valuable knowledge.
Thanks.
Many Thanks to everyone who put his best effort for this thread.
Finally with the help of one my senior I found where I was lacking in my code.
As I am passing html tags as a data parameter to my server side method written in C# from jQuery.ajax(); I need to encode the data.
As I used the escape() function in javascript to encode it worked. Data is submitted to database.
var encodedHTML = escape(Html); //here encoding Html.
$.ajax({
type: "POST",
url: "Post.aspx/savePost",
data: "{Title:'" + Title + "',Html:'" + encodedHTML + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});
Thanks everyone :)

pass an array in jquery via ajax to a c# webmethod

I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance.
Here is what I have so far:
My array:
$(".jobRole").each(function (index) {
var jobRoleIndex = index;
var jobRoleID = $(this).attr('id');
var jobRoleName = $(this).text();
var roleInfo = {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
};
queryStr = { "roleInfo": roleInfo };
jobRoleArray.push(queryStr);
});
My ajax code
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: jobRoleArray,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
Not sure on the webmethod but here is what I'm thinking:
[WebMethod]
public static bool save_Role(String jobRoleArray[])
You will be passing an array of:
[
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
},
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
}, ...
]
And in my opinion, it would be easier if you have a class that matches that structure, like this:
public class roleInfo
{
public int roleIndex{get;set;}
public int roleID{get;set;}
public string roleName{get;set;}
}
So that when you call your web method from jQuery, you can do it like this:
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: "{'jobRoleArray':"+JSON.stringify(jobRoleArray)+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
And in your web method, you can receive List<roleInfo> in this way:
[WebMethod]
public static bool save_Role(List<roleInfo> jobRoleArray)
{
}
If you try this, please let me know. Above code was not tested in any way so there might be errors but I think this is a good and very clean approach.
I have implement something like this before which is passing an array to web method. Hope this will get you some ideas in solving your problem. My javascript code is as below:-
function PostAccountLists() {
var accountLists = new Array();
$("#participantLists input[id*='chkPresents']:checked").each(function () {
accountLists.push($(this).val());
});
var instanceId = $('#<%= hfInstanceId.ClientID %>').val();
$.ajax({
type: "POST",
url: "/_layouts/TrainingAdministration/SubscriberLists.aspx/SignOff",
data: "{'participantLists': '" + accountLists + "', insId : '" + instanceId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
}
In the code behind page (the web method)
[WebMethod]
public static void SignOff(object participantLists, string insId)
{
//subscription row id's
string[] a = participantLists.ToString().Split(',');
List<int> subIds = a.Select(x => int.Parse(x)).ToList<int>();
int instanceId = Convert.ToInt32(insId);
The thing to notice here is in the web method, the parameters that will receive the array from the ajax call is of type object.
Hope this helps.
EDIT:-
according to your web method, you are expecting a value of type boolean. Here how to get it when the ajax call is success
function AjaxSucceeded(result) {
var res = result.d;
if (res != null && res === true) {
alert("succesfully posted data");
}
}
Hope this helps
Adding this for the ones, like MdeVera, that looking for clean way to send array as parameter. You can find the answer in Icarus answer. I just wanted to make it clear:
JSON.stringify(<your array cames here>)
for example, if you would like to call a web page with array as parameter you can use the following approach:
"<URL>?<Parameter name>=" + JSON.stringify(<your array>)

How to consume the return value of a webservice in jquery ajax call?

I have a simple webservice in asp.net which determine if the input parameter is valid or not :
[WebMethod]
public bool IsValidNationalCode(string input)
{
return input.IsNationalCode();
}
I call it from an aspx page by jquery ajax function :
$('#txtNationalCode').focusout(function () {
var webMethod = "../PMWebService.asmx/IsValidNationalCode";
var param = $('#txtNationalCode').val();
var parameters = "{input:" + param + "}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.responseText == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
},
error: function () {
$('#status').html("error occured");
}
});
});
But I don't know how to get the return value of webservice in order to show appropriate message . Here if(msg.responseText == true) doesn't work
Make the IsValidNationalCode method static and use this in javascript:
success: function (msg) {
if (msg.d == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
}
For "d" explanation follow this link: Never worry about ASP.NET AJAX’s .d again

jQuery ajax call failing with undefined error

My jQuery ajax call is failing with an undefined error. My js code looks like this:
$.ajax({
type: "POST",
url: "Data/RealTime.ashx",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 15000,
dataFilter: function(data, type) {
alert("RAW DATA: " + data + ", TYPE: "+ type);
return data;
},
error: function(xhr, textStatus, errorThrown) {
alert("FAIL: " + xhr + " " + textStatus + " " + errorThrown);
},
success: function(data) {
alert("SUCCESS");
}
});
My ajax source is a generic ASP.NET handler:
[WebService(Namespace = "http://my.website.com")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class RealTime : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{ data: [1,2,3] }");
context.Response.End();
}
public bool IsReusable
{ get { return false; } }
}
Now, if I return an empty object ("{ }") in my handler, the call will succeed. But when I return any other JSON object, the call fails.
The dataFilter handler shows that I am receiving a correct object. Firebug shows the response as expected, and the JSON tab shows that the object is parsed correctly.
So what could be the cause?
[Edit] I should have actually written "when I return any invalid JSON object, the call fails"! :D
You need valid JSON! :)
Change this line:
context.Response.Write("{ data: [1,2,3] }");
To this:
context.Response.Write("{ \"data\": [1,2,3] }");
jQuery 1.4+ doesn't tolerate invalid JSON like it used to (fails silently/in weird ways), so just add the double quotes and you're all set. For a handy tool to test JSON validity, checkout JSONLint: http://www.jsonlint.com/

Resources