Sending data from JQuery to C#, ASP.Net - javascript

I have a canvas in my .aspx form page where one can sign a signature, I would like to send the base64 data from the JQuery client side to the C# Asp.Net side. Here I want to upload this base64 data to a database.
(a couple things I tried)
Jquery:
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: '{ data: "' + base64 + '"}',
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 }); // another thing i tried
C#:
var d = Request.Params["data"];
The variable d is null when i put a breakpoint at it.
Does anybody see how I can tackle this hurdle, or make it easier?
(note: I do not have a lot of experience with JQuery)

Your JSON with base64 could be available as request body.
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
string text = reader.ReadToEnd();
}

If you replace
url: 'EvaluatieForm.aspx'
by
url: 'EvaluatieForm.aspx?data=' + base64
and remove
data: '{ data: "' + base64 + '"}',
then it will work.

Try this:
Just a small change in your existing code, used JSON.stringify to post data.
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
var objectToPasss = {data: base64};
var postData =JSON.stringify(objectToPasss );
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: postData,
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 });

Try this:
$("#savebtn").bind("click", function () {
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: {
sketch: $('#sketch')[0].toDataURL("image\png")
},
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
where
var d = Request.Params["sketch"];
The data argument in the jQuery ajax() function works in conjunction with the contentType. As you are setting it to application/json, then it stands to reason that data will be serialized, so setting the sketch variable seems about right.

With ajax you can try xhr.
maybe this thread helps you out! :)
How can I upload files asynchronously?

Related

.net Core send xlsx file as response for Ajax request

My web-application can only work with .xlsx-files. I created a function in my controller, which converts a .xls-file into an .xlsx-file. The conversion works totally fine. So whenever I try to open a .xls-file, I send it via Ajax request.
After that, I want to respond with the converted .xlsx-file, but it never arrives at the client.
Since the conversion works fine, i simplified the code, to just pass a simple .xlsx file, which didn't work aswell.
JavaScript:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
formData = new FormData();
formData.append("xlsfile", files[0]);
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: formData,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
Controller:
public IActionResult ConvertToXlsx(IFormFile xlsfile) {
//For simplification without conversion
//var xlsconverter = new XLSConverter();
//FileStreamResult response = xlsconverter.XLSConvert(xlsfile);
var path = $"wwwroot/temp/";
var filepath = Path.Combine(path, "test.xlsx");
MemoryStream x = new MemoryStream();
using(FileStream fs = System.IO.File.OpenRead(filepath)) {
fs.CopyTo(x);
}
return File(x, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
In the browser-network tab I get Status: net::ERR_CONNECTION_RESET
Am I missing a setting somewhere, which causes I simply can't respond with files?
If you want to pass file to action,try to use the following code:
if (files[0].type == "application/vnd.ms-excel") {
console.log("XLS-File");
$.ajax({
url: '/Home/ConvertToXlsx',
type: 'POST',
cache: false,
processData: false,
data: files[0],
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
openXLSFile(response);
},
error: function () {
console.log("An Error occurred");
}
});
}
And if you want to return file with content type,you can try to use:
public IActionResult ConvertToXlsx(IFormFile xlsfile)
{
return File(xlsfile.OpenReadStream(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

Can not send data from c#(controller) to javascript

I have this code on my JavaScript file:
temp="string";
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: myJson,
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(temp.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
console.log(errorThrown);
ConnectionChanged();
}
});
And this controller:
[HttpPost]
public string updateStatus(string updatedJson)
{
var Player = JsonConvert.DeserializeObject<GameDataClass>(updatedJson);
var Opponent = JsonConvert.DeserializeObject<GameDataClass>(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, Player.OpponentID + ".json")));
... }
I tried to change $.ajax to $.post method, also changed
public string updateStatus
to
public JsonResult updatedStatus
But neither of this didn't work. myJson on javascript contain data but when it reaches controller updatedJson is empty. I've never had this kind of experience so I'm using this code from another project and it works very well there. So can somebody suggest me what I'm doing wrong?
temp="string";
// (0)
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus?updatedJson=' + temp, // (1)
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '', // (2)
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(response.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
ConnectionChanged();
}
});
Or if this does not have to be passed as a parameter, then do the following:
(0) var formData = new FormData(); formData.append('updatedJson', temp);
(1) url: '/MemoryGame/updateStatus',
(2) data: formData,
$.ajax is a fonction from the jQuery library, does your project include it ?
You can also check the Javascript console of your browser to see if it contains errors. On Firefox and Chrome you can access it by pressing F12.

jquery ajax request not responding

I'm a newbie at asp.net and trying to understand ajax responses. I have following code:
$(document).ready(function () {
$('#<%=cbx_pep.ClientID%>').change(function () {
var mSis = $('#<%=cbx_pep.ClientID%>').val();
getRCT(mSis);
});
});
function getRCT(mez_sis) {
$.ajax({
url: '/Staff/PEX.aspx/GetTempInfo',
method: 'get',
contentType: 'application/json',
data: '{d_val:' + mez_sis + '}',
dataType: 'json',
success: function (data) {
alert(data.d);
},
error: function (error) {
alert(error);
}
});
}
and that's my server side code:
[WebMethod]
public static string GetTempInfo(string d_val)
{
string str = d_val;
return str;
}
I'm repeatedly getting error. Appreciate for help.
First, as mybrithname said, You have yo use method: 'post' and then your json is invalid, you have a missing quotes there:
It should be something like this
data: '{d_val:\"' + myVar + '\"}',
You should use method: 'post' if you are going to send data to the server, which you are doing in data: '{d_val:' + mez_sis + '}'

Making a AJAX request with jquery and parsing JSON

EDIT- I have figured out that the request is working correctly but I don't know what to do with the data once it has been retrieved from the server. I don't know how to access the JSON, how do I do this?
I am trying to do a jQuery AJAX request and parse the JSON which is hopefully received. Here is my code:
search.onsubmit = function() {
$.getJSON("http://www.geocodefarm.com/api/forward/json/d4abb1b19adb13e42eac5a7beac6f4dbeb4b4ba4/" + searchBox.value, function(data) {
var rawJSON = $.parseJSON(data);
alert(rawJSON.COORDINATES.latitude);
});
alert("test");
}
I known that the getJSON function is not working because the test alert appears. Why does it not work?
You can do it like so:
sendAjax: function (url, dataObj) {
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(dataObj),
contentType: "application/json; charset=utf-8",
timeout: 30000,
success: function (result) {
//do shit..
}
,
error: function (result) {
}
});
}

How to pass parameter through url using jquery ajax without refreshing page?

I am trying to pass parameter using Get method in Asp.Net. But in address bar url did not change.
Please any one help me to pass parameter using ajax call through url.
Some try from my side is as below Consider url as below
var obj = { templateName: templateName, pageIndex: pageIndex };
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "result.aspx/DisplayResult",
// data: "{'templateName':'" + document.getElementById('txtSearch').value + " &pageIndex : '" + pageIndex + "'' }",
data: JSON.stringify(obj),
dataType: "json",
success: OnSuccess,
error: function (result) {
alert(result.value);
}
});
Your AJAX request looks fine, but there's no reason it'd change the URL. If your request is successful, it will be handled by the OnSuccess function. However, I don't see where you've defined the function referenced by onSuccess. Try this:
var obj = { templateName: templateName, pageIndex: pageIndex };
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "result.aspx/DisplayResult",
// data: "{'templateName':'" + document.getElementById('txtSearch').value + " &pageIndex : '" + pageIndex + "'' }",
data: JSON.stringify(obj),
dataType: "json",
success: function (response) {
// You should see the response object in your dev console
console.log(response);
// If you want to manipulate the URL for some reason after a successful callback,
// do that here, or better, call a function referenced elsewhere that does it.
},
error: function (result) {
alert(result.value);
}
});

Categories