Hello Everyone I am using angularjs to send byte array on server side but I am not getting data on server side.
Here is my code.
$scope.Upload = function () {
var bytesToSend = [253, 0, 128, 1]
var send = new Uint8Array(bytesToSend)
var Upload = $.ajax({
type: 'POST',
url: "/UploadFile",
dataType: JSON,
contentType: false,
data: send,
success: function (send) {
toastr.success("Upload Successfully");
}
});
Upload.error(function () { console.log(bytesToSend+'gaurav') });
}
And here is my server side code
[HttpPost]
[Route("UploadFile")]
public bool UploadedFile(byte[] send)
{
return false;
//return await CenterGateWay.UpldFile(up);
}
}
I am not getting data in byte[] send it is showing null value.
please anyone help where I am wrong And I am getting data in console
here [253, 0, 128, 1].
Using firefox browser right now.
Please use following code to resolve your issue.
$scope.Upload = function () {
var bytesToSend = [253, 0, 128, 1];
var send = new Uint8Array(bytesToSend)
var Upload = $.ajax({
type: 'POST',
url: "/Home/UploadFile",
dataType: "JSON",
data: { send: btoa(String.fromCharCode.apply(null, send)) },
success: function (send) {
toastr.success("Upload Successfully");
}
});
Upload.error(function () { console.log(bytesToSend + 'gaurav') });
}
In Controller
[HttpPost]
[Route("UploadFile")]
public bool UploadedFile(string send)
{
return false;
//return await CenterGateWay.UpldFile(up);
}
Even I got help from this link Please refer it:-
Related
I have some AJAX code in my JavaScript which is not showing any success or failure alert.
function AttemptHouseViewingAppointment(house) {
var imgOfHouse = $(house).attr("value");
$.ajax({
type: "POST",
url: '#Url.Action("AttemptHouseViewingAppointment", "Viewing")',
dataType: "json",
data: ({
userId: #Model.UserId,
appointmentKey: '#Model.Key',
chosenHouse: imgOfHouse
}),
success: function (data) {
alert(data);
if (data.success) {
alert(data.message);
} else { alert(data.Message) }
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
The above function is called when I click an image on the screen. This part works fine as I have set a breakpoint on my ASP controller and I can see the relevant action being called. C# code below:
public ActionResult AttemptHouseViewingAppointment(int userId, string appointmentKey, int chosenHouse)
{
string selecteHouseName = $"./house-code-icons/{chosenHouse}.png";
var house =
_ctx.houses.Where(x => x.HouseID == userId && x.Icon == chosenHouse)
.FirstOrDefault() ?? null;
if(house != null)
{
var member = _ctx.User.FirstOrDefault(x => x.Id.Equals(userId));
_ctx.Appointments.Add(new ViewingModel
{
House = chosenHouse,
UserId = userId
});
_ctx.SaveChanges();
return Json(new { success = true, message = "Appointment Confirmed!" });
}
else
{
return Json(new { success = false, message = "Sorry, a booking has already been made!" });
}
}
Even though, the return Json lines are being hit and returned to the page, there is no alert popup on my page to let user know if success or not. Please let me know if any questions.
Thanks
Add the done function to the end of Ajax
$.ajax({
.
.
.
}).done(function( response ) {
alert(response);
...
});
I am new to ajax, currently I am using ajax trying to send base64string from view to controller and get a JsonResult as following:
$.ajax({
url: "#Url.Action("UploadSignature", "JobList")",
type: "POST",
dataType: "json",
data: { photoByte: base64String, eventRecordID: "123456" },
success: function (result) {
if (result.success === true) {
alert("Signature uploaded !");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
}
});
And my controller method is as following:
[HttpPost]
public async Task<ActionResult> UploadSignature(string photoByte, string eventRecordID)
{
byte[] photoAfterConvert = Convert.FromBase64String(photoByte);
...
//Upload photoAfterConvert to server
...
return Json(new { success = true });
}
However, the code above sometimes not working especially when the base64String is too long. Once I call the ajax, it hang and never go inside the controller method. Approximately 1 minute later, it will trigger the error callback function and the message is shown as below which is meaningless.
{"readyState":0,"status":0,"statusText":"error"}
Therefore, I was thinking is there any alternative way that I can send large string data from view to controller via ajax? Is sending blob a good choice? If yes, how can I achieve it by sending blob? What is the datatype that I need to put in the controller parameter to accept blob?
Thanks in advance for any help.
try this:
function Base62ToBlob (dataURI) {
'use strict'
var byteString,
mimestring
if (dataURI.split(',')[0].indexOf('base64') !== -1) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], { type: mimestring });
}
call action metthod from client side:
function FileUploadServer (blob) {
var fd = new FormData();
fd.append("file", blob, "FileName.png");
$http.post("URL", fd, {
headers: { 'Content-Type': undefined }
})
.success(function (response, status, headers, config) {
});
}
server side call receiver method:
public ContentResult Upload()
{
var files = System.Web.HttpContext.Current.Request.Files;
return CustJson( null);
}
Getting an error when trying to delete a user from db.
Here is the code that i wrote:
This is server side:
#RestController
public class EmployeeRestController {
#DeleteMapping( value = "/delete_user")
public List<Employee> deleteEmployee(#RequestParam(value = "id") Integer id) {
employeeService.deleteEmployee(id);
List<Employee> list = employeeService.getAllEmployees();
return list;
}
}
Client side:
function delete_row(id){
$.ajax({
type:'DELETE',
url:'/delete_user',
dataType: 'json',
data:JSON.stringify({
id:id
}),
success:function(data){
console.log(data);
}
});
}
Error from server side :
DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'id' is not present]
Error code from client side is 400
I am noob at ajax , javascript and spring. Sorry if the problem is obvious and thanks in advance.
did you tried this
function delete_row(id){
$.ajax({
type: "DELETE",
url: "/delete_user",
data: { id: id },
success: function (data) {
console.log(data);
},
error: function () {
}
});
}
or directly bind to url
function delete_row(id){
$.ajax({
type: "DELETE",
url: "/delete_user?id="+id,
success: function (data) {
console.log(data);
},
error: function () {
}
});
}
Try using PathVariable instead of RequestParam.
#DeleteMapping(value = "/delete_user/{id}")
public List<Employee> deleteEmployee(#PathVariable("id") Integer id) {
employeeService.deleteEmployee(id);
List<Employee> list = employeeService.getAllEmployees();
return list;
}
}
I want print receipt in client side without print dialog box, i am using mvc this is my solution to achieve my problem.
EPSON printer was installed in my system.This solution is working when host in my local iis but its not work when host in server and accessing from my local system getting "An error occurred while processing your request" error. In server no printer is installed.
$.ajax({
type: "POST",
url: '../Service/print',
cache: false,
data: { iprintData: printData, iprinterName: sPrinterName },
success: function (data) {
// alert('print Send Successfully');
},
error: function (ex) {
alert(ex.responseText);
// alert('error while Seding print');
}
});
this is my code in controller
public JsonResult print(string iprintData, string iprinterName)
{
Boolean bflag = false;
System.Web.HttpContext.Current.Session["_printData"] = iprintData;
PrintDocument printDocument = new PrintDocument();
printDocument.PrintController = new StandardPrintController();
printDocument.PrintPage += PrintDocumentOnPrintPage;
printDocument.PrinterSettings.PrinterName = iprinterName;
//printFont = new System.Drawing.Font("Arial", 10);
printDocument.Print();
bflag = true;
return Json(bflag, JsonRequestBehavior.AllowGet);
}
public static Image resizeImage(Image image, int new_height, int new_width)
{
Bitmap new_image = new Bitmap(new_height, new_width);
Graphics g = Graphics.FromImage((Image)new_image);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, new_width, new_height);
return new_image;
}
private void PrintDocumentOnPrintPage(object sender, PrintPageEventArgs e)
{
string printstring = System.Web.HttpContext.Current.Session["_printData"].ToString();
string path = HttpContext.Server.MapPath("~/content/Images/logo.png");
System.Drawing.Image img = Image.FromFile(path);
//img = resizeImage(img, 80, 60);
e.Graphics.DrawImage(img, 6, 100);
e.Graphics.DrawString(printstring, new System.Drawing.Font("ronnia", 9), Brushes.Black, 10, 150);
}
can any one help me from this ?
first you have to write windows service that contain HttpListener.
write your printing code inside the service
Install the service in client machine
call that service using ajax like below.
function PrintReceipt() {
var PrintData = JSON.parse($("#receiptData").html())
if (PrintData.length > 0) {
$.ajax({
type: "POST",
url: "http://localhost:41963/printOrder",
data: JSON.stringify({ "PrintData": PrintData }), //reciept data
crossDomain: true,
success: function (response) {
},
error: function () {
}
});
}
}
set System.Drawing.dll property
Copy Local=true
I am new to .NET MVC so please bear with me.
I wrote a function that gets triggered when there is a blur action on the textarea control:
function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}
jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});
This works fine and will hit the controller:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
I get the intended results if the URL is valid; it will return a partialview to the .done() function and I just display it in code. However, if the URL is not valid i want it to hit either complete, success, or done (I have been playing around to see which it will hit but no luck!) and do something with the returned data. I had it at some point trigger either complete or success but the data was 'undefined'. Can someone help me out on this?
Thanks!
In both cases your controller action is returning 200 status code, so it's gonna hit your success callback:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});
But of course a much better and semantically correct approach is to set the proper status code when errors occur instead of just returning some 200 status code:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
and then in your AJAX call you would handle those cases appropriately:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);
// and display the error message to the user
alert(data.message);
}
}
});
Also don't forget that you have some standard way of returning your error messages you could subscribe to a global .ajaxError() handler in jQuery instead of placing this code in all your AJAX requests.