No response from POST request Spring boot - AJAX - 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>

Related

Ajax with Spring boot

Sorry for asking this question as a new Question. I changed the code as instructed. but still it's not working. Please help me to solve this coding. Thanks !
<div class="label_left_2">
<label class="outputdataField2_Short">Product No</label>
</div>
<div class="input_left_2">
<input list="dropdownproduct" placeholder="Start typing..."
class="inputDataField_Select2_Short" id="dropProduct"
th:field="*{product_id}">
</div>
<datalist id="dropdownproduct">
<option value="0">select product Code</option>
<option th:each="product1 : ${listProducts}"
th:value="${product1.item_Code}" th:text="${product1.name}" />
</datalist>
Ajax Code
$( "#dropProduct" ).select(function() {
// alert( "Handler for .select() called." );
var productId= $( "#dropProduct" ).val();
// alert(' productId'+ productId);
$ajax({
url :'/findProduct2',
**data:{ "productid" : productId },**
dataType:'json',
contentType:'application/json',
success: function(result){
$(discount_Amount).html(result.discount);
}
//}
});
});
Spring Controller Code:-
#RequestMapping("/findProduct2")
ResponseEntity<Product> showProduct2(HttpServletRequest req, Model model) {
System.out.println(" in method.... ");
**String productId = req.getParameter("productId");**
ResponseEntity<Product> responseEntity = new ResponseEntity<Product>(productService.get(productId),
HttpStatus.OK);
return responseEntity;
}
It's probably because you forgot to specify the HTTP method both in the Ajax and Spring controller. I am assuming it's a GET request.
try this for the Ajax
$( "#dropProduct" ).select(function() {
// alert( "Handler for .select() called." );
var productId= $( "#dropProduct" ).val();
// alert(' productId'+ productId);
$ajax({
url :'/findProduct2',
**data:{ "productid" : productId },**
dataType:'json',
type: "GET",
contentType:'application/json',
success: function(result){
$(discount_Amount).html(result.discount);
}
//}
});
});
And this for the Controller
#RequestMapping("/findProduct2", method = RequestMethod.GET)
ResponseEntity<Product> showProduct2(HttpServletRequest req, Model model) {
System.out.println(" in method.... ");
**String productId = req.getParameter("productId");**
ResponseEntity<Product> responseEntity = new ResponseEntity<Product>(productService.get(productId),
HttpStatus.OK);
return responseEntity;
}

Ajax call not working in foreach loop in MVC

I'm dynamically adding data to the database using AJAX and displaying them using foreach loop in MVC, I have also added a button to remove the those data using ajax call.
HTML/MVC code:
<div id="divaddrules" class="form-group row">
#try
{
foreach (var item in ViewBag.AdditionalRules)
{
<div class="col-sm-10">
<p style="font-size:large">#item.AdditionalDesc</p>
</div>
<div class="col-sm-2">
<input type="button" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
</div>
}
}
catch (Exception ex){ }
</div>
Now when I click on Remove button it call the following JS code:
function Removeinput(id) {
var datas = {};
datas.addId = id
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: datas,
success: function (result) {
alert(result.id);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
and its passing to this controller:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
I'm getting 500 error on ajax call error.
Can anyone tell me where I'm doing it wrong? Please.. I'm stuck here.
Update:
Attached screenshot: Debug Screenshot
Write your Removeinput function as follows:
function Removeinput(id) {
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: { addId : id},
success: function (response) {
alert(response);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
Then in the controller method:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
AdditionalRules rules = db.AdditionalRules.Find(addId); // Here was the problem. He was pointing to the wrong table that has fixed over team viewer.
db.AdditionalRules.Remove(rules);
db.SaveChanges();
return Json(addId,JsonRequestBehavior.AllowGet);
}
the problem it is missing values on db, in the image you ask to id 25 but return null and you try to remove a item passing null value.
so in your case you need to validate before remove or fix the missing data:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
If(rules == null)
{
//return error msg.
return Json(JsonRequestBehavior.AllowGet);
}
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
make your input type submit, may this was helpful
function deleterelation(id) {
debugger;
if (id > 0)
$.ajax({
url: "/Relations/Delete/" + id,
type: "get",
datatype: "json",
data: { id: id },
success: function (response) {
debugger;
if (response != null) {
$("#txtDName").text(response.name);
$("#DRelationId").val(response.id);
$("#DeleteRelation").modal("show");
}
},
error: function (response) {
$("#DeleteRelationLoading").hide();
$("#DeleteRelation_btn_cancel").show();
$("#DeleteRelation_btn_save").show();
}
});
else
toastr.error("Something went wrong");
}
<input type="submit" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
if this not work plz let me know

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);
});
}

Ajax doesn't call method in production

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.

How can I Authenticate with ServiceStack using jQuery Ajax

I'm trying to do something like the following:
jQuery Part:
function ajaxLogin() {
$.ajax({
url: "auth/credentials",
type: "POST",
data: { UserName: $("#form_username").val(), Password: $("#form_pwd").val() },
success: function (data) {
$("#login_div").hide();
},
error: function (jqXHR,textStatus,errorThrown) {
$("$login_msg").text(errorThrown);
}
});
}
However, for some reason it's always coming back to the success function and data contains the html contents of the current html document.
My ServiceStack AuthProvider contains the following TryAuthenticate:
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var session = authService.GetSession();
string error = null;
try
{
var dataSource = authService.TryResolve<RiskViewDataSource>();
var diModelInstance = dataSource.diModelRootObject;
string authResult = UserFactory.authenticate(session.Id, userName, password, false);
if ("OK".Equals(authResult))
{
session.IsAuthenticated = true;
session.UserName = session.DisplayName = userName;
session.UserAuthId = password;
UsersManager.generateUsersPolicies();
UsersManager.loadUserPolicies();
return true;
}
else
{
session.IsAuthenticated = false;
session.UserName = session.DisplayName = null;
session.UserAuthId = null;
authService.RemoveSession();
return false;
}
}
catch (Exception e)
{
Log.Error(e.ToString());
session.IsAuthenticated = false;
session.UserName = session.DisplayName = null;
session.UserAuthId = null;
error = "Could not connect to RiskView database";
}
if (error != null)
{
throw HttpError.Unauthorized(error);
}
else
{
return false;
}
}
Ok, after a day of messing about I've come up with this solution which works for me. I had to create a new service request for logging in. I called it RenewSession.
Service Stack Part:
[Route("/RenewSession", "POST")]
public class RenewSessionRequest : IReturn<RenewSessionResponse>
{
}
public class RenewSessionResponse : IHasResponseStatus
{
public RiskViewJsonObject Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class RenewSessionService : Service, IPost<RenewSessionRequest>
{
public object Post(RenewSessionRequest request)
{
string username = this.Request.GetParam("UserName");
string password = this.Request.GetParam("Password");
string message = "";
IAuthProvider authService = AuthService.GetAuthProvider("credentials");
Boolean success = false;
try
{
var response = authService.Authenticate(this, this.GetSession(), new Auth { UserName = username, Continue = null, Password = password });
success = true;
}
catch (Exception e)
{
message = e.ToResponseStatus().Message;
}
return new RenewSessionResponse { Result = new Mapping.RiskViewJsonObject("{ \"success\" : " + (success ? "true" : "false") + ", \"message\" : \"" + RiskViewJsonObject.cleanForJSON(message)+ "\" }") };
}
}
Html and Ajax Part:
1) Add a div to the page for the login details (Hide it to start with)
<div id="login-div" style="position:absolute;display:hidden;left:100;top:100;background-image:url('images/login_bk.png');">
<p id="login_error_msg"></p>
<form id="login_form" onsubmit="loginSubmit(); return false;">
<table>
<tr>
<td>Username:<input id="in_un" type="text" name="UserName" autocomplete="off" autocorrect="off" autocapitalize="off"/></td>
</tr>
<tr>
<td>Password:<input id="in_pw" type="password" name="Password" autocomplete="off" autocorrect="off" autocapitalize="off"/></td>
</tr>
<tr>
<td style="text-align: center;">
<input id="login_submit" type="submit" class="hand_cursor" value="Login">
</td>
</tr>
</table>
</form>
</div>
2) I add 401 checks to every ajax query on my page (401 tells us that the session has expired)
$.getJSON('/Menus?format=json', function(data) {
// Do some stuff
}).fail(function (jqxhr,textStatus,error) {
if (jqxhr.status == 401) {
loginAgain();
}
});
3) Show the div to re-login
function loginAgain(reloadMenu) {
$("#login-div").show("slow");
}
4) The onclick for login button or onsubmit event for the login form
function loginSubmit() {
if ($("#in_un").val().trim() == "" || $("#in_pw").val().trim() == "") {
$("#login_error_msg").text("Username or Password is still empty.");
return false; // Prevent form from submitting
} else {
$("#login_submit_btn").attr("disabled","disabled");
$("#login_error_msg").text("");
$.ajax({
url: "/RenewSession?format=json",
type: "POST",
data: { UserName: $("#in_un").val(), Password: $("#in_pw").val() },
success: function (data, textStatus, jqXHR) {
$("#login_submit_btn").removeAttr("disabled");
if (data.Result.success) {
$("#login-div").hide();
} else {
if (data.Result.message) {
$("#login_error_msg").text(data.Result.message);
} else {
$("#login_error_msg").text(textStatus);
}
$("#in_pw").focus();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$("#login_submit_btn").removeAttr("disabled");
$("#login_error_msg").text("ERROR: "+errorThrown);
$("#in_pw").focus();
}
});
}
return false; // Stop the form submiting, we're just gonna hide the div
}

Resources