Passing array from jquery ajax method to c# codebehind - asp.net

I need to pass a JavaScript Array variable to a code-behind file and access that array.
Please let me know if this is the exact data object that the Ajax method would expect. While using this, the code always jumps to failureCallback function. Can anyone please help me with this?
jQuery/JavaScript:
The data in the result array is: section_1,section_2,section_3.
The output of paramList is: {"data":"section_1,section_2,section_3"}.
function generateData() {
var result = $('#accordion').sortable('toArray');
alert(result);
ExecutePageMethod("ReorderList.aspx", "HandleData", ["data", result], successCallback, failureCallback);
}
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
alert("entered page method");
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 + '}';
alert(paramList);
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
function successCallback(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
function failureCallback(result) {
alert("entered failure");
}
C# Code Behind:
public static string HandleData(object[] data)
{
//How should I parse this object data?
return data;
}

There are two ways to access code behind from the client.
Store it in a collection sent with a request (normally this is through a form submit).
Set up an "AJAX" call to a server side service through JavaScript.
There are variations on the above, but essentially you are consuming a service or you are posting back.
Looking at your code, you want the AJAX direction. I would start with this Stack Overflow post, as it covers the basics of passing an array back to the "service endpoint" of a code behind file.

Related

Facing error in ajax

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?

Calling a web service method from ASP.NET 1.1 using jQuery ajax, not returning any data.

I have hosted a web service that gets called from an ASP.NET 1.1 by jQuery ajax.
Here is the code i am using to call the web service :
function OnTrimLevelChange()
{
var $jDecode = jQuery.noConflict();
var vin = $jDecode("input[id*=txtVIN]").val();
var styleId = '';
var paramList = '{"vin": "' + vin + '","styleID": "' + styleId + '"}';
try
{
$jDecode.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://192.168.10.10/VINDecoder/service.asmx/CallADSWebMethod',
data: paramList,
dataType: 'json',
success: function(data) {
alert('I am here');
},
error: function(xml,textStatus,errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
});
}
catch(er)
{
}
}
=======================================================
The above always going to the error part.
Error: xml.status = 0 xml.responseText = null
Web method code is :
[WebMethod]
public VINDescription CallADSWebMethod(string vin, string styleID)
{
VehicleDescription vehicleDescription = FetchVehicleInfo(vin, true, styleID);
VINDescription vinDescription = new VINDescription();
try
{
if (vehicleDescription != null)
{
//Check if the response status of the call is successful or not.
if (vehicleDescription.responseStatus.description.Equals("Successful"))
{
vinDescription = AddToVINDescription(vehicleDescription);
}
}
}
catch (NullReferenceException ex)
{
}
return vinDescription;
}
Note : The webservice is created in .Net 4.0 and site from which i am calling is in 1.1.
They are hosted in different servers.
PLease let me know what am i lacking here or what mistake i am doing her..
Script service execution was needed to be enabled in the web service. Like this :
[ScriptService]

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 :)

making ajax call (in jquery) for webservice in asp.net

I want to validate product code for duplication using ajax call(in jquery) for webservice in which web method is written. now if success function executes as 'duplicate product code' it should not allow the user to save record. so how can i check this on Save buttons click event
First, create the below method in the page code behind.
using System.Web.Services;
[WebMethod]
public static bool CheckDuplicateCode(string productCode)
{
bool isDuplicate = false;
int pCode = Convert.ToInt32(productCode);
//check pCode with database
List<int> productCodes = GetProductCodeInDb();
foreach (var code in productCodes)
{
if (pCode == code)
{
isDuplicate = true;
break;
}
}
return isDuplicate;
}
And in the page markup just before the end body tag insert this code
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btnSave.ClientID %>').click(function () {
SaveProduct();
});
});
function SaveProduct() {
//Get all the data that you are trying to save
var pCode = $('#<%= txtProductCode.ClientID %>').val();
//pass the product code to web method to check for any duplicate
$.ajax({
type: "POST",
url: "/InsertProductPage.aspx/CheckDuplicateCode",
data: "{'productCode': '" + pCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSuccees(msg);
},
error: AjaxFailed
});
}
function AjaxSuccees(msg) {
if (msg.d == true) {
return true;
//insert the rest of data
}
else {
alert("Product code already exists");
return false;
}
}
function AjaxFailed(msg) {
alert(result.status + ' ' + result.statusText);
}
</script>
Hope this helps

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