I download a source code, and I tried it in Visual Studio 2013, and it didn't work, but it works when I use Visual Studio 2010, which I think there is a trick in ASP.Net 4.5 that I don't know about. Here is the code:
function Load(Skip, Take) {
$('#divPostsLoader').html('<img src="../ProgressBar/ajax-loader.gif">');
//send a query to server side to present new content
$.ajax({
type: "POST",
url: "/Grid/LoadImages",
data: "{ Skip:" + Skip + ", Take:" + Take + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
$('.thumb').append(data.d);
}
$('#divPostsLoader').empty();
}
})
};
And this is the Webmethod that never run:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string LoadImages(int Skip, int Take)
{
System.Threading.Thread.Sleep(2000);
StringBuilder GetImages = new StringBuilder();
string Imagespath = HttpContext.Current.Server.MapPath("~/Images/");
string SitePath = HttpContext.Current.Server.MapPath("~");
var Files = (from file in Directory.GetFiles(Imagespath) select new { image = file.Replace(SitePath, "") }).Skip(Skip).Take(Take);
foreach (var file in Files)
{
var imageSrc = file.image.Replace("\\","/").Substring(1); //Remove First '/' from image path
GetImages.AppendFormat("<a>");
GetImages.AppendFormat("<li>");
GetImages.AppendFormat(string.Format("<img src='{0}'/>", imageSrc));
GetImages.AppendFormat("</li>");
GetImages.AppendFormat("</a>");
}
return GetImages.ToString();
}
Any suggestion?
Thanks.
Have you tried stepping through your javascript? I bet you're getting a 500 error.
UPDATE
OP is getting 401 unauthorized when the AJAX request tries to call the WebMethod.
Once you allow authentication, you have to set AutoRedirectMode = RedirectMode.Off in your AppStart/RouteConfig.cs.
See more here
Related
I'm having trouble with calling a WebMethod with Jquery.
function runQuery(e) {
var search = $(e).val();
var csKind;
if ($('#rbLP').is(':checked'))
csKind = 1;
else
csKind = 0;
var params = {
url: 'addEditProduct.ascx/AutoComplete_Press',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(search),
dataType: 'json',
success: function(data) {
alert(1);
},
error: function(data) {
alert(2);
}
};
$.ajax(params);
}
[WebMethod]
public static void AutoComplete_Press(string searchClause, int csKind)
{
int searchType = 0; //ЕГН
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(searchClause))
searchType = 1;
string clients = laboratory.getClients2(searchType, searchClause, csKind);
}
How can I diagnose the problem, I've never used ajax before and I'm at a loss.
The problem I can see here is your passing arguments:
data: JSON.stringify(search),
you are missing csKind, maybe change this line to
data: "{searchClause: '" + search + "',csKind: '" + csKind + "'}",
And change your method to :
public static void AutoComplete_Press(string searchClause, string csKind)
The url seems to be wrong if you ask me. Open up your console in the browser and see what it says, it will be throwing cant connect/connection refused error. Also open network in the browser and you can check what http response you are getting. This will help u start up diagnosing the problem.
I am sending a complex string (which is a combination of the style attribute, ID and label text) from the script using $.ajax() . I went through a couple of questions on similar problems. But maybe I am not able to understand where am I getting it wrong.
This is the script I am using :
$(".btnSaveStyle").click(function (e) {
var comp1Style = "";
var comp2Style = "";
$(".box").children(".comp1").each(function () {
var style = $(this).attr('style');
var title = $(this).text();
var componentClass = $(this).attr('class');
comp1Style = comp1Style + style + "#" + componentClass + "#" + title + "$";
});
alert(comp1Style); //I get the style here
$.ajax({
type: "POST",
async: true,
url: 'AjaxRecieveStyle.aspx/GetStyle',
data: comp1Style
});
And in the C# I am accessing it in the following way :
[WebMethod]
protected void GetStyle(string style)
{
var recievedStyle = style;
Customer customer = (Customer)Session["existing_user"];
if (customer != null)
{
EventComponent eventComponent = new EventComponent();
string txtComp1 = recievedStyle;
string[] separateComponents = txtComp1.Split('$');
string[] individualComponent = new string[5];
foreach (string position in separateComponents)
{
individualComponent = position.Split('#');
if (individualComponent[0].Equals(""))
{
//do nothing
}
else
{
eventComponent.EventID = 1;
eventComponent.Image = "";
eventComponent.Style = individualComponent[0].ToString();
eventComponent.ComponentType = individualComponent[1].ToString();
eventComponent.Title = individualComponent[2].ToString();
int id = new EventComponentLogic().Insert(eventComponent);
}
}
}
}
Now :
1) : Should I use a JSON object to pass the data ?
OR
2) : Please show me what am i doing wrong in here ?
1) Yes it's better to send data using JSON - I mean, it'd be much easier to understand what's happening when anyone will look at that code in a year from now. And it's also much easier to extend the protocol based on JSON.
2) I suggest you to add logging at the very beginning of the GetStyle(string style) method. Then please try to get to it by explicitly typing the URL in your browser (or better using PostMan - see below for a link, PostMan will help you with testing POST requests as I see you have a POST request there) and ensure that the web-server code works.
And only if it works then please try your front-end AJAX request.
I suppose that you don't handle POST request correctly in your WebAPI. It will only handle GET requests. Please look at this SO question for details: Simple post to Web Api
3) Link to PostMan: https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
Did some digging and came up with this link: http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
The source code from the website shows that you may be missing some key features in your ajax call:
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
While this is (obviously) intended for their example you see that they set the following attributes that you do not
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
While the success and failure attributes are definitely optional I believe that setting your content type and datatype would really help you out here.
I changed my script to the following :
$.ajax({
type: "POST",
async: true,
url: 'AjaxRecieveStyle.aspx',
data: { style: comp1Style } //as I want to pass the parameter 'style' which is internally a JSON array.
});
I fetched the variable style in my C# in the following way (without using [WebServices]) :
I wrote a method GetStyle(string style) to get the data being sent from the ajax call.
Note: I did not call AjaxRecieveStyle/GetStyle from my script as the method is not accessible in my C# method . The data is actually received from the Page_Load method.
I access the variable sent from the script using Request.Params["style"].
My C# method is :
protected void Page_Load(object sender, EventArgs e)
{
GetStyle(Request.Params["style"]);
}
protected void GetStyle(string style)
{
var recievedStyle = style;
//do something on the recieved data!
}
This wil be an alternative to anyone who don't want to send JSON data actually !But sending data using JSON format will increase the readability of the code..
I post data to a aspx page via ajax, and now i don't know how to read it. I just need to take the strings that are passed via JSON and assign them to certain variables and manipulate the variables in the .aspx file. How do I do this?
Here is the jquery:
var ceSaveDatea = {};
ceSaveDatea.one = requestNumber;
ceSaveDatea.two = itemTypeID;
ceSaveDatea.three = servicesRequired;
ceSaveDatea.four = otherComments;
ceSaveDatea.five = suggestedReplacements;
ceSaveDatea.six = internalTestingRequired;
ceSaveDatea.seven = externalTestingRequired;
ceSaveDatea.eight = ceGeneralComments;
/*
var url = "../ajaxURLs/ComponentEngineering.aspx?requestNumber=" + requestNumber + "&itemTypeID=" + itemTypeID + "&servicesRequired=" + servicesRequired + "&otherComments=" + otherComments + "&suggestedReplacements=" + suggestedReplacements + "&internalTestingRequired=" + internalTestingRequired + "&externalTestingRequired=" + externalTestingRequired + "&ceGeneralComments=" + ceGeneralComments;
var encodedURL = EncodeURL(url);
*/
$.ajax({
type: "POST",
url: "/ajaxURLs/ComponentEngineering.aspx",
data: JSON.stringify(ceSaveDatea),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
alert(data);
if (data != '')
$('#checkboxContainerDiv').html(data);
},
error: function(msg) {
alert('error');
}
});
Then I just need to take this information and convert it on the ComponentEngineer.aspx page. It is not a web service.
Thanks!
If you want to handle JSON in your C# code, I strongly encourage you to go explore JSON.NET
The following code should do what you need:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Dictionary<object, object> jsonLookup = ((Dictionary<object, object>)serializer.Deserialize<Dictionary<object, object>>(jsonSource));
The 'jsonSource' passed into the Deserialize method is your JSON string.
Prerequisites are:
Include a reference to the .NET assembly: System.Web.Extensions
Include a using statement at top of your class file: using System.Web.Script.Serialization;
I am calling a WebMethod from jQuery doing the following:
function WebMethod(fn, paramArray, successFn, errorFn) {
var paramList = {};
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
paramList[paramArray[i]] = paramArray[i + 1];
}
}
var params = $.toJSON(paramList);
$.ajax({
type: 'POST',
url: '../../PricingEngine/ContractView.aspx' + '/' + fn,
contentType: 'application/json; charset=utf-8',
data: params,
dataType: 'json',
success: successFn,
error: function(xhr, status, error) {
// Display a generic error for now.
alert("AJAX Error!");
}
});
}
// Used returned object to populate every field
function updateTextFields(result) {
//do some processing here
}
function failed(result) {
alert('failed');
}
// EVENTS
// ------------------------------------------------------------
$(".editableField").keydown(function(e) {
WebMethod('PriceContract',
[
'AQ', aq.val(),
'SOQ', soq.val()
], updateTextFields, failed);
});
The JSON string after the .toJSON has been called:
{"AQ":"140000","SOQ":"1169"}
The C# method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static ContractsListPricing PriceContract(string AQ, string SOQ)
{
ContractsListPricing clp = new ContractsListPricing();
clp.Aq = 1;
clp.Soq = 2;
return clp;
}
This is returning the following error:
Invalid JSON: (Followed by the complete HTML of the current page).
Please take no notice of the logic in the C# as this isn't implemented yet. I am using the jquery-json plugin to parse the JSON.
Thanks
Ive run a demo of your code and got it working fine. Have you checked that you have the ScriptModule Handler set correctly in your web.config?
You're sure the exact url is '../../PricingEngine/ContractView.aspx' + '/' + fn ?
Because ContractView.aspx IS your current webpage
I have a webmethod which is trying to construct xml data document and return to clientside
but I am not able to guess whether the error is on clientside call or webservice return method. can anyone help to sortout this logic
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDataDocument GetList(string keyword1, string streetname, string lat, string lng, string radius)
{
XmlDataDocument xmlDoc= CreateXML( keyword1,streetname,lat,lng,radius);
//save file to application folder which will be refferd by client application
xmlDoc.Save(#"D:\blockseek7-9-2010\Block3.xml");
//xmlDoc.LoadXml(
return xmlDoc;
}
This is my call on clientside
var keyword2 = "{\"keyword1\":\"" + keyword1 + "\",\"streetname\":\"" + address1 + "\",\"lat\":\"" + lat + "\",\"lng\":\"" + lng + "\",\"radius\":\"" + radius + "\"}";
$.ajax({
type: "POST",
async: false,
url: "http://localhost:2330/blockseek7-9-2010/JsonWebService.asmx/GetList",
data: keyword2,
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: ajaxCallFailed,
success: ajaxCallSucceed
});
});
This is the function for the ajaxCallSucceed
function ajaxCallSucceed(response) {
//alert("hi");
GDownloadUrl(response.xml, function(data) {
var xml = GXml.parse(response.xml);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
alert(markers.length);
..........
............
..........................
..................................
Use tool such as Fiddler or FireBug add-on for FireFox - this will allow you to inspect each request/response. By looking at response to your web service call, you will know the xml returned. That will help you in determining whether the issue is on server side or on client side.