404 after processing request for ajax call in console - javascript

I 'm giving an ajax call GET Request to a controller and and the method is getting processed but after completion of execution.it is showing 404 error code in the console of web page.
please find the below code for ajax call
jQuery(document).ready(function() {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: "application/json",
url: "${home}getOPList",
cache: false,
success: function(response) {
// var str = JSON.stringify(response);
var operatorList;
// alert("yes");
// alert(str);
for (var i = 0; i < response.length; i++) {
console.log(response[i].listOfOperators);
operatorList += "<option value =' " +
response[i].sno +
" '>" +
response[i].listOfOperators +
"</option>"
}
$('#opList').html(operatorList);
},
error: function() {
alert('Error while request..');
}
});
$("#opList").change(function() {
var abc = document.getElementById('opList').value;
alert("we got :: " + abc);
$.ajax({
type: 'GET',
dataType: 'json',
contentType: "application/json",
url: "${home}partnerDetails?operator=" + abc,
data: {
operator: abc
},
cache: false,
success: function(response) {
// var str = JSON.stringify(response);
var partnerList;
alert("yes");
alert("oplist " + abc);
for (var i = 0; i < response.length; i++) {
console.log(response[i].campaignName);
partnerList += "<option value =' " +
response[i].sno +
" '>" +
response[i].campaignName +
"</option>"
}
$('#ptList').html(partnerList);
},
error: function() {
alert('Error while request in partners..');
}
});
});
});
and please find the controller code
#Controller
public class PartnerController {
Logger logger = Logger.getLogger(PartnerController.class.getName());
#Autowired
public UserService userService;
#Autowired
public Gson gson;
public Gson getGson() {
return gson;
}
public void setGson(Gson gson) {
this.gson = gson;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(value ="/partnerDetails" , method=RequestMethod.GET)
public String getPartnerList(String operator){
logger.info(" \t OP IN REQUEST :: "+operator);
String partnerList = "";
try{
ArrayList<PartnersList> arrayList =
(ArrayList<PartnersList>)userService.getPartnersListFromDB();
logger.info(" \t PARTNERS LIST BEFORE CONVERSION :: "+arrayList);
partnerList = gson.toJson(arrayList);
logger.info(" \t PARTNERS LIST :: "+partnerList);
}catch(Exception e){
e.printStackTrace();
}
return partnerList;
}
}
i'm able to print the last logger and return statement and the code is getting excuted but some how i'm not able to get the alert popup on web page and the last alert was that "we got " one and then the code is getting processed in controller method and getting 404 in the console like below please help me on this.
GET XHR http://localhost/Promotions/partnerDetails [HTTP/1.1 404 Not Found 40ms]

Related

How can i check User Role in javascript (without razor or controller)

I'm trying to use User.IsInRole() with javascript like on the razor page. I don't want use Controller, if this can be done, How can i do this in MVC5?
Edit: I want to display button by user role. I can do this with the razor page. There are fields in javascript where I add elements to the table, I will try to use them here.
You can do like below as shown below in for price
#{var price=20;}
<html>
<body>
#if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
try like this:
//Check login User has 'System Administrator' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "System Administrator") {
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
https://msdynamicscrmblog.wordpress.com/2013/03/10/get-login-user-role-names-in-javascript-in-dynamics-crm-2011/

How can I pass jquery variable as parameter to Java controller by href?

This is my variable in javascript:
var dataid = dataInfo[i];
I want to pass the variable to my java controller through href:
row = row + "<tr><td>" + dataid + "</td><td>" +
schoolid + "</td><td>" +
"<td><a class='details' id='" + dataid + "' href='#{DataManagement.dataDetails(dataId)}'>Details</a></td>"+
"<td>"+
</tr>";
but controller gets null value.
I am trying this using ajax:
$.ajax({
type: "GET",
url: "#{DataManagement.dataDetails}",
data: {
id: dataId
},
success: function(data) {
console.log(data);
}
});
This is my controller:
public static void dataDetails(Long id) throws SQLException {
Logger.info("id: "+ id);
//dataId=dataId.trim();
//Long iid = Long.parseLong(dataId);
Data data = Data.findById(id);
String totalStudent = Data.getTotalStudent(1L);
Logger.info("totalStudent: " + totalStudent);
renderArgs.put("totalStudent",totalStudent);
render(data,totalStudent);
}
But after ajax call it is not render the new page.
How can I do this?
It works!!!
I changed it to :
<td><a class='details' id='" + dataid + "' href='/datamanagement/dataDetails/"+dataid+"'>Details</a></td>
You can send a json request with ajax and accept it on Controller.
Ajax Request:
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify(yourObject),
url: "/path",
success: function (msg) {
console.log(msg);
window.location = "/redirectTo";
},
error : function(e) {
console.log('Error: ' + e);
}
});
On Controller:
#ResponseBody
#CrossOrigin #RequestMapping(value = "/path", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
private ResponseEntity<YourObject> someMethod(#RequestBody YourObject obj){
// do your coding here
return new ResponseEntity<YourObject>(modifiedObject, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<YourObject>(HttpStatus.BAD_REQUEST);
}
}

JSON AJAX Post 403 forbidden error

Hi I just started learning Spring, AJAX, JSON. I have been getting an error when i try to post a message back.
messages.jsp
function success(data) {
$("#form" + data.target).toggle();
$("#alert" + data.target).text("Message sent.")
startTimer();
}
function error(data) {
alert("Error sending message");
}
function sendMessage(i, name, email){
var text = $("#textbox" + i).val();
$.ajax({
type: "POST",
url: '<c:url value="/sendmessage" />',
data: JSON.stringify({"target": i, "text": text, "name": name, "email": email}),
success: success,
error: error,
contentType: "application/json",
dataType: "json"
});
}
function showMessages(data){
$("div#messages").html("");
for(var i=0; i<data.messages.length; i++) {
var message = data.messages[i];
var messageDiv = document.createElement("div");
messageDiv.setAttribute("class", "message");
var subjectSpan = document.createElement("span");
subjectSpan.setAttribute("class", "subject");
subjectSpan.appendChild(document.createTextNode(message.subject));
var contentSpan = document.createElement("span");
contentSpan.setAttribute("class", "contentText");
contentSpan.appendChild(document.createTextNode(message.content));
var nameSpan = document.createElement("span");
nameSpan.setAttribute("class", "nameSpan");
nameSpan.appendChild(document.createTextNode("From: "+ message.name + '('));
var link = document.createElement("a");
link.setAttribute("class", "replylink");
link.setAttribute("href", "#");
link.setAttribute("onClick", "showReply(" + i + ")");
link.appendChild(document.createTextNode(message.email));
nameSpan.appendChild(link);
nameSpan.appendChild(document.createTextNode(")"));
var alertSpan = document.createElement("span");
alertSpan.setAttribute("class", "alert");
alertSpan.setAttribute("id", "alert" + i);
var replyForm = document.createElement("form");
replyForm.setAttribute("class", "replyForm");
replyForm.setAttribute("id", "form" + i);
var textarea = document.createElement("textarea");
textarea.setAttribute("class", "replyArea");
textarea.setAttribute("id", "textbox" + i);
var replyButton = document.createElement("input");
replyButton.setAttribute("class", "replyButton");
replyButton.setAttribute("type", "button");
replyButton.setAttribute("value", "reply");
replyButton.onclick = function(j, name, email) {
return function() {
sendMessage(j, name, email);
}
}(i, message.name, message.email);
replyForm.appendChild(textarea);
replyForm.appendChild(replyButton);
messageDiv.appendChild(subjectSpan);
messageDiv.appendChild(contentSpan);
messageDiv.appendChild(nameSpan);
messageDiv.appendChild(alertSpan);
messageDiv.appendChild(replyForm);
$("div#messages").append(messageDiv);
}
}
controller.java
#RequestMapping(value="/sendmessage", method=RequestMethod.POST, produces="application/json")
#ResponseBody
public Map<String, Object> sendMessages(Principal principal, #RequestBody Map<String, Object> data){
String text = (String)data.get("text");
String name = (String)data.get("name");
String email = (String)data.get("email");
Integer target = (Integer)data.get("target");
System.out.println(name + " , " + email + " , " + text);
Map<String, Object> returnVal = new HashMap<String, Object>();
returnVal.put("success", true);
returnVal.put("target", target);
return returnVal;
}
I have tried many different things to solve this problem but nothing is working, I can't post the message.
Any help or reason why I keep getting this error?
jquery.js:4 POST http://localhost:8080/spring/sendmessage 403
(Forbidden) send # jquery.js:4 ajax # jquery.js:4 sendMessage #
messagesView:32 (anonymous function) # messagesView:90
Screenshot
I had the same problem, you need to add the CSRF headers into the AJAX POST request. Take a look at Cross Site Request Forgery. I'm not at my development system at the moment so can't post an example, but using the info from this page worked for me.
step-1:
put a id to the form --->
<form id='formid' ....>
step-2:
pass the form as serialize form --->
$.ajax({
type: "POST",
url: '<c:url value="/sendmessage" />',
data: ('#formid').serialize(),
success: success,
error: error,
contentType: "application/json",
dataType: "json"
});

ASP.NET execute WebMethod with Jquery/AJAX

I have one WebMethod that will execute some DB search and return it's data in some HTML template. I need to execute this method using jquery to populate an area of the website but the problem is that my website URL/URI is dynamic.
My URL is http://site/school-name/home. The school-name will always change to indicate wich school i'm accessing.
I have accomplished so far:
$.ajax({
type: "POST",
url: "/Default.aspx/BuscaEquipe",
data: { 'pIndex': pIndex, 'pLimite': 4, 'pUnidadeCE': codigoEmitente },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
failure: function(response) {
alert(response.d);
}
});
and the WebMethod:
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
var objEquipe = new Equipe { EquipeUnidadeCE = pUnidadeCE, EquipeAtivo = 1 };
var CaminhoImagem = Configuracoes.CaminhoVirtual + "Controles/Redimensiona.ashx?img=" + Configuracoes.CaminhoVirtual + "images/equipe/" + pUnidadeCE + "/";
if (!objEquipe.Listar(objEquipe)) return "";
var depoimentos = objEquipe.lstEquipe.Skip(pIndex).Take(pLimite);
var objJson = new JavaScriptSerializer().Serialize(depoimentos.Aggregate("", (current, equipe) =>
current + ("<div class='col-lg-3 col-md-3 col-sm-3'><img src='" + CaminhoImagem + equipe.EquipeImagem + "&w=400&h=400' alt='" + equipe.EquipeNome + "' class='img-circle img_perfil'><div class='nome_perfil text-center'>" + equipe.EquipeNome + "</div></div>")));
return objJson;
}
Using like this i get a 401 Not Authorized and if i try to use my full URL http://site/school-name/Default.aspx/BuscaEquipe i get a 404.
P.S. I have already used this same method in another project and it worked fine but i can't figure out what's wrong in this one, i think it might be related to the URl but i'm not sure.
the problem is with your URL
Use the ResolveClientUrl() method
<%= ResolveUrl("~/Default.aspx/BuscaEquipe") %>
And you must Have [WebMethod] attribute before your static server function
[WebMethod]
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
//Code
}
Your data:
var requestData= JSON.stringify({
pIndex: pIndex,
pLimite: 4,
pUnidadeCE: codigoEmitente
})
and then
data:requestData

Not getting data value from [object XMLDocument] after success Ajax

I have created a javascript and a WebMethod. It works in IE but not in firefox and chrome
MyWebMethod
[WebMethod]
public string Send(string name, string email, string message)
{
try
{
MailMessage objMailMessage = default(MailMessage);
objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress(email, name,System.Text.Encoding.UTF8);
objMailMessage.To.Add("feedback#abc.in");
objMailMessage.Subject = "Feedback";
objMailMessage.Body = "<b>Name :</b> " + name + "<br/><br/>";
objMailMessage.Body += "<b>Email :</b> " + email + "<br/><br/>";
objMailMessage.Body+= "<b>Message :</b> "+message;
objMailMessage.IsBodyHtml = true;
objMailMessage.Priority = MailPriority.High;
CommonFunctions.CommonFunctions.SendEmailMessage(objMailMessage);
return "success";
}
catch (Exception ex)
{
Logger.Log.Error(ex);
return "Fail";
}
}
MYScript
$.ajax({
datatype: 'text',
type: 'POST',
url: options.url,
data: { name: $(this_id_prefix + '#name').val(), email: $(this_id_prefix + '#email').val(), message: $(this_id_prefix + '#message').val() },
success: function (data) {
$(this_id_prefix + '#loading').css({ display: 'none' });
var xmlDoc = data;
var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue;
if (returnvalue == "success") {
$(this_id_prefix+'#callback').show().append(options.recievedMsg);
setTimeout(function () {
$(this_id_prefix + '.holder').show();
$(this_id_prefix + '#callback').hide().html('');
}, 2000);
if(options.hideOnSubmit == true) {
//hide the tab after successful submition if requested
$(this_id_prefix+'#contactForm').animate({dummy:1}, 2000).animate({"marginLeft": "-=450px"}, "slow");
$(this_id_prefix+'div#contactable_inner').animate({dummy:1}, 2000).animate({"marginLeft": "-=447px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");
$(this_id_prefix+'#overlay').css({display: 'none'});
}
} else {
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
setTimeout(function(){
$(this_id_prefix+'.holder').show();
$(this_id_prefix+'#callback').hide().html('');
},2000);
}
},
error:function(){
$(this_id_prefix+'#loading').css({display:'none'});
$(this_id_prefix+'#callback').show().append(options.notRecievedMsg);
}
});
I am not able to get return value from webmethod to script. In Success funcation I want to check that if(data=="Success") but here I am not able to check that. Is there anything wrong in script like datatype or any other issue? Here var returnvalue = xmlDoc.childNodes(1).firstChild.nodeValue; is not working. It works locally fine but after publish to server it's not working. It return object xmldocument in data. It's not returing string. I have changed datatype to text

Categories

Resources