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
Related
I'm new to jquery and I can;t find an answer to my simple problem on the web.
I have
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Default.aspx/Getmessage",
data: "{'uid': '" + "XX" + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: OnFailure
});
});
function OnSuccess(data) {
$("#lblMessageReceived").html(data.uid + data.text);
}
function OnFailure() {
alert("Error");
}
Server side I have
Public Class clsResponseData
Public Property uid As String
Public Property text As String = "Hello"
End Class
<System.Web.Services.WebMethod()>
Public Shared Function getMessage(uid As String) As String
Dim rd As New clsResponseData
rd.uid = uid
Return JsonConvert.SerializeObject(rd)
End Function
When I run the code I get
"data" as Object {d: "{"uid":"XX","text":"Hello"}"}
and then
"data.d" as "{"uid":"XX","text":"Hello"}"
but then
"data.d.uid" returns undefined
so how do I reference the value of "uid" and "text"? .
I have tried this code with the Visuals Studio editor and Chrome browser insepction. What else do I need to add?
In case anyone looks for this, i cound the answer is to add an eval() function
function OnSuccess(data) {
eval('var t =' + data.d);
$("#lblMessageReceived").html(t.uid + t.text);
}
I have an aspx file that, on page load, is supposed to use ajax to call a webmethod from my code-behind file that gets data from a MySql database to display on the page. The problem is that when the page loads and the javascript function containing the ajax request is called, I get the following error:
Unknown web method PopulateUsersList.Parameter name: methodName
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unknown web method PopulateUsersList.Parameter name: methodName
Im not sure as to why this happens when I have other ajax requests that I use throughout the page and they all work just fine. Here is the code for the function containing the ajax request:
function loadUsersList(active) {
$.ajax({
type: 'POST',
url: 'ManagerPopup.aspx/PopulateUsersList',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ active: active }),
beforeSend: function () {
console.log('loading users list...');
},
success: function(result){
$('#userListDiv').empty();
$('#userListDiv').append(result.d);
$('#userListTable').DataTable({
"lengthChange": false,
"pageLength": 13,
"order": [[ 1, "asc" ]]
});
$('#userListTable tbody').on('click', 'tr', function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
var id = $.trim(tableData[0]);
var email = $.trim(tableData[2]);
var phone = $.trim(tableData[3]);
var active = $.trim(tableData[4]);
getUserSpecifics(id, email, phone, active);
})
},
error: function (ex) {
console.log('error loading user list');
console.log(ex.responseText);
}
});
}
And here is the webmethod that it is trying to reach:
[WebMethod]
public static string PopulateUsersList(bool active)
{
ArrayList userList = new ArrayList();
Query query = new Query();
StringBuilder userListHTML2 = new StringBuilder();
string userListHTML = "" +
"<table runat=\"server\" id=\"userListTable\" class=\"table table-striped table-bordered table-hover\">" +
"<thead>" +
"<tr>" +
"<th>User ID</th>" +
"<th>Name</th>" +
"<th>E-Mail</th>" +
"<th>Phone</th>" +
"<th>IsActive</th>" +
"</tr>" +
"</thead>" +
"<tbody>";
switch (active)
{
case true:
userList = query.GetUserList(true);
break;
case false:
userList = query.GetUserList(false);
break;
}
foreach (User user in userList)
{
userListHTML2.Append(string.Format(#"
<tr>
<td>{0}</td>
<td>{1}</td>
<td>{2}</td>
<td>{3}</td>
<td>{4}</td>
</tr>", user.userID, user.displayName, user.email, user.phone, user.isActive));
}
string userListHTML3 = "" +
"</tbody>" +
"</table>";
string finalHTML = userListHTML + userListHTML2 + userListHTML3;
return finalHTML;
}
NOTE: The HTML that is being returned from the WebMethod is making it to the page somehow even though it says that the method itself cannot be found.
I have already tried removing static from the WebMethod.
Any help would be greatly appreciated!
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
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")
I'm trying to pass a string from javascript to a razor ActionLink
string filtering =$("#Hello").val();
#Html.ActionLink(Name, ControllerName, new { sort = columm, order = orderby, filters = filtering })
but I'm not able to access to this variable, I already try #:filtering or "#filtering" but doesn't work anyway,
How can I pass the variable to the controller?
If you want to send or post the data to Controller's Action then you may try this...
<input type="submit" id="btnFilter" value="Filter" name="btnFilter" />
$('#btnFilter').click(function () {
var sort = sortValue;
var order = orderValue;
var filter= filterValue;
$.ajax({
type: 'POST',
url: '#Url.Action(ActionName, ControllerName)',
data:'{"sort":"' + sort+ '","order":"' + order+ '","filter":"' + filter+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function () {
}
});
});
then.... in controller action
public ActionResult ActionName(string sort ,string order , string filter)
{
// do Something here....
}
You'd have to add the parameter to the URL yourself manually using jQuery to assign the href attribute of the anchor tag.
First, let's take off the filter parameter off your ActionLink and give it an ID (so we can reference it in jQUery):
#Html.ActionLink(Name, Controller, new { sort = columm, order = orderby }, new { id = "myLink" })
Then do the following jQuery:
$(function () {
var newLink = $("#myLink").attr("href") + "?filter= " + $("#Hello").val();
$("#myLink").attr("href", newLink);
});
the way that I could do it was passing the Url to the controller
window.location = window.location.protocol + "//" + location.host + "/Name/Controller/" + "?sort=sort" + "&order=order" + "&page=page" + "&filters=" + filter;