Ajax form validation in MVC - javascript

I have an Ajax form that I need to hit a JavaScript function on failure, like so:
using (Ajax.BeginForm("UpdateStages", new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "refreshSearchResults('" + #Model.First().ItemCode + "')",
OnFailure = "showError"
}))
With the showError function taking the Ajax context response and appending it to a div, like so:
function showError(ajaxContext)
{
var response = ajaxContext.responseText;
response = $($.trim(response));
var itemVersion = response.filter("div")[0].innerHTML.trim().toString();
var error = response.filter("p")[0].outerHTML.toString();
$("#" + itemVersion.replace(".", "") + "-UpdateStagesResults").empty();
$(error).appendTo("#" + itemVersion.replace(".", "") + "-UpdateStagesResults");
}
In order for the OnFailure to be called I have in my MVC controller ActionResult, when an error occurs:
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return PartialView();
which returns a PartialView with the error message in the ViewBag. This works fine when running locally, the error message is sent to the showError function and then the error is appended to the page.
The problem is that when I put the application onto a live server (IIS7), the Ajax context is just
Bad Request
and for example is not:
<p>You have not entered a valid date.</p>
<div style="display:none;">V7.0 </div>
Any help would be great!

I've had this,
in IIS7 the default error settings are to show detailed error messages locally only., your view is replaced with the default for the status code.
If you want to see your custom errors, add this into your web.config
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
that should sort it

Related

Getting error Access was denied - ASP .NET. You don't have authorization to view this page.

I am doing a simple new view on a MVC ASP .NET
Here, I am doing the href:
$(document).on('click', '.viewFormacion', function () {
var id = $(this).data("id");
location.href = baseURL + "Farmacia/ModalPopUp/";
});
Farmacia is the controller and ModalPopUp is the method.
Inside FarmaciaController I have the method:
public ActionResult ModalPopUp(int id, int vid = 0)
{
return View();
}
I created also a new simple View Called ModalPopUp.
When I am going to Farmacia/ModalPopUp/ I received the error.
You don't have authorization to view this page.
HTTP ERROR 403
Can anyone help me?

How to show error in View if the Controller fails ? ASP.NET MVC

On the server-side I have a transaction which returns a JsonResult:
public JsonResult DoStuff(Guid id, string userInputText)
{
var product = _repository.Product(id); //busines logic
//Only a specific product must have userInputText <= 10 characters.
//Other products may have as many characters as the user wants.
if(product == Enum.SpecificProduct && userInputText.Count() > 10)
{
//The user input text comes from the View...
//If it has more then 10 characters, need to send the errorMessage to the View.
return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
}
//Otherwise, do stuff on the product...
//and return success at the end.
return Json(new { success = true });
}
On the other hand, on the client-side I have this:
using (Ajax.BeginForm("DoStuff", ajaxOptions))
{
<span>Enter the text:</span>
#Html.TextArea("userInputText", new { onkeyup = "SyncContents(); return false;" })
<input type="submit" value="Add" />
<!-- error message should be displayed here-->
}
This is the AjaxOptions:
var ajaxOptions= new AjaxOptions
{
OnSuccess = "reload",
OnFailure = "FailMessage"
};
If the entered text have more then 10 characters, when the "Add" button is pressed, the Controller is being executing the code on the server-side and fails, how can I get the errorMessage from there and use it here, in the View, to inform the user ?
I tried to alert a message:
<script>
function FailMessage() {
alert("Fail Post");
}
</script>
But no pop-up "Fail post" appears.
Best regards.
The problem here is the Ajax helper thinks all your responses are successful. Your controller action is returning HTTP 200 so there isn't a problem.
https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.onfailure(v=vs.118).aspx#P:System.Web.Mvc.Ajax.AjaxOptions.OnFailure
AjaxOptions.OnFailure Property
This function is called if the response status is not in the 200 range.
So you'll need to use the success handler and explicitly check the JSON success parameter.
Or have your action change the HttpStatusCode for the response.
if (notValid)
{
Response.StatusCode = 400; // Bad Request
return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
}
But for a validation error here I'd just check the for an error in the success handler.
And yes, you should validate on the client and on the server.

JavaScript, JSP and JSON not working with POST

I'm trying to make a client-server application where from the client I send a request through a JSON object to the server to register. The thing is I should get another JSON with an "OK" field (which is actually being sent) but for some reason the client keeps going to the .fail function instead of the .done one (sorry if some of used terms are not very accurate, I'm new to this).
So I'll this is my code incase you can check if there's anything wrong causing this:
Client JS:
define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'jquery', 'ojs/ojknockout', 'ojs/ojinputtext'],
function(oj, ko, $, app) {
function RegistrarseViewModel() {
var self = this;
this.email = ko.observable();
this.pwd1 = ko.observable();
this.pwd2 = ko.observable();
this.registrar = function(){
alert("Se ha mandado el registro");
var p = {tipo:"Registrarse",email: this.email(), pwd1:this.pwd1(), pwd2:this.pwd2()};
$.ajax({
type:"POST",
url:"http://localhost:8080/ServidorWeb/Registrarse.jsp",
data: "p=" + JSON.stringify(p)
}).done(function(data, textStatus, jqXHR){
alert("Comprobando tipo");
if (data.tipo == "OK"){
//window.location="index.html?root=juegos"
sessionStorage.jugador=self.email();
app.router.go("login");
alert("Registro correcto");
}else
alert(respuesta.texto)
}).fail(function() {
alert("Sorry. Server unavailable. lol ");
});
}
this.cancelar = function(){
app.router.go("login");
}
}
return new RegistrarseViewModel();
}
);
Server JSP:
<%# page language="java" contentType="application/json ; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import= "org.json.*,dominio.Manager"%>
<%
String p = request.getParameter("p");
JSONObject resultado=new JSONObject();
try{
JSONObject jso= new JSONObject(p);
if(!jso.getString("tipo").equals("Registrarse")){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje inesperado");
}else{
String email=jso.getString("email");
String pwd1=jso.getString("pwd1");
String pwd2=jso.getString("pwd2");
Manager.get().registrarse(email,pwd1,pwd2);
resultado.put("tipo","OK");
resultado.put("texto","Te has registrado con el email " + email);
}
}
catch(Exception e){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje Inesperadoo");
}
%>
<%=resultado.toString()%>
After executing Manager.get().registrarse(email,pwd1,pwd2); (which is the logic to register into a MongoDB) it just continues with the resultado.put("tipo","OK"); line which means the problem isn't in there.
Also if I send the request http://localhost:8080/ServidorWeb/Registrarse.jsp?p=%7Btipo:%22Registrarse%22,email:%2233%22,pwd1:%2220%22,pwd2:%2220%22%7D from a browser like Google Chrome it prints this: {"texto":"Te has registrado con el email 33","tipo":"OK"} but from the real client it just won't get into the .done function, idk why.
I really hope you can help me.
Thanks in advance.
EDIT 1: Added the server response from the browser console IMAGE
Okay I solved this finally.
I had to add this line at the beggining of the .jsp, this was an issu with TomCat which has something like 2 machines and without this line it doesn't allow communication among different machines because of security reasons it seems.
response.setHeader("Access-Control-Allow-Origin", "*");
if you use jquery the correct way is use serialize function from jquery
https://api.jquery.com/serialize/
first give a id for you form something like :
`
$("#myform form").submit(function(event){
event.preventDefault();
var sendData = $("#myform form").serialize();
$.post("your-PHP-handler.php", sendData);
});
<form id="myform" method="post" action="your-PHP-handler.php">
<input type="name" placeholder="name">
<input type="name" placeholder="age">
<input type="name" placeholder="address">
<button type="submit">send</button>
</form>
`
note when you submit your form via javascript the serialization jquery get all inputs in your post end send all together you cam handler the response php inside of $.post() you can make many things with this consulting jquery documentation.
anyway the basic is there , get everything inside my form and send to my php file

session timeout issue using ajax

I have 2 application one in struts and other one is in spring. From struts application I have one link which will call spring application controller through ajax call which returns model.
In struts application I have session timeout for 20 mins and while doing any transaction for the spring application which is rendered in the struts application the session timeout in struts application remains same and after 20 mins it is logging out.
struts application jsp page.
<body>
<div id="content"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
var sessionId = '<%= sessionId %>'
$.ajax({
type: "GET",
url: '/springapp/index.app?id='+sessionId,
data: "" ,
success: function(response){
$('#content').html(response);
},
error: function(e){
alert('Error: ' + e);
console.log(e)
}
});
});
</script>
Spring application controller.
#RequestMapping(value = "/*.app", method = {RequestMethod.GET, RequestMethod.POST})
public String jspController(ServletRequest req, ServletResponse res) throws exception {
LOGGER.debug("inside jspController() start");
HttpServletRequest request = (HttpServletRequest) req;
String model = request.getRequestURI();
if (model.endsWith("index.app")) {
String sessionKey = request.getParameter("employeeId");
SpringStrutsHandshake springStrutsHandshake = securityDelegate.getUserId(sessionKey);
User user = userDelegate.getUserByEmployeeId(springStrutsHandshake.getUserId());
user.setSessionKey(sessionKey);
request.setAttribute("USER", user);
model = "candidateList";
} else {
model = model.substring(model.lastIndexOf("/") + 1, model.lastIndexOf("."));
}
return model;
}
could you please help me how to fix timeout issue when there is any transaction in the rendered spring applicaiton page?
If you don't want the session timeout in struts application, why don't you just keep sending requests periodically(maybe every 15 mins) to the struts app which does nothing but just to keep the session from idling, until spring app calls back.
Or you can add a method to dynamically set the session timeout time like this
request.getSession.setMaxInactiveInterval(60*60); //in seconds

Call MVC action method by javascript but not using AJAX

I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>

Categories

Resources