AJAX POST to WEB Method not working for me - javascript

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

Related

How decode html content bound in json?

I am using asp.net application and using ajax call,below is my code.Below is my web method which is working fine and give response of ajax call.
ADController adc = new ADController();
DataTable dt = adc.GetGeneral(Convert.ToInt32( AnnouncementId));// GetAnnouncementsByIDAndRead(Convert.ToInt32(AnnouncementId), Convert.ToInt32(userid));
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in dt.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
if (col.ColumnName == "description")
{
childRow.Add(col.ColumnName, HttpUtility.HtmlDecode( Convert.ToString( row[col]) )as object);
}
else
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
following is my ajax code ,which is working fine and giving data on call fine.
function fnshowAncDetails(AnnouncementId, userid) {
$(".loading").show();
var url = $("[id$='hdURLt']").val();
$("[id$='btnSaveMD']").show();
$.ajax({
type: "POST",
url: url + "/GetInfo.aspx/General",
data: '{AnnouncementId:"' + AnnouncementId + '",userid:"' + userid + '"}',
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: OnSuccessSetCGiven,
error: function (response) {
}
});
var vtext = $("[id$='lblAnnoucement']").text();
if (vtext != 0) {
vtext = vtext - 1;
}
$("[id$='lblAnnoucement']").text(vtext);
}
below is my success method
function OnSuccessSetCGiven(response) {
var parsed = $.parseJSON(response.d);
$("[id$='htititlen']").text(parsed[0].Title);
$("[id$='divNotifBody']").text(parsed[0].Description);
$("[id$='divadded']").text("By:"+parsed[0].FirstName + " " + parsed[0].LastName);
$("#divNotifdetails").modal('show');
$(".modal-backdrop").css('z-index', '0');
$(".loading").hide();
var formattedTime = parsed[0].stime.Hours + ":" + parsed[0].stime.Minutes;
//$("[id$='divtime']").text(formattedTime);
$("[id$='divdate']").text("Time:" +parsed[0].startdate + " " + formattedTime);
}
Now my question is in The Description there may be html tags, means formatted htmls,like <p>xxx</p><b>sdf</b>. So it not loaded as bold,
how can I render formatted html?
Use jQuery .html function and not .text:
function OnSuccessSetCGiven(response) {
...
$("[id$='divNotifBody']").html(parsed[0].Description);
...
}
But note that you will have JS injection vulnerability, so you must clean the HTML code in the description field and remove unwanted attributes & tags (for example: <script>, <any onclick=""> etc.)
Update:
By the way, I am not familiar with this selection syntax:
$("[id$='divNotifBody']")
Assuming that you want to select a div with the id "divNotifBody", Why not just use:
$("#divNotifBody")

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

How to update SharePoint 2010 Column with SharePoint Username via OnClick?

Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");

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.

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

Categories

Resources