problem sending html2canvas image to ajax - html2canvas

I am working in ASP.net. I can create an image using html2canvas of the div i want, but sending it through AJAX causes an error. The error statuscode is 'OK'. Not sure what that means. The serever side code never gets executed. The AJAX call I am making looks like this:
html2canvas($('#box1'), {
onrendered: function (canvas) {
$('#box1').html('');
$('#box1').append(canvas);
cartImage = canvas.toDataURL('image/jpeg');
$.ajax({
type: "POST",
url: pageUrl + '/UploadImage',
data: { "imageData": cartImage },
dataType: "json",
success: function (msg) {
console.warn(msg.d);
},
error: function (result) {
console.warn(result.statusText);
}
});
The server side code looks like this:
Public Shared Function UploadImage(imageData) As String
imageData = imageData.Replace("data:image/png;base64,", "")
Dim fileNameWitPath As String = "TempDownload/" & Guid.NewGuid().ToString & ".png"
Dim fs As FileStream = New FileStream(fileNameWitPath, FileMode.Create)
Using (fs)
Dim bw As BinaryWriter = New BinaryWriter(fs)
Using (bw)
Dim data As Byte() = Convert.FromBase64String(imageData) 'convert from base64
bw.Write(data)
bw.Close()
End Using
End Using
Return "Success"

I did find the AJAX call would work if I used JSON.stringify({ "imageData": cartImage }) for the data parameter in the AJAX call.

Related

Dart : i can't POST data in HTTP Message Body using HttpRequest.send() method

In my Rest server, i can't read the data contained in the HTTP Message Body when the call comme from script writing in Dart.
When calling the same webservice with ajax, there is no problem. In both case the data send with the URL (pcParamUrl=yopla) can be read in the server side.
i think the problem come from "processData: false" in ajax, i don't know how to set this key in HttpRequest Dart object.
I am trying to convert this ajax call (javascript) :
var url = "http://127.0.0.1:8980/TestDartService/rest/TestDartService/Test?pcParamUrl=yopla";
$.ajax({url: url,
type: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify({ request: {pcParamBody: "yepYep"} }),
success: function(data, status) { alert(data.response.pcRetour); },
error: function(status) { alert("erreur"); }
});
to this one using Dart:
HttpRequest request = new HttpRequest();
request.onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE && request.status == 200 || request.status == 0)) {
print(request.responseText);
}
});
var url = "http://127.0.0.1:8980/TestDartService/rest/TestDartService/Test?pcParamUrl=yopla";
request.open("POST", url, async: false);
request.setRequestHeader("content-Type", "application/json");
String jsonData = JSON.encode('{ request: { pcParamBody: "yepYep" } }'); // etc...
request.send(jsonData);
thanks for your help and sorry for my bad english
(moved from the Question:)
The problem is the format of the data being passed to JSON.encode; it should be an object; or you could skip the encoding altogether:
String jsonData = JSON.encode('{request: {pcParamBody: "yepYep"}}'); // BAD
String jsonData = JSON.encode({"request": {"pcParamBody": "yepYep"}}'); // GOOD
String jsonData = '{request: {pcParamBody: "yepYep"}}'; // ALSO GOOD

GWT/JSNI this. is not replace with a reference to the instance

I have the following code in a GWT class:
private native JavaScriptObject getRequest() /*-{
var request = ...;
request.onOpen = function(response) {
this.#com.mdarveau.fnp.client.Client::onOpen(Lcom/mdarveau/fnp/client/Response;)(response);
};
return request;
}-*/;
void onOpen( Response response ) {
Window.alert( "Got response " + response );
}
However, when the function associated with request.onOpen is called, the "this variable" is not replaced with a reference to the compiled GWT class. Using chrome javascript console and debugger I see that it looks like a reference to the request object.
Any idea why? I also have jquery loaded, could there be a conflict?
Got it: you need to get a reference to this in the native code and then use it in the function block:
var theInstance = this;
and then
request.onOpen = function(response) {
theInstance.#com.mdarveau.fnp.client.Client::onOpen(Lcom/mdarveau/fnp/client/Res‌​ponse;)(response);
};

JQuery AJAX get not working correctly?

I have a partial view with this jquery script:
$("#btnGetEmpInfo").click(function () {
var selectedItem = $('#EmployeeId').val();
var focusItem = $('#EmployeeId')
alert("Starting");
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "<%= Url.Action("getEmpInfo", "NewEmployee")%>?sData=" + selectedItem,
data: "{}",
success: function(data) {
if (data.length > 0) {
alert("Yeah!");
} else {
alert("No data returned!");
}
}
});
alert("Back!");
});
Then in my controller I have:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getEmpInfo(string sData)
{
return new JsonResult { Data = "test" };
}
I can breakpoint in the controller and it is hitting, but the only "Alerts" I get are the "Starting" and "Back". Why would the data not be returned or at least hit saying no data returned?
Thanks in advance for any and all help.
Geo...
You probably might want to improve this ajax call like this:
$.ajax({
type: 'GET',
url: '<%= Url.Action("getEmpInfo", "NewEmployee")%>',
data: { sData: selectedItem },
success: function(data) {
// Warning: your controller action doesn't return an array
// so don't expect a .length property here. See below
alert(data.Data);
}
});
and have your controller action accept GET requests:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getEmpInfo(string sData)
{
return Json(new { Data = "test" }, JsonRequestBehavior.AllowGet);
}
OK, now that we have fixed the error let me elaborate. In your code you were using an application/json content type to format your request string. Unfortunately in ASP.NET MVC 2 there is nothing out of the box that is capable of making sense of JSON requests (unless you wrote a custom json value provider factory). Then using string concatenation to append the sData parameter to the URL without ever URL encoding it meaning that your code would break at the very moment the user enters some special character such as & in the EmployeeId textbox.
Try adding the 'beforeSend', 'error' and 'complete' callbacks to get more info in your javascript debugger. http://api.jquery.com/jQuery.ajax/
Are you using a javascript debugger? (firebug, ie9 dev-tools, chrome dev-tools are decent ones 3 that come to mind)

JQuery post function problem

I try to post some data via json objects to my asp.net mvc view, here is the code
$("#submitButton").click(function () {
var name = $("#name")[0].valueOf();
var price = $("#price").valueOf();
var url = $("#url").valueOf();
var product = { Name: name, Price: price, Url: url };
$.post("/Home/NewProduct", product, function (json) { $('ul.items').append("<li><img src=" + url + "/></li>"); },"json");
});
and now, the result is an error:
uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: http://localhost:1804/Scripts/jquery-1.4.2.min.js :: f :: line 132" data: no]
I try JQuery 1.4.1 and 1.4.2, If I try this code the error is the same
$.ajax({
type: "POST",
url: "/Home/NewProduct",
dataType: "json",
data: { Name: name, Price: price, Url: url },
success: function () { $('ul.items').append("<li><img src=" + url + "/></li>"); }
});
What I'm doing wrong? Please help!
Thanks!
To get the value of an input type element, use .val() instead of .valueOf(), like this:
var name = $("#name").val(),
price = $("#price").val(),
url = $("#url").val();
When you call .valueOf() on a jQuery object, it gets an array of DOM elements...and that doesn't serialize well :)
In your $.post call if you pass JSON as a 4th parameter then jQuery will expect VALID json string only other wise it might cause error.
example of valid JSON is
var json = {"a":"my name", "b":"my school"};

Sending parameters in AJAX call

This has been asked before by others, but I have not been able to use their answers.
I am trying to sending some data by doing the following:
function addForumPost() {
var title = jQuery('#forumTitle').val();
var message = htmlEncode(jQuery('#message').htmlarea("toHtmlString"));
var tagNames = addTags();
var dataPost = $.toJSON({ title: 'testingsadf', message: message, tagNames: tagNames });
jQuery.ajax({
type: "POST",
url: "/Create",
data: dataPost,
dataType: "json",
success: function (result) {
}
});
}
I have checked, and doubled checked that the input contains data, but I only receive the data from the message parameter in my controller. The other two values are null. As you can see in the the example above, I have even assigned some static text to the title parameter, but I still only receive data for the message parameter.
The controller looks like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string title, string message, List<string> tagNames)
{
....
}
Your error is very simple. If you have an action which returns JsonResult then it means not that you have to send also JSON encoded input parameters to the method. Just remove the usage of $.toJSON() and use the object as a value of data parameter of jQuery.ajax (see the answer of Darin for example).
If you call ASMX Web Service instead of ASP.NET MVC action you have to use contentType: "application/json; charset=utf-8" and convert the values of all web-method parameters to JSON but in a little other way (see How do I build a JSON object to send to an AJAX WebService?). But ASP.NET MVC hat no such requirement. MVC converts the input parameters which you send with respect of Parse method (int.Parse, DateTime.Parse and so on) and not deserialize from JSON. So if you search for code examples look exactly which technology are used on the backend: ASP.NET MVC, ASMX web serveces or WFC.
Try setting the traditional parameter starting from jQuery 1.4. This works for me:
var title = 'title';
var message = 'message';
var tagNames = ['tag1', 'tag2'];
jQuery.ajax({
type: 'POST',
url: '/Home/Create',
data: { title: title, message: message, tagNames: tagNames },
dataType: 'json',
traditional: true,
success: function (result) {
}
});
With this action:
[HttpPost]
public ActionResult Create(
string title,
string message,
IEnumerable<string> tagNames
)
{
return Json(new
{
Title = title,
Message = message,
TagNames = tagNames
});
}
You don't have to post json for the type of action you described.
You don't have to manually assemble the fields into a map. Use .serializeArray()
var postData = $('.myform').serializeArray()