JSON AJAX Post 403 forbidden error - javascript

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

Related

404 after processing request for ajax call in console

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]

AJAX POST to WEB Method not working for me

I coded up just like everybody else on the net but my WebMethod isn't getting hit from the post action. I believe my code is fine but I'll post my code just in case.
I put a breakpoint in the WebMethod, this is how I know it isn't being called.
Any help would be appreciated.
AXAJ
var div = document.getElementById(this.id);
var divid = div.getElementsByClassName("portlet-id");
varSQL="UPDATE [ToDoTrack] SET [Status] = '" + this.id + "' WHERE [ID] = '" + divid[0].innerHTML + "'";
var item = {};
item.status = this.id;
item.id = divid[0].innerHTML;
var Data = '{varSQL: ' + varSQL + ' }'
$.ajax({
type: "POST",
url: "ToDoTrack.aspx/UpdateDB",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
window.location.reload();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
Code Behind
[WebMethod]
[ScriptMethod]
public static void UpdateDB(string varSQL)
{
string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(varSQL))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
There is a problem the data object, it's a string not an object
Its not recommended to create the SQL on client side, it's a security flaw unless it's an application
//Problem is a string not object
var Data = '{varSQL: ' + varSQL + ' }'
//Solution below
var Data = {'varSQL': varSQL };
// Or this
var Data = 'varSQL='+varSQL;
The code seemed to work fine but if you have this issue in the future, these are the things I got from the internet that you seem to need for ajax post to work with WebMethods:
Ensure your URL in AJAX is correct
Ensure your json is well formed
Set <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">, my script manager was in my site.master
Set settings.AutoRedirectMode = RedirectMode.Off; in the App_Start>RouteConfig.cs file

Link not opening after streaming data of the document down

I think I am missing some code on the JavaScript side. I am downloading the documents for each request. When the user clicks on the link, I go get the document data and stream it down. I see on Fiddler that the data is coming down, but the .txt document link is not opening.
[HttpGet]
public HttpResponseMessage GetDataFiles(Int64 Id)
{
var results = context.PT_MVC_RequestFile.Where(x => x.RowId == Id).FirstOrDefault();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
if (results != null)
{
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(results.Data);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = results.FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = results.Data.Length;
}
}
catch (EntityException ex)
{
throw new EntityException("GetFiles Failed" + ex.Message);
}
return response;
}
Firstly, I downloaded all the documents for that request, and if the user clicks on the file, I call the download stream action.
$.ajax({
url: url,
type: 'GET',
// data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
if (data != "") {
$("#fileLength").val(data.length);
// alert(data.length);
$.each(data, function (i, item) {
var newDiv = $(document.createElement('div')).attr("id", 'file' + i);
newDiv.html("<input id=\"cb" + i + "\" type=\"checkbox\"> <a href=\"#\" onclick=\"GetData('" + item.RowId + "','" + item.mineType + "')\" >" + item.FileName + "</a>");
newDiv.appendTo("#fileRows");
});
} else {
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I think I am missing something after success though. Somehow it downloads the data, but the link does not open. Could it be the content type is not set, or that it thinks it is JSON data? Help with some ideas please.
Here is the link:
function GetData(rowId,mineType) {
// alert(mineType);
var url = "api/MyItemsApi/GetDataFiles/" + rowId;
$.ajax({
url: url,
type: 'GET',
//data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
You can't easily download a file through an Ajax request. I recommend to post the data to a blank page from a form, instead of the Ajax (you can populate that form and post it via jQuery if you need to). If you're interested, I could guide you through it, just let me know.
If you still want to download from Ajax, I suggest you refer to this post.

AJAX preloader/throbber getting

Below is an AJAX function I'm trying to use to show a loader gif during the request and hide when successful. Basically I started out with the function inside of the response.success which used to work by itself. It creates short urls and sets it to the value of an input field. And I was shown the rest that wraps that function, but i'm getting a 404 error in the console for failure to load resource. I'm sure this is a straightforward answer, I'm too new to tell but I think I'm close. Any help is much appreciated, thanks.
function getShare(url)
{
$('#loader').show(); // show loading...
$.ajax({
dataType: "jsonp",
jsonpCallback:'apiCallback', // this will be send to api as ?callback=apiCallback because this api do not want to work with default $ callback function name
url: 'http://b1t.co/Site/api/External/MakeUrlWithGet',
data: {'url':url},
success: function(response){
$('#loader').hide(); // hide loading...
//respponse = {success: true, url: "http://sdfsdfs", shortUrl: "http://b1t.co/qz"}
if(response.success){
{
var s = document.createElement('script');
var browserUrl = document.location.href;
//alert(browserUrl);
if (browserUrl.indexOf("?") != -1){
browserUrl = browserUrl.split("?");
browserUrl = browserUrl[0];
}
//alert(browserUrl);
var gifUrl = $('#gif_input').value;
var vidUrl = $('#vid_input').value;
//alert(gifUrl + "|" + vidUrl);
url = encodeURIComponent(browserUrl + "?gifVid=" + gifUrl + "|" + vidUrl);
//alert(encodeURIComponent("&"));
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
document.getElementsByTagName('head')[0].appendChild(s);
}
function resultsCallBack(data)
{
var obj = jQuery.parseJSON(JSON.stringify(data));
$("#input-url").val(obj.shortUrl);
}
}
},
error:function(){
$('#loader').hide();
}
});
}

getting an error Object doesn't support property or method 'setSrc' in web Resource in CRM 2011

I have used the WebResource on the Page and I am getting an error Object doesn't support property or method 'setSrc' in Javascript
Can you Please help me
My actual code is like this
function getImage()
{
var entityId = Xrm.Page.data.entity.getId();
var profilePictureElement = Xrm.Page.getControl("WebResource_ProfilePicture");
if (entityId) {
var oDataQuery = getServerUrl() + "/XRMServices/2011/OrganizationData.svc" +
"/AnnotationSet?$top=1&$select=AnnotationId,DocumentBody,MimeType&" +
"$orderby=ModifiedOn desc&$filter=ObjectId/Id eq guid'" + entityId +
"' and IsDocument eq true and Subject eq 'Profile Picture'" +
" and startswith(MimeType,'image/') ";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataQuery,
beforeSend: function (request) { request.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, request) {
if (data.d.results.length > 0) {
var mimeType = data.d.results[0].MimeType;
var body = data.d.results[0].DocumentBody;
// set src attribute of default profile picture web resource.
// here we use DataURI schema which has 32kb limit in IE8 and doesn't support IE <= 7.
profilePictureElement.setSrc("data:" + mimeType + ";base64," + body);
}
},
error: function (request, status, exception) { }
});
}
}
function getServerUrl()
{
var serverUrl = Xrm.Page.context.getServerUrl();
// trim trailing forward slash in url
return serverUrl.replace(/\/*$/, "");
}
you can refer the whole article from here http://blogs.msdn.com/b/crm/archive/2011/09/28/displaying-a-contact-s-facebook-picture-in-microsoft-dynamics-crm-2011.aspx?CommentPosted=true#commentmessage
Looks like that now the methods getSrc and setSrc can be used against a Web Resource only when refer to an HTML content.
If the Web Resource is an image, the crm will use an img tag to display the picture.
If you want to make that code working you need to retrieve the img element and assign the src property manually:
instead of
profilePictureElement.setSrc("data:" + mimeType + ";base64," + body);
you need to write
var profilePicture = document.getElementById("WebResource_ProfilePicture");
profilePicture.setAttribute("src","data:" + mimeType + ";base64," + body);
note: this is an unsupported customization

Categories

Resources