Saving HTML 5 Canvas via Ajax ASP.NET - c#

I'm trying to sand canvas Data to web service via Ajax, but I get an error:
500 (Internal Server Error)
JavaScript:
var imageData = canvas.toDataURL("image/png");
imageData = imageData.replace('data:image/png;base64,', '');
$.ajax({
type: "POST",
url: "WebService.asmx/SendRegistration",
data: "{ 'imageData':'" + imageData + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded
});
Web service:
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public bool SendRegistration(string imageData)
{
....
}

When the data is a string it must be a query string. Don't use string, simply use an object and jQuery will convert it for you:
data: { imageData: imageData },
If you really want to make the string by yourself, use:
data: "imageData=" + imageData",
Remember, it's a query string, so the format is x=1&y=2&z=3.

The problem was solved, I had to add this code due to a huge file.
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>

Related

Unable to send large data in Jquery ajax call

Hi I am developing MVC4 application. I am saving values to Database. I am getting below error.
The request filtering module is configured to deny a request where the query string is too long.
I am making ajax call and sending data as Json as below.
$.ajax({
type: "POST",
cache: false,
url: '/UploadDocument/SubmitDoc?JsonValue=' + JSON.stringify(SaveUpload) + '&gridData=' + strOrderArr,
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
success: function (response) {}
});
Web.config
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
May i know am i following good approach to handle above scenario when posting huge data to database? Thanks in advance.
It's a POST Request yet you're passing data in Query string!
Pass data in Data parameter:
$.ajax({
type: "POST",
cache: false,
url: '/UploadDocument/SubmitDoc',
data: JSON.stringify({ JsonValue: SaveUpload, gridData:strOrderArr }),
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
success: function (response) {}
});

Ajax results in 500 Internal Server Error because of large JSON

I have a the following code
ajax call
$.ajax({
type: "POST",
dataType: "json",
async: false,
contentType: "application/json; charset=utf-8",
url: "Account/SomeFunc",
data: JSON.stringify(dataToSend),
success: function (res) {
//some code
},
error: function (res, textStatus, errorThrown) {
//some code
}
});
and on the server-side
public ActionResult SomeFunc()
{
//some code
VeryBigObject result = getResult();
if (result == null)
return null;
var jsonResult = Json(result, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
result variable can be small but sometimes its a very big object. when the object is small enough the code works and the ajax success code is activated but when the result is big enough the code fails with 500 Internal Server Error.
I cant put MaxJsonLength any bigger because its an int but sometimes I need to send some big data.. what can I do?
Use the code below in web.config. It will solve your problem.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="900000" />
</webServices>
</scripting>
</system.web.extensions>
Increasing maxJsonLength in Web config worked for me when I faced similar issues with large json data.

Posting Form values with jquery ajax call to inputstream in ASP.NET static method

Trying to use this code
i reached a dead end,
in the client side the form values collcected and serialized , but since it's not possible to use an instance of request in a static method
i failed to receive the seialized form values at the server,
i tried to bypass it by using the static HttpContext.Current.Request.InputStream
but i got empty stream.
how can i get the input stream in the server ?
client side :
function myFunction() {
$.ajax({
type: "POST",
url: "ajaxForm.aspx/Receiver",
contentType: "application/json; charset=utf-8",
data: $('#myForm').serialize(),
datatype : "json",
cache: false,
success: function (data) {
$('#result').html(data);
},
error: function (data) {
alert('failed');
}
});
}
server side first version (copied from that link):
{
string json;
using(var reader = new StreamReader(Request.InputStream)){
json = reader.ReadToEnd();
}
second version :
[WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Receiver()
{
if (HttpContext.Current.Request.InputStream.Position != 0)
{
HttpContext.Current.Request.InputStream.Seek(0,System.IO.SeekOrigin.Begin);
}
byte[] data = new byte[HttpContext.Current.Request.InputStream.Length];
HttpContext.Current.Request.InputStream.Read(data, 0, data.Length);}
Currently your data doesn't look like JSON. Try like this.
var jsonData = JSON.stringify({
form: $('#myForm').serialize()
});
in the ajax call for data
...
contentType: "application/json; charset=utf-8",
data: jsonData,
datatype : "json",
...
Your method:
[WebMethod ]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void Receiver(string form)
{
//in the string form you should have myForm serialize.
}
If you want to use Context.Session for something, you need to enable it.
[System.Web.Services.WebMethod(EnableSession = true)]
This is an old post, but I recently ran into a similar issue with a client and figured I'd share my experience.
The client had a legacy app that was running jQuery 1.7.1 (were afraid to change this) and had recently set up a page to accept POST only. In jQuery 1.7.1 (and possibly others), I learned you have to pass the type (as well as the method?) for POSTs.
So, this
$.ajax({
url: {url...},
data: {data...},
method: 'POST',
...
});
became, this
$.ajax({
url: {url...},
data: {data...},
method: 'POST',
type: 'POST',
...
});
And everyone lived happily ever after.
Hopefully, this saves someone else some headache.

Error 500 using C# WebMethod from jQuery ajax

I keep getting error 500 from my ajax function when trying to call WebMethod.
$.ajax({
type: "POST",
url: "BookingCalendar.aspx/TestFunction",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function () {
alert("Error");
}
});
[WebMethod]
public static string TestFunction()
{
return DateTime.Now.ToString();
}
After more looking I found out that GET and POST are disabled by default in .NET. I added this to the web.config file:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
For more information look here.

Pass html string to server side with Jquery Ajax

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.
i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}
--For Jquery:
$("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
and Server-Side ASP.NET:
[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
Jquery part gives me an error:
Invalid object passed in and error in
System.Web.Script.Serialization.JavascriptObjectDeserializer.
It's like jquery doesnt accept string with html content.what is wrong with my code ?
Pass it like this
JSON.stringify({'num':HTML});
You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.
var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
You can use this
var HTML = escape($("#t").val());
and on server end you can decode it to get the html string as
HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.
[HttpPost]
public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring)
{
retrun view();
}
$.ajax({
url: '/Controller/ActionMethod',
type: "POST",
data: JSON.stringify({
para1: titletext,
para2: datetext,
para3: interchangeNbr.toString(),
htmlstring : messageText.toString()
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function successFunc(data) {
},
error: function errorFunc(jqXHR) {
$('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show();
}
});

Categories