Ajax post to controller not found - javascript

I have the following JavaScript:
function saveAvatar() {
var img = $('#preview-pane .preview-container img');
$('#avatar-crop-box button').addClass('disabled');
$.ajax({
type: "POST",
url: App.url + "/Save",
traditional: true,
data: {
width: img.css('width'),
height: img.css('height'),
marginLeft: img.css('marginLeft'),
marginTop: img.css('marginTop'),
fileName: img.attr('src'),
userId: this.userId
}
}).done(function (data) {
if (data.success === true) {
if (!keepCropBox) {
$('#avatar-crop-box').addClass('hidden');
location.reload();
}
} else {
alert(data.errorMessage)
}
}).fail(function (e) {
alert('Cannot upload avatar at this time');
});
}
Here is my save method:
[HttpPost]
public async Task<ActionResult> Save(string marginTop, string marginLeft, string height, string width, string fileName, int userId)
{
var image = ImageHelper.Save(marginTop, marginLeft, height, width, fileName);
if(image != "error")
{
var savedProfilePicture = await userService.SaveProfilePicture(image, userId);
if (savedProfilePicture > 0)
{
return Json(new { success = true, avatarFileLocation = image });
}
}
return Json(new { success = false, errorMessage = "Could not save profile picture" });
}
This works fine when I run the project on my local machine and when the App.url is set to http://localhost:1234/Home
But when I deploy the project to a server, and the App.url becomes: http://project-on-another-machine.com/Home. It's not working with the Save-method. I'm always getting a 404 not found.
I have other method that works fine, but not this particular Save-method. Why is this?

In your view add the value of URL in a global variable like this
<script>
var params["saveUrl"] = "#Action("Save","Home")";
</script>
and then use this variable in your js file to access the action method.
$.ajax({
type: "POST",
url: params["saveUrl"],
...

The Url should be url: "/Home/Save/"
function saveAvatar() {
var img = $('#preview-pane .preview-container img');
$('#avatar-crop-box button').addClass('disabled');
$.ajax({
type: "POST",
url: "/Home/Save",
traditional: true,
data: {
width: img.css('width'),
height: img.css('height'),
marginLeft: img.css('marginLeft'),
marginTop: img.css('marginTop'),
fileName: img.attr('src'),
userId: this.userId
}
}).done(function (data) {
if (data.success === true) {
if (!keepCropBox) {
$('#avatar-crop-box').addClass('hidden');
location.reload();
}
} else {
alert(data.errorMessage)
}
}).fail(function (e) {
alert('Cannot upload avatar at this time');
});
}

Related

How can I console "Sucess" present on $.ajax?

How can I show "success" up on Console screen? In a nutshell, I want to show on Console the erros that I forced to happen in a register formulary.
function getRoot() {
var root = "http://" + document.location.hostname + "/login_AMUBA/";
return root;
}
$("#formCadastro").on("submit", function (event) {
event.preventDefault();
var dados = $(this).serialize();
function response() {
return $.ajax({
url: getRoot() + 'controllers/controllerCadastro',
type: 'post',
dataType: 'json',
data: dados,
success: function (response) {
console.log(response);
}
});
}
if (response) {
console.log(success);<--Here
}
});
Finally, the final function (on a php file) should show the error(errors) on console screen, but only "else" works (when it is not commented)
public function validateFinalCad($arrVar)
{
if (count($this->getErro()) > 0) {
$arrResponse = [
"retorno" => "erro",
"erros" => $this->getErro()
];
} else {
/*$this->cadastro->insertCad($arrVar);*/
}
return json_encode($arrResponse);
}

How to pass parameters from Ajax function to controller action?

I have a button in my view that calls a jQuery Ajax function passing in parameters from my model
<input type="button" value="Run Check" onclick="runCheck('#actionItem.StepID', '#Model.Client.DatabaseConnectionString', '#Model.Client.ClientID')" />
The jQuery function
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
contentType: 'application/json;',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (data) {
if (data.IsValid) {
//alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
//alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
</script>
And finally my controller action
public JsonResult ProcessFeedbackHasRows(int StepId, string DatabaseConnectionString, int ClientID)
{
bool isValid = true;
FeedbackDetails feedbackDetails = new FeedbackDetails();
feedbackDetails.Data = _clientProcessingService.GetProcessingFeedbackDetails(StepId, DatabaseConnectionString);
if (feedbackDetails.Data.Rows.Count == 0)
{
_clientProcessingService.RunProcessStepConfirmation(DatabaseConnectionString, StepId, ClientID, "No information returned, automatically proceeding to next step.");
isValid = false;
}
return Json(new { IsValid = isValid });
}
The logic in the ajax function works when I hard code specific values in the controller to represent the appropriate step, client & database but when I debug I see the two integers as 0 and the string as null.
How can I pass these values to the controller? I considered just storing them in ViewBag or ViewData but that seems clunky and not really a good practice.
Try this,
var req={ stepId: x, databaseConnectionString: y, clientId: z }
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(req),
success: function (data) {
if (data.IsValid) {
//alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
//alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
As per this question, I had to remove my contentType property and the values were passed successfully.
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (result) {
if (result.IsValid) {
alert('true');
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};

Ajax callback is firing after function call

Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}

Why Ajax edit code not work properly? can you help me?

I m working on simple registration i have two forms one is registration another is city, When city is newly added it get added update perfectly but when i use city in registration form eg pune. pune will not get edited or updated, code written in ajax
function UpdateCity(Ids) {
debugger;
var Id = { Id: Ids }
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
}
})
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
}
debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
dataType: "text",
success: function (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
window.setTimeout(function () { location.reload() }, 3000)
}
})
})
}
Controller
public bool UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
return true;
}
catch (Exception Ex)
{
return false;
}
}
A few stabs in the dark here but, try changing your code to the following (with comments).
Controller:
// !! This is a POST transaction from ajax
[HttpPost]
// !! This should return something to ajax call
public JsonResult UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
// !! Change return type to Json
return Json(true);
}
catch (Exception Ex)
{
// !! Change return type to Json
return Json(false);
}
}
Script:
function UpdateCity(Ids) {
//debugger;
var Id = { Id: Ids };
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/GetCityDetail");
}
});
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
};
//debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
// !! Change return type to Json (return type from Server)
dataType: "json",
success: function (city) {
// !! Check result from server
if (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
// !! Why reload location?
// window.setTimeout(function () { location.reload(); }, 3000);
} else{
// !! Change this to something more suitable
alert("Server Error: /City/UpdateCity");
}
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/UpdateCity");
}
});
});
}
This should give you some more clues as to what's going on.

Resumable file upload customize name and add additional parametrs

I'm using http://resumablejs.com/ and can't understand how I can change filename after upload.
Describe a little more my situation:
I have file UploadFile.php with default code:
include 'vendor/autoload.php';
use Dilab\Network\SimpleRequest;
use Dilab\Network\SimpleResponse;
use Dilab\Resumable;
$request = new SimpleRequest();
$response = new SimpleResponse();
$resumable = new Resumable($request, $response);
$resumable->tempFolder = 'tmps';
$resumable->uploadFolder = 'upload/video';
$resumable->process();
I know that if I will use following:
$originalName = $resumable->getOriginalFilename(Resumable::WITHOUT_EXTENSION);
$slugifiedname = 'custom_prefix_'.$originalName;
$resumable->setFilename($slugifiedname);
It's will add 'custom_prefix_' to my filename.
But! I need use for prefix some additional information from form (Firstname and Lastname), how I can add this information to my request?
In frontend my file looks like:
<script type="text/javascript">
window.onload = (function () {
var r = new Resumable({
target: '/UploadFile.php',
maxChunkRetries: 2,
maxFiles: 1,
prioritizeFirstAndLastChunk: true,
simultaneousUploads: 4,
chunkSize: 5 * 1024 * 1024,
uploadMethod: 'POST',
maxFileSize: 550 * 1024 * 1024
});
...
uploadFile.on('click', function () {
$('.valid').html('');
if (results.children().length > 0) {
$.ajax({
url: '/Validate.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
dataType: "json",
success: function (data) {
if (results.children().length > 0) {
if(data[0]==true && data[1]==true){
$.ajax({
url: '/FormUpload.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
success: function (data) {
if (results.children().length > 0) {
r.upload();
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
}else{
if(data[0]==false){
valid.text('Please complete all required fields!');
}
if(data[1]==false){
valid.text('Please complete all exeption fields!');
}
}
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
} else {
nothingToUpload.css('opacity', 1);
setTimeout(function () {
nothingToUpload.css('opacity', 0);
}, 3000);
}
});
Try this code:
$resumable->process();
// you can get file information after the upload is complete
if (true === $resumable->isUploadComplete()) { // true when the final file has been uploaded and chunks reunited.
$extension = $resumable->getExtension();
$filename = $resumable->getFilename();
}
I found solution in my file FormUpload.php I return necessary information and send it like this:
uploadFile.on('click', function () {
$('.valid').html('');
if (results.children().length > 0) {
$.ajax({
url: '/Validate.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
dataType: "json",
success: function (data) {
if (results.children().length > 0) {
if(data[0]==true && data[1]==true){
$.ajax({
url: '/FormUpload.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
success: function (data) {
var data = jQuery.parseJSON(data);
if (results.children().length > 0) {
r.files[0].fileName = data.new_file_name;
r.upload();
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
}else{
if(data[0]==false){
valid.text('Please complete all required fields!');
}
if(data[1]==false){
valid.text('Please complete all exeption fields!');
}
}
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
} else {
nothingToUpload.css('opacity', 1);
setTimeout(function () {
nothingToUpload.css('opacity', 0);
}, 3000);
}
});

Categories

Resources