How to send byte array to server side using AJAX - javascript

forgive me if this question is too silly or already asked I googled a lot but I didnt get anything I want. I need to pass a byte array to server side using ajax but its not working as planned my current code is given below
var bytes = [];
for (var i = 0; i < data.length; ++i) {
bytes.push(data.charCodeAt(i));
}
$.ajax({
url: '/Home/ImageUpload',
dataType: 'json',
type: 'POST',
data:{ data:bytes},
success: function (response) {
alert("hi");
}
});
Upload Method
[HttpPost]
public ActionResult ImageUpload(byte[] data)
{
ImageModel newImage = new ImageModel();
ImageDL addImage = new ImageDL();
newImage.ImageData = data;
addImage.AddImage(newImage);
return Json(new { success = true });
}
I know something wrong with my program but I cant find it please help me to solve this

Better do this:
$.ajax({
url: '/Home/ImageUpload',
dataType: 'json',
type: 'POST',
data:{ data: data}, //your string data
success: function (response) {
alert("hi");
}
});
And in controller:
[HttpPost]
public ActionResult ImageUpload(string data)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(data);
//other stuff
}

Related

How to send a JavaScript object on the server side (ASP NET MVC)?

Below is the relevant code (JS+jQuery on the client side):
function getuser(username, password) {
var user = new Object();
user.constructor();
user.username = username;
user.password = password;
//....
$("#a1").click(function () {
var u = getuser($("#username").val(), $("#password").val());
if (u == false) {
alert("error");
} else {
//....
}
});
}
The question is how to send var u to a session on the server side?
You can use ajax to accomplish this. Something like:
$.ajax({
url: "/Controller/Action/",
data: {
u: u
},
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
//handle response from server
}
});
Then have a controller action to receive the data:
[HttpPost]
public ActionResult Action(string u)
{
try
{
//do work
}
catch (Exception ex)
{
//handle exceptions
}
}
Note that /controller/action will be specific to where youre posting the data to in your project
See the documentation
For example:
If you just want to do a simple post the following may suit your needs:
var user = getUser(username, password);
$.post(yourserverurl, user, function(response){console.log("iam a response from the server")});
As the documentation says:
This is a shorthand to the equivalent Ajax function:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
So In your example:
$.ajax({
type: "POST",
url: "/mycontroller/myaction",
data: {user: getUser(username, password)},
success: function(responseFromServer){//handleResponseHere},
error: function(xhr){//handleyourerrorsHere}
dataType: yourdatatype
});

Passing values from controller to view

Controller
public ActionResult Booklist(string bookid) {
return View();
}
View
// other codes
url: 'Index/Booklist',
method: 'POST',
success: function (a) {
var windows = window.open('Index/Booklist');
}
But it seem to invoke dispose(); twice..the reason being the first time it calls return View(); and the second var windows = window.open('Admin/GenerateQRCode');
I need to pass data from controller to javascript in sencha and also pass them to the View..is this possible?
Try this:
public ActionResult Booklist([DataSourceRequest] DataSourceRequest request,string bookid)
{
//result should be your data.
var result=0;
return Json(result, JsonRequestBehavior.AllowGet);
}
// other codes
url: 'Index/Booklist',
method: 'POST',
data:{
'bookid': bookid
},
success: function (result) {
}
Please try this.. Sorry earlier one is not working...
$.ajax({
url: "#Url.Action("Booklist", "Home")",
data: {
'bookid': bookid
},
dataType: 'json',
async: true,
type: 'POST',
success: function (response) {
}
});
public ActionResult Booklist( string bookid)
{
var result=1;
return Json(result, JsonRequestBehavior.AllowGet);
}
This is work for me...

JQuery Ajax Success not being triggered

I'm not sure why my ajax success isn't being triggered/called.
My controller is called and the code is executed fine. I'm not returning anything, so my method is a void! Do I need to return something (ActionResult/JSonResult/etc) to get the success to trigger?
Here is my controller code.
public void DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
}
Here is my ajax call.
$.ajax({
url: '/ManageSpaces/DeleteEvent',
dataType: 'json',
data: {
eventId: eventId,
},
success: function() {
//var obj = JSON.parse(doc);
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}
});
Yes, you need to return JsonResult:
[HttpPost]
public JsonResult DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
return Json("{status:"OK"}");
}
Since you are changing back-end data, set it to POST:
$.ajax({
url: '/ManageSpaces/DeleteEvent',
method: 'POST',
dataType: 'json',
data: {
eventId: eventId,
},
success: function(response) {
if(response.status=="OK"){
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}else{
console.log("Error occured")
}
}
});

C# Web method is not calling in javascript

i create a web method and now i'm calling this in my java script file but it give an path error,it is not able to find path what i'm giving ..
Web method code is :
[System.Web.Services.WebMethod]
public static int ItemCount(string itemId)
{
int val = 0;
Item itm = Sitecore.Context.Database.GetItem(itemId);
val = itm.Children.Count;
return val;
}
java script function calling like as:
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Views/GetItem.aspx/ItemCount",
data: { itemId: itemId },
dataType: "json",
async: false,
success: function (data) {
funRes = data.result;
},
error: function(err) {
alert(err.responseText);
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;}
while i'm giving exact path for the C# method class but it's not working give an error on console, can anyone suggest me what i'm missing here..
There are few rules for ajax to work with asp.net.
Your WebMethod should be public and static.
If your WebMethod expects some parameter(s) than these parameter(s) must be passed as data in ajax.
Name of parameter(s) should be same in WebMethod and in data part of ajax.
Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.
Please check the below sample ajax call
function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code
},
error: function (err) {
alert(err.responseText);
}
});
}
[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}
catch (Exception ex)
{
}
return list;
}
EDIT
If you use GET in ajax than you need to enable your webmethod to be called from GET request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] on top of WebMetod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()
Just Modify the javascript function as below
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
type: "GET",
url: "/Views/GetItem.aspx",
data: 'itemID=' + itemId,
contentType: "application/html",
dataType: "html",
success: function (response) {
funRes= response.result;
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;
}
I am not sure it is a solution for every question subject which web method not fire. But I discovered today when there is ' char in the string. Web Method not firing.

How to send the selected values from list box using ajax

I need to send the multiple selected data from list box using ajax in mvc. I get the selected data. I dont know how to send the data ajax to controller. My code is below:
var Students= [];
var x = document.getElementById("ListBox");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected == true) {
Students.push(x.options[i].text)
}
}
$.ajax({
url: '',
type: 'POST',
data: { id:studenid, class: class, Students: Students},
dataType: 'json',
success: function (data) {
}
}); // id:studenid, class:classs values are send it properly how to add the students?
var Students= [];
var x = document.getElementById("ListBox");
for (var i = 0; i < x.options.length; i++) {
if (x.options[i].selected == true) {
Students.push(x.options[i].text)
}
}
$.ajax({
type: "POST",
data: {StudentList:Students},
url: "index.aspx",
success: function(msg){
alert(msg);
}
});
//Send width param name
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: { paramName: Students},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
}
});
//Get value
[WebMethod]
public static string GetValue(string paramName)
{
}
In The Generic Handler
//Send
$.ajax({
type: "POST",
url:'/MyHandler.ashx?students=Students,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
}
});
//Get
public void ProcessRequest(HttpContext context)
{
string students= (string)context.Request["students"];
}
Your url:'' field is empty. You need to add some URL there for which you have written the server side code which is ready to accept data.
And, of course, I'm guessing that you wish to send data:{Student:Students} instead of data:{User:Users}. Preferably data:{Student:Students}
Please confirm the data type of "Students" object you are passign to controller.
Try to use Array data type,
Public ActionResult SendData(string id, string class,Array Students)
{
}
If it is not working then convert Javascript array to string array with delimeter(,) and use below
Public ActionResult SendData(string id, string class,string Students)
{
}
This will help you.
Thanks.

Categories