Can't Send Base64 string To C# via AJAX - javascript

I am simply sending a base64 string thru ajax to an aspx page with C# code behind. The string never makes it to the C#. It always comes out empty.
The ajax is being sent in the post request and all other form fields post fine.
My string looks like: QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==
The method that sends the string to c# code behind is:
string signature = Request.Form.Get("newsig");
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap, signature);
The code behind:
string base64image = sig;
// Convert base64string to bytes array
var newbytes = Convert.FromBase64String(base64image);
Sometimes the base64 string is long - could this be the issue? Is there a better way of handling base64 strings in c#?
UPDATE: my ajax post method:
var localbase64string = localStorage["signature"];
var b64 = localbase64string.replace(/^data:image\/(png|jpg);base64,/, "");
var formData = new FormData($(this)[0]);
formData.append( 'newsig', b64);
var sendPost = 'http://xxx.xx/this.aspx';
$.ajax({
type: 'POST',
data: formData,
processData: false,
contentType: false,
timeout: 50000,
url: sendPost,
success: function(data){
alert('Sent!');
window.location.href = './../mainmenu.html';
}, error:function (){
alert("something went wrong!");
}
});

Another way to check what content you're sending is to use Request.Content.ReadAsStringAsync().Result in your C# receiving method.
Here's an example I put together quick:
C#:
public IHttpActionResult PostB64Test(string one, string two)
{
string b64 = Request.Content.ReadAsStringAsync().Result;
return Ok();
}
JS:
// here's an example url. I'm adding the base64 string to the POST body,
// and the other parameters in the query string.
var url = '/api/xxx/b64/?one=' +1 +'&two=' +2 +'';
var b64 = ""; // your base64 string e.g., "9j/4AAQSkZJRgABAg..."
$http.post(url, { b64: b64 });

Related

C# - Get Ajax data

I want to send data though Ajax to a C# file, but when I check the received data, It gives me null. Is there someting wrong with my code?
Javascript file
$(".save").click(function () {
var ss = "Helloo!";
$.ajax({
type: "POST",
url: "/Notes/save.cshtml",
global: true,
data: {fofo: ss},
processData: false,
contentType: false,
cache: false,
success: function(data){
console.log(data);
},
error: function (req, status, error) {
alert("There was a problem with the server. Try refreshing the page.");
return false;
}
});
});
C# File which receives the data (save.cshtml)
#{
var s = Request.Form["fofo"];
var result = "";
var userData = s;
var dataFile = Server.MapPath("~/Notes/lolo.txt");
File.WriteAllText(#dataFile, s);
result = "Information saved.";
}
#if(result != ""){
<p>Result: #result, #s</p>
}
You are not sending a response back to your AJAX function. Not only that what you're doing isn't standard MVC. You should be hitting a Controller which saves the data in the file at the server side and then send the result back using a JsonResult.
For example:
public JsonResult SaveNotes()
{
// Code to save file here
// Return the response
return Json({NotesSaved = true});
}
Then in your JavaScript AJAX success object you will then have the NotesSaved object set to true.
Note: You should also change your URL parameter in the AJAX command to something like:
url: '#Url.Action("SaveNotes")'

Retrieve binary data from C# with Ajax

I'm a bit new in web development and I can't achieve what I'm trying to do.
I have a Database with a table called "PI_Banners", where I store some images. This table stores an ID and a VARBINARY column that contains the binary data of the image.
What I'm trying to do, is to retrieve that data with an Ajax request to a C# function, and create a "img" tag using Data URI Scheme. Then append that new image to a div
This is what I got:
Ajax call:
$(document).ready(function() {
var dto = {};
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'BannerRotativo.aspx/devuelveBanners',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
responsedevuelveBanners(data);
},
error: errorResponse
});
});
Being "devuelveBanners" the C# function.
C# code:
public static string devuelveBanners()
{
DataReader DR;
DR = listaBanners();
//armaJson creates the Json string from the DataReader.
string strJson = GENERAL.armaJson(DR);
return strJson;
}
public DataReader listaBanners()
{
try
{
string strComando;
sqlCommand SQLC;
DataReader DR;
strComando = "SELECT banner_img FROM PI_Banners";
//sqlCon is the connection, and is open already.
SQLC = new System.Data.SqlClient.SqlCommand(strComando, sqlCon);
SQLC.CommandType = CommandType.Text;
DR = SQLC.ExecuteReader();
return DR;
}
catch (Exception ex)
{
throw ex;
}
}
When I parse the Json string back, and create the image:
function responsedevuelveBanners(data)
{
var datos = JSON.parse(data.d);
$("#imgContainer").append("<img src='data:image/jpg;base64," + datos.Rows[0].Row[0].banner_img + "' />");
}
the image is created but doesn't show up, because it has this URL:
data:image/jpg;base64,System.Byte[]
I know I'm doing something terribly wrong trying to retrieve the json data this way, but I don't know how to achieve this!
Thanks in advance!
In order to use <img src="data:image/PNG;base64' the base64 part is because you need to return a Base64 string instead of array of bytes therefore you need to convert your byte[] to 64Base using: Convert.ToBase64String(buffer)
So using your code as example:
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_YourObj.GetImage(), typeof(byte[]));
Your WebApi method should be returning:
return Convert.ToBase64String(resourceByteArray);

Removing Some Characters In A JSON Response

I have a JSON response as the follwoing, but my problem is there are some characters that is not related to the JSON response I want. So I have pass that JSON response to a JavaScript variable and look into the JSON string. That is at the bottom.
-----------JSON Response------------
{
"readyState":4,
"responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"query\":{\"start-date\":\"2014-10-01\",\"end-date\":\"2014-10-23\",\"ids\":\"ga:76546294\",\"dimensions\":\"ga:userType\",\"metrics\":[\"ga:users\"],\"start-index\":1,\"max-results\":10},\"itemsPerPage\":10,\"totalResults\":2,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:76546294&dimensions=ga:userType&metrics=ga:users&start-date=2014-10-01&end-date=2014-10-23&max-results=10\",\"profileInfo\":{\"profileId\":\"76546294\",\"accountId\":\"289147\",\"webPropertyId\":\"UA-289147-1\",\"internalWebPropertyId\":\"456104\",\"profileName\":\"US - Institutional Investors - NP Microsite\",\"tableId\":\"ga:76546294\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:userType\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:users\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:users\":\"1110\"},\"rows\":[[\"New Visitor\",\"826\"],[\"Returning Visitor\",\"284\"]]}</string>",
"status":200,
"statusText":"OK"
}
-----------End of JSON ------------
I want to remove these characters from the beginning of the string:
`{"readyState":4,"responseText":"<?xml version=\"1.0\"encoding=\"utf-8\"?>\r\n<string>`
And I want to remove these character from the end of the string:
`</string>","status":200,"statusText":"OK"}`
So I want to remove these characters. I think a set of JavaScript String functions to be used. But I don't know how to mix them and use.
Could someone help me to solve this matter?
Thanks and regards,
Chiranthaka
UPDATE
I have used the follwoing AJAX function to send and get the JSON response back.
function setJsonSer() {
formData = {
'Email': 'clientlink#site.com',
'Password': 'password1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(JSON.stringify(data));
Load(data);
}
});
}
UPDATE 02
function setJsonSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
dataType: 'json',
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(jsonResult);
Load(data);
}
});
}
I looked at your code:
complete: function(data) {
var jsonResult = JSON.stringify(data);
alert(jsonResult);
Load(data);
}
So you want to stringify your customized result, but your result is not well parsed JSON*? If yes then:
complete: function(data) {
var responseText = data.responseText;
var responseJson = JSON.parse(responseText.match(/[{].*.[}]/));
// you can skip `JSON.parse` if you dont want to leave it as `String` type
alert(JSON.stringify(responseJson)); //or just `responseJson` if you skip `JSON.parse`
Load(JSON.stringify(responseJson));
}
This can solve your problem for a while. But I think the problem is in your backend which did not serve well parsed JSON data. My recommendation is fixing your backend system first.
*Not well parsed JSON because your result some kind of including XML type of string under JSON object.
You have to parse JSON to get stuff which is inside it (You have
done this)
You have to parse the XML to get text which is inside the XML
Here's sample code for XML parsing:
http://www.w3schools.com/xml/tryit.asp?filename=tryxml_parsertest2

How to access the serialized data in PHP file in the following scenario?

How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

Categories