Ajax doesn't call method in production - ajax

This is probably something simple, but I can't find what is wrong to give me this problem.
I have a form in a HTML page that calls, on click, a method in a controller via Ajax. It works perfectly in my development machine, but when I put it in production environment the call never gets to the controller. Anyone have any ideas why? I've seen many questions like this, most of them saying it's most likely a problem with the action path, but I've tried a lot of diferent ways to call it (with razor html helpers, passing the absolute path, etc) and got nothing.
The form (simple):
<form action="/Home/SendMail/" id="contactForm" type="post">
<input type="text" name="name" id="name">
<input type="email" name="email" id="email">
<input type="text" name="subject" id="subject">
<textarea name="message" id="message"></textarea>
<input type="submit" value="Enviar Mensagem">
</form>
The ajax call:
$("#contactForm").validate({
submitHandler: function(form) {
var submitButton = $(this.submitButton);
submitButton.button("loading");
var url = $("#contactForm").attr("action");
$.ajax({
type: "POST",
url: url,
data: {
"name": $("#contactForm #name").val(),
"email": $("#contactForm #email").val(),
"subject": $("#contactForm #subject").val(),
"message": $("#contactForm #message").val()
},
dataType: "json",
success: function (data) {
if (data.response == "success") {
$("#contactSuccess").removeClass("hidden");
$("#contactError").addClass("hidden");
$("#contactForm #name, #contactForm #email, #contactForm #subject, #contactForm #message")
.val("")
.blur()
.closest(".control-group")
.removeClass("success")
.removeClass("error");
if(($("#contactSuccess").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactSuccess").offset().top - 80
}, 300);
}
} else {
$("#contactError").removeClass("hidden");
$("#contactSuccess").addClass("hidden");
if(($("#contactError").position().top - 80) < $(window).scrollTop()){
$("html, body").animate({
scrollTop: $("#contactError").offset().top - 80
}, 300);
}
}
},
The controller method:
public class HomeController : Controller
{
[HttpPost]
public JsonResult SendMail(string name, string email, string subject, string message)
{
try
{
string emailTo = "myemail#example.com";
MailMessage Email = new MailMessage();
Email.From = new MailAddress("mail#example.comr");
string[] emailsDestinarios = emailTo.Split(';');
foreach (string emailDestinatario in emailsDestinarios)
{
Email.To.Add(new MailAddress(emailDestinatario));
}
Email.Subject = subject;
Email.IsBodyHtml = true;
Email.Body = DateTime.Now.ToString() + "<br />" + name + "<br />" + email + "<br /><br /><b>" + subject + "</b><br /><br />" + message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("mail#example.com", "mypassword");
smtp.Send(Email);
return Json(new { response = "success" });
}
catch (Exception ex)
{
return Json(new { response = ex.Message });
}
}
}
It works fine in development, but not in production environment.

Related

No response from POST request Spring boot - AJAX

I try to send data from AJAX POST request and don't get an answer, but if I send the exact same request with POSTMAN I do get a response. I don't know what is causing this.
REST Spring boot:
#RestController
public class UsuarioRest {
UsuarioController usuarioController = new UsuarioController();
String token = null;
Usuario usuario = null;
#GetMapping(value = "/hola")
public ResponseEntity<?> login(#RequestBody Usuario user) {
token = usuarioController.login(user.getUser(), user.getPassword());
if (token != null) {
usuario = new Usuario(user.getUser(), user.getPassword());
usuario.setToken();
return new ResponseEntity<Usuario>(usuario, HttpStatus.OK);
} else {
return new ResponseEntity<Error>(new Error(), HttpStatus.BAD_REQUEST);
}
}
AJAX POST:
$(document).ready(
function() {
// SUBMIT FORM
$("#btnEnviar").submit(function(event) {
// Prevent the form from submitting via the browser.
event.preventDefault();
ajaxPost();
});
function ajaxPost() {
// PREPARE FORM DATA
var User = {
id:0,
user : $("#user").val(),
password : $("#password").val(),
token:0
}
console.log(formData);
// DO POST
$.ajax({
type : "GET",
contentType : "application/json",
url : "hola",
data : JSON.stringify(User),
dataType : 'json',
success : function(result) {
console.log(result);
if (result.status == "success") {
$("#resultado").html(
"" + result.data.token
+ "Post Successfully! <br>"
+ "---> Congrats !!" + "</p>");
} else {
console.log(result);
$("#resultado").html("<strong>Error</strong>");
}
},
error : function(e) {
alert("Error!")
console.log("ERROR: ", e);
}
});
}
})
HTML:
<body>
<form id="login">
<input type="text" id="user">
<input type="text" id="password">
<button type="submit" id="btnEnviar" >Enviar</button>
</form>
<div id="resultado">
<button id="hola"></button>
</div>
</body>

Getting the Error 'Not Found' when Mapping Routes

When I try to Map a Route to a Api method call, I only get 'Not Found' in the index.html calling function. I've tried multiple routing template combinations but all get the same error, Not Found. Can anyone help with this?
My Class
public class LogonController : ApiController
{
[HttpPost]
[ActionName("Logon")]
public Boolean Logon(string username, string password)
{
return true;
}
}
My WebApiConfig
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "Logon",
routeTemplate: "api/{controller}/{logon}/{username}/{password}",
defaults: new
{
username = RouteParameter.Optional,
password = RouteParameter.Optional
}
);
}
My Index.html Caller
<div>
<h2>All Products</h2>
<ul id="logon" />
</div>
<div>
<h2>Get User ID</h2>
<input type="text" id="username" size="5" />
<input type="text" id="password" size="5" />
<input type="button" value="Search" onclick="find();" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/logon';
function formatItem(item) {
return 'True';
}
function find() {
var username = $('#username').val();
var password = $('#password').val();
// var email = $('#email').val();
// var firstname = $('#firstname').val();
// var lastname = $('#lastname').val();
// $.getJSON(uri + '/' + username + ',' + password + ',' + email + ',' + firstname + ',' + lastname)
$.getJSON(uri + '/' + username + ',' + password)
.done(function (data) {
$('#logon').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#logon').text('Error: ' + err);
});
}
</script>
I found the answer to my problem. I was going about everything the wrong way. First I was not returning an 'IEnumerable' object.
Next, there was no {action} attribute in my route mapping.
Finally, the request which was coming from an html file was not passing parameters. Here are the changes that were made.
My Class
public class LogonController : ApiController
{
Logon[] log = new Logon[]
{
new Logon { UserName = "Roland", Email = "mike#optonline.net", Password = "test" },
new Logon { UserName = "Yo-yo", Email = "mike#optonline.net", Password = "test" },
new Logon { UserName = "Hammer", Email = "mike#optonline.net", Password = "test" }
};
[ActionName("LogonApi")]
public IEnumerable<Logon> GetThisLogon(string username, string password)
{
var s = log.FirstOrDefault((p) => p.UserName == username);
if (s == null)
{
return log;
}
return log;
}
[ActionName("LogonApi")]
public IEnumerable<Logon> GetLogon()
{
return log;
}
The WebApiConfig
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "LogonApi",
routeTemplate: "api/{controller}/{action}/{username}/{password}",
defaults: new
{
username = RouteParameter.Optional,
password = RouteParameter.Optional
}
);
The JavaScript Call
<div>
<h2>Get User ID</h2>
<input type="text" id="username" size="5" />
<input type="text" id="password" size="5" />
<input type="button" value="Search" onclick="find();" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/logon/LogonApi';
function formatItem(item) {
return 'True';
}
function find() {
var username = $('#username').val();
var password = $('#password').val();
$.getJSON(uri + '/', { username: username, password: password})
.done(function (data) {
$('#logon').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#logon').text('Error: ' + err);
});
}

Upload files with Jquery File Upload in ASP.NET MVC 3

Does anyone has a clean suggestion of instantiate this jquery's useful library.
I need to submit files and manage the Json response from the server.
I always get none json response within the Js code. I have reviewed some articles mentioning it but the code doesn't fit to the purpose.
The situation is: I achieve the submition and saving in the database but the Json response never arrives.
Thanks in advance.
This is my view code:
<script type="text/javascript">
$("#formUplImg").fileupload({
dataType: "json",
url:'#Url.Action("CreateJson","ProductImage")',
done: function (e, data) {
alert(data.StatusMessage);
}
});
</script>
#using (Html.BeginForm("CreateJson", "ProductImage", FormMethod.Post, new { id = "formUplImg", enctype = "multipart/form-data", #class = "jqtransform" }))
{
#Html.ValidationSummary(true)
<div class="rowElem">
<input type="file" id="Content" name="Content" />
</div>
<div class="rowElem">
#Html.ValidationMessageFor(item => item.Content)
</div>
<div class="rowElem">#Html.JQueryUI().Button("Guardar imagen", ButtonElement.Button, ButtonType.Submit, new { id = "guardar_imagen" })</div>
}
This is my controller action code:
[HttpPost]
public ContentResult CreateJson(UploadedFileInfo fileInfo)
{
try
{
if (fileInfo.Content == null)
throw new Exception("Hubo problemas con el envĂ­o. Seleccione un archivo a subir");
var file = new TempDocument
{
CreatedBy = User.Identity.Name,
CreationTime = DateTime.Now,
FileName = fileInfo.Content.FileName,
MimeType = fileInfo.Content.ContentType,
Size = fileInfo.Content.ContentLength,
Content = new byte[fileInfo.Content.ContentLength]//Image content to save
};
fileInfo.Content.InputStream.Read(file.Content, 0, fileInfo.Content.ContentLength);//Reading image content into ProductImage object
DocumentsManager.StorePendingDocuments.Add(file);
DocumentsManager.SaveTempDocuments();//Store each document uploaded to: TempDocument Table
TempData["SuccessMsg"] = "The image was saved successfully";
var json = new JavaScriptSerializer().Serialize(new { Success = true, StatusMessage = "El objeto fue insertado correctamente" });
return Content(json, "application/json");
}
catch (Exception exception)
{
TempData["ErrorMsg"] = exception.Message;
var json = new JavaScriptSerializer().Serialize(new { Success = false, StatusMessage = exception.Message });
return Content(json, "application/json");
}
}
Use return type of Action as ActionResult and use:
`return Json(new { Result = "Success" });`
So that on success you will get Json object containing result value.

MVC 3 razor - maintain checkbox values between page requests

I have a page with checkboxes which are used to filter a webgrid.
To give my question some context by unchecking a checkbox the data will be filtered to show fewer results in my webgrid by using ajax request. But once I click on the numbers below the webgrid to cycle through the next set of records in the grid I lose the current state of my checkboxes. This is because I am calling my ActionResult method again which is loading the page again.
So how do I maintain those checkbox values between page loads?
This is my view
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#*#model UserManager.Models.vw_UserManager_Model
*#
#{
ViewBag.Title = "User Manager Dashboard";
}
#Html.ActionLink("Create New User", "CreateUser")
<div class="webgrid-filter">
<b>#Html.Label("Select a filter: ")</b>
<br />
#Html.Label("Toggle ALF Intelligence users:")
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("Index", "UserManager")')" id="chkFilterAlfIntell" checked="checked" />
#Html.Label("Toggle ALF Connect users:")
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("Index", "UserManager")')" id="chkFilterAlfConn" checked="checked"/>
#Html.Label("Toggle BRAD users:")
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("Index", "UserManager")')" id="chkFilterBrad" checked="checked"/>
</div>
<div id="webgrid-wrapper">
#Html.Partial("~/Views/Partial/_WebGridUserManager.cshtml", Model)
</div>
<br />
<script type="text/javascript">
$(document).ready(function () {
// Disable checkboxs where a user is not active.
$(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");
// Style tables.
function jQueryUIStyling() {
$('input:button, input:submit').button();
$('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
$('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
jQueryTableStyling();
} // end of jQueryUIStyling
function jQueryTableStyling() {
$('.webgrid').addClass('ui-grid-content ui-widget-content');
$('.webgrid-header').addClass('ui-state-default');
$('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
} // end of jQueryTableStyling
});
</script>
<script type="text/javascript">
function filterGrid(url) {
var filters = getFilterVals();
// console.log(filters);
$.ajax({
url: url,
type: "POST",
async: true,
dataType: "html",
data: "alfConnect=" + filters.alfConnect + "&" + "alfIntelligence=" + filters.alfIntelligence + "&" + "brad=" + filters.brad,
success: function (data) {
$('#webgrid-wrapper').empty().html(data);
// $('#webgrid-wrapper').html(data);
}
});
}
function getFilterVals() {
filters = new Object();
if ($('.webgrid-filter #chkFilterAlfIntell').is(':checked')) {
filters.alfIntelligence = 1;
}
else {
filters.alfIntelligence = 0;
}
if ($('.webgrid-filter #chkFilterAlfConn').is(':checked')) {
filters.alfConnect = 1;
}
else {
filters.alfConnect = 0;
}
if ($('.webgrid-filter #chkFilterBrad').is(':checked')) {
filters.brad = 1;
}
else {
filters.brad = 0;
}
return filters;
}
function logUserOff(url) {
var answer = confirm('Are you sure you want to save this data?')
if (answer) {
// alert(url + ": " + value);
$.ajax({
url: url,
type: "POST"
// data: value
}).done(function () {
$(this).addClass("done");
});
return true;
}
else {
return false;
}
};
</script>
In div class webgrid filter you can see the checkboxes which I want to maintain the values of.
My actionResult for this view
public ActionResult Index()
{
try
{
var model = new UserManagerTestEntities().vw_UserManager_Model;
//var model = new UserManager.Models.vw_UserManager_Model();
return View(model.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
Does anyone have suggestions? Thanks!
Instead of doing action on your controller, maybe you could: as click action on checkbox call javascript function which at the end would make ajax call.

How would I pass a value via a ajax form post in MVC3?

I have the ability to upload a file and save it to a directory. That is all good. I need to make an entry to my database with information about that file. So far I am not sure how to pass a value from the view to the controller in this particular case. I have tried to pass it as a method parameter but the value is not getting posted.
Here is my Razor form:
#using (Html.BeginForm("AjaxUpload", "Cases", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
{
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
}
<div id="attachments">
#Html.Partial("_AttachmentList", Model.Attachments)
</div>
Here is my jQuery to ajaxify the form:
$(function () {
$('#ajaxUploadForm').ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$('#ajaxUploadForm').block({ message: '<h1><img src="/Content/images/busy.gif" /> Uploading file...</h1>' });
},
success: function (result) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, result.message);
//$('#attachments').html(result);
},
error: function (xhr, textStatus, errorThrown) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
Here is the controller method:
public FileUpload AjaxUpload(HttpPostedFileBase file, int cid)
{
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
var attach = new Attachment { CasesID = cid, FileName = file.FileName, FileType = file.ContentType, FilePath = "Demo", AttachmentDate = DateTime.Now, Description = "test" };
db.Attachments.Add(attach);
db.SaveChanges();
//TODO change this to return a partial view
return new FileUpload { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I would like cid to be passed to this method so that I can insert a record into the database.
You could include it as a hidden field inside the form:
#Html.Hidden("cid", "123")
or as a route value:
#using (Html.BeginForm(
"AjaxUpload",
"Cases",
new { cid = 123 },
FormMethod.Post,
new { enctype = "multipart/form-data", id = "ajaxUploadForm" }
))
{
...
}

Resources