Pass large data using jquery.ajax - asp.net

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

Related

Autocomplete Web Service in ASP.Net web forms

I have a web service for multiple item selection, its working fine but i am getting Undefined data. anyone can tell me solution for it. I am attaching my error screenshot too with this post, please see them below.
Web Service JSON Code
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'skill':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Result Found");
}
});
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#ctl00_ContentMain_TextBoxSkills").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
Web Service:
[WebMethod]
public List<UserRegistration> GetAutoCompleteData(string skill)
{
List<UserRegistration> list = new List<UserRegistration>();
UserRegistrationHelper userRegistrationHelper = new UserRegistrationHelper();
using (DataTable dataTable = userRegistrationHelper.GetSkillsList(skill))
{
if (CommonFunctions.ValidateDataTable(dataTable))
{
foreach (DataRow dr in dataTable.Rows)
{
var SkillsList = new UserRegistration
{
SkillId = Convert.ToInt32(dr["SkillId"].ToString()),
Skills=dr["SkillName"].ToString()
};
list.Add(SkillsList);
}
}
}
return list;
}
Screenshot here:
I got answer for it:
1: Change SQL Query:
select concat('[', STUFF
(
(
SELECT top 15 '","'+ CAST(skillname AS VARCHAR(MAX))
from DNH_Master_Skills where SkillName LIKE '%' + #SkillName + '%'
FOR XMl PATH('')
),1,2,''
),'"]')
2: Change JSON Code:
From: response(data.d); TO: response(Array.parse(data.d));
Now its working feeling happy.

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?

jQuery Ajax success response returns HTML and not my intended value

I'm calling the Page Method and it's returning all of the HTML in this page and not the value of 1 or 0.
I don't know why this is. Can someone point me in the right direction ?
JavaScript:
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{}',
url: "main.aspx/IsInfoComplete",
success: function(data, textStatus, jqXHR) {
console.log(textStatus);
console.log(data.d);
// act on return value:
if(data==0) {
// todo -
} else if (data==1) {
// todo -
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
Server:
[System.Web.Services.WebMethod()]
public int IsInfoComplete()
{
int returnValue = 0;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetIsUserInfoComplete";
cmd.Parameters.AddWithValue("#UserName", userName);
conn.Open();
try
{
returnValue = (int)cmd.ExecuteScalar();
}
catch (Exception) { /* todo - */ }
}
return returnValue;
}
One thing you might try is to write your success function like this,
success: function (result) {
if (result!="False") {
//it worked
}
else {
//it failed
}
},
And change your server side method to return a bool. This would probably get you the desired results. I had to do this in something I wrote and it worked just fine. Little silly that you have to check for "False" but it worked.
Note: Case matters when looking for the word "False"
Look's like this is messing it up.. data here is an object and you are trying to compare the data with a 0 or a 1
success: function(data, textStatus, jqXHR) {
console.log(data); // Check the format of data in object
if(data != null){
console.log(data.d); // Generally your actual dat is in here
// act on return value:
if(data.d ==0) {
// todo -
} else if (data.d ==1) {
// todo -
}
}
},
If thats the case is your WebService returning a json object in the first place..
You need to decorate your webservice with this..
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[System.Web.Services.WebMethod()]
public int IsInfoComplete()
{
And set the dataType :'json' in your ajax request

Passing array from jquery ajax method to c# codebehind

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.

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

Resources