Hi I am new to ASP and wondering how to pass an image from the input file using jquery ajax.
I am supposed to pass the path and get the image in the server side? is it possible?
or are there any alternative on it?
what I am doing is that I want to upload a photo while checking if the user is currently in session.
I used ajax so I dont refresh my page everytime I hit the upload button.
$.ajax({
type: "POST",
url: 'Upload.aspx/uploadPhoto',
data: "{ ???? }", <-- what Should I put it here??
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
Is it the right way to upload a photo while checking the session in the webmethod?
var formData = new FormData();
formData.append('file', $('#youruploadbuttonid')[0].files[0]);
$.ajax({
type: "POST",
url: 'Upload.aspx/uploadPhoto',
data: formData,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
var formData = new FormData();
formData.append('file', $('#youruploadbuttonid')[0].files[0]);
$.ajax({
type: "POST",
url: 'Upload.aspx/uploadPhoto',
data: formData,
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
Related
I have a List which look like the following
I want to send this list into my controller,
I am using ajax call to send data from client side to server side
here is my ajax call
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and my method in controller
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
here my List<Holidaysclass> data is showing null
what can I do here?
To send data from browser to controller you need to use POST type and then pass data inside ajax call. you can directly map your entites in action method.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and in controller put HttpPost Data Annotation
[HttpPost]
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
Using ajax get method we cant send data from client to server is not best way. try using POST method send data from client to server.
Reference : https://api.jquery.com/jquery.post/
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
......
});
You can do it like this :
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
Please follow this link for more information :
link
You can not post data in get request. Instead you need to use POST type request.
Here is your updated request.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
Also your action should have [HttpPost] annotation.
try this:
$.ajax({
url: '/Main/updateHoliday',
data: {list: d.weekendLeave},
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
[HttpPost]
public bool updateHoliday(List<Holidaysclass> list)
i have some problem when i use jquery.when function in web form using master page
This is my code in web form using master page
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
And this my master page
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
result is web function is running when master page function not done
please help, thank you so much
You're close, but the when, then and done functions rely on promises. You aren't returning any promises in your code, so it's just running straight through.
First, you'll need to obtain the result of the promise after it completes in the done function in your master page. We'll do that by adding a response parameter to the callback, then passing it through to webFormFunction.
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
Next, we need to add a promise to masterPageFunction and return it. You resolve the promise with the response you want to send back to the done function in your master page. Like so:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
In this way, webFormFunction won't be called until the second ajax call completes, which resolves the promise.
I'm calling a function in the controller using ajax. If there is an error in the controller, it goes to the Error.cshtml page, sends an error email from that page, but it won't render the Error.cshtml page on the screen, it stays on the page with the ajax call.
How do I fix that?
Here is the ajax call:
$("#County").change(function () {
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
failure: function (data) {
alert('failure');
},
});
});
Here is the customErrors from the main web.config:
<customErrors mode="On" defaultRedirect="~/Error" redirectMode="ResponseRedirect"/>
In your $.ajax definition you should use error property, not failure, check documentation. Like this:
$.ajax({
url: '#Url.Action("UpdateCountySessionVariables", "Home")',
type: 'POST',
data: JSON.stringify({ countyId: $("#County").val() }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
location.reload();
},
error: function (data) {
alert('failure');
},
});
You also can get full error page like this:
error: function (httpRequest) {
console.log(httpRequest.responseText);
},
I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!
try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});
In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.
I am sending a collection of GUID-like objects to my MVC controller like so:
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: {
songIds: JSON.stringify(songIds)
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});
The data being sent in my request header looks like:
songIds:["6cb44f55-9fd5-4540-9b11-75ccce816d67"]
and my MVC3 controller method looks like:
[HttpGet]
public ActionResult GetByIds(List<Guid> songIds)
{
SongManager songManager = new SongManager(SongDao, PlaylistDao, PlaylistItemDao);
IList<Song> songs = songManager.GetByIds(songIds);
return new JsonDataContractActionResult(songs);
}
In this implementation I receive a non-null List object, but it is always empty. What's my mistake?
EDIT: If I POST like this instead of GET it works fine. How come??
$.ajax({
type: 'POST',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
songIds: songIds
}),
success: function (data) {
loadedSongs = loadedSongs;
if (callback) {
callback(data);
}
},
error: function(error) {
console.error(error);
}
});
You should try to use "traditional" option set to true for your jQuery Ajax request.
Refer to documentation for more details : http://api.jquery.com/jQuery.ajax/
And you should also remove the JSON.Stringify part.
Can you try this out and let me know if it worked out for you ?
I Did a test on my end and it works just fine.
$.ajax({
type: 'GET',
url: 'http://localhost:61975/Song/GetByIds',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
traditional: true, //// traditional option to true
data: {
songIds: songIds /// no JSON.stringify
},
success: function (data) {
},
error: function(error) {
console.error(error);
}
});