I am playing with C# and jQuery (Ajax). In a effort to keep the C# code as short and clean as possible when creating a Ajax request, without using the Encosia example (in short without ASP.NET for the Ajax calls). The response can be XML, JSON or plain (parts) HTML.
I got a working version, but is this preferable to do? Or should I consider a other method?
I do get 1 warning (for the ajax.aspx page) in VS2010 express (a search of this error doens't gives me a satisfied answer)
Warning
Validation (): Element 'html' occurs too few times.
default.aspx
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id="Result"></div>
<script type="text/javascript" language="javascript">
$(function () {
$.ajax({
url: "AJAX.aspx",
success: function (data) { $("#Result").html(data); }
});
});
</script>
</asp:Content>
ajax.aspx (there is only this line on this page)
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="AJAX.aspx.cs" Inherits="AJAX" %>
ajax.aspx.cs
using System;
using System.Text;
using System.Data;
public partial class AJAX : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.Write("Hello world");
Response.End();
}
}
well it's like the error says: you have to have <html> tags to have a valid html document. Since your page doesn't seem to use a master page, there's probably no html tags being rendered. There's short and concise and then there's too short.
One thing I think you should add to your code is in relation to the jQuery ajax call.
You have not explicitly specified all of the settings. I use the following to set up my default values for all of my ajax calls, which can be overridden at any stage by an individual ajax call:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
error: function (XMLHttpRequest, textStatus, errorThrown) {
utilities.ajaxErrorAlert(XMLHttpRequest, textStatus, errorThrown);
}
});
Related
I want to get access to a method in code behind when I clicked an span in my view aspx:
DEFAULT.ASPX VIEW CODE:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<%-- MY SPAN --%>
<span runat="server" onclick="ShowChartSpider(this.id)" id="group_2" style="cursor: pointer" class="pull-right">My Span</span>
<%-- JAVASCRIPT CODE --%>
<script type="text/javascript">
function ShowChartSpider(group_id) {
$.ajax({
type: "POST",
url: "Default.aspx/MethodToCreateChart",
dataType: "json",
data: "{'parameter1':" + JSON.stringify(group_id) + "}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("all correct");
},
error: function (data) {
alert("no");
}
}
);
}
</script>
</asp:Content>
DEFAULT.ASPX.VB CODE BEHIND:
<WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Sub MethodToCreateChart(sender As Object, e As EventArgs)
' My code to create the chart .....
End Sub
if I run the page, and inspects the page with the browser to see errors, none appear, but the code does not reach the breakpoint that I put in the method in codebehind.
What I´m doing wrong?
I would appreciate suggestions, thanks.
First check your server allow non HTTPS request.
i had that type of issue and my server didn't allow me to do that.
it so then disable that and test.
Then check the response status.
error: function(xhr, status) {
alert(xhr.status); }
let us know that is the outcome.
--Ruhul
Go to "RouteConfig.vb" under "App_Start" folder.
Change following line
settings.AutoRedirectMode = RedirectMode.Permanent
To
settings.AutoRedirectMode = RedirectMode.Off
i think your method code returning something like this.
Return Default.aspx/MethodToCreateChart
so me your MethodToCreateChart logic.
you can try with below sample method. your internal server error are coming because you are returning somethng from your method.
Public Shared Function MethodToCreateChart(parameter1 As String) As String
Return "Hello " & Environment.NewLine & "The Current Time is: " & _DateTime.Now.ToString()
End Function
I think you should remove 'runat=server' attribute from span tag.
You use aspx file same as ashx files. So have a look at below links:
1. How do you debug ASP.net HTTPHandler
2. Can't debug ASHX handler
I am calling .asmx service from inside script tag in aspx page. When I view the page source it's showing my webservice.
How to protect the webservice from expose?
cause when some one view the page source then he can see the web service name as well as its all methods name.
.aspx Page:
<asp:PlaceHolder ID="divBody" runat="server">
<div class="aa-dashboard-wrapper">
<asp:Textbox id="textbox1" runat="server"></asp:Textbox>
</div>
</asp:PlaceHolder>
Here is my script tag, that is placed at the bottom of my aspx page.
$("#textbox1").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebService.asmx/webServiceMethod") %>',
data: "{ 'keyword': '" + request.term + "'}",
dataType: "json",
timeout: 20000,
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (response) {
},
failure: function (response) {
}
});
},
select: function (e, i) {
},
minLength: 2
})
</script>
While you can't stop users from seeing the URL of your service, you can stop them viewing the documentation for it - just put this inside the system.web tag of your web.config
<webServices>
<protocols>
<remove name="Documentation" />
</protocols>
</webServices>
See https://support.microsoft.com/en-us/kb/815149 on 'Removing the Documentation Protocol'
The best way is to have a JS file and place your AJAX call there. Even in this case, user can browse and view the JS, but the chances are little less.
There is no way to completely hide your API endpoints from someone who wants to find it. Even if you somehow obfuscate the calling of it in some javascript construction, it will still be visible in Chrome web inspector. And at the most basic level, I can still see it when I intercept the communication with packet sniffers.
This is the Ajax code to be used with my chat application.
I have successfully completed chat application but I need to use ajax so that application make lesser trips to database, BUT I DON't KNOW HOW TO USE THIS CODE WITH MY SIMPLE CHAT APPLICATION.PLEASE SOMEONE EXPLAIN THE USE OF CODE IN DETAIL
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Reference to google J-Query api.
You can download and add jquery javasripts files to you soln.-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<script type="text/javascript">
function callService() {
//url of your web service
$.ajax('../sessionOut.asmx/GetNewsAndAlerts',
{
beforeSend: function (xhr) { },
complete: function () { },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
jsonp: 'callback',
type: 'POST',
error: function (xhr, ajaxOptions, thrownError) {
//Function will be called when any error occcured.
alet(thrownError);
},
success: function (data) {
if (!data.d) {
//Cound not find data.
}
else {
if (curdata != data.d) {
//result of you web method is stored in data.d object.
//TODO : Work with you data here.
alert(data.d);
}
}
}
});
}
callService();
</script>
</body>
</html>
The idea behind Ajax is to reduce the number of full page refreshes that your web application does. It does not reduce database activity as you mention in your question.
In this case CallService calls a page in this case getnewsandalerts and the success: code is called when the page results are returned to the Ajax call at that point any data returned by the page on the server is available to jquery on the web page in the browser.
I have a page which displays the following content when it is loaded:
<div>
<img src="loading.gif" alt="Loading" /> Generating PDF Document, please wait.
<div>
At the same time, I want to run this method the code behind automatically:
private void GeneratePdf()
{
...
}
Lastly, I want to redirect the user to the File.pdf path once the GeneratePdf() method is completed.
How do I do this?
You need to use the Page_Load event as explained here. Additionally, this is a great explanation of the page life cycle. You should take a look at it. Here is some sample code from the above link:
<script runat="server">//This script runs on the server and dishes up some output for the page.
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>//This generates the textbox that will be given a value from the above script.
</form>
</body>
</html>
Hope this helps you!
I suggest to use GeneratePDF with ajax, so you can use like
$.ajax({
url: '/pdf/fiele_to_generate_pdf.aspx',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: $.toJSON(jsonObj),
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.location.href = '/pdf/example.pdf';
}});
so for loading you can use jquery, there is a good plugin named BlockUI you can use it before your ajax call.
You can use the asp:Timer control to indicate when your code-behind should be called
<asp:Timer runat="server" ID="timer1" Interval="3000" OnTick="timer1_Tick"></asp:Timer>
Then implement the Timer's Tick event. This will be called after 3 seconds (3000ms) as specified in the markup
protected void timer1_Tick(object sender, EventArgs e)
{
GeneratePdf();
Response.Redirect("~/somepath/generatedPDF.pdf");
}
I have a website where i want my visitors to invite their friends. I'm using the Requests Dialog for this. But now i want to add a dynamic text message to this invite.
The dynamic text is generated in an c# code behind file. But the Request Dialog is triggered with javascript.
Here is the Request Dialog part on my aspx page:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/nl_NL/all.js">
</script>
<script>
FB.init({
appId: '[MY-APP-ID]', cookie: true,
status: true, xfbml: true
});
function inviteFriends() {
FB.ui({ method: 'apprequests', message: '[THE DYNAMIC MESSAGE I WANT TO SEND]', data: 'tracking information for the user' });
}
</script>
Is it possible to call this javascript form codebehind code and pass the message parameter too?
Thanks in advance!
You can use <%= ... %> to expose your code to page (assuming you have message in requestsDialogMessage variable):
FB.ui({
method: 'apprequests',
message: '<%= requestsDialogMessage %>',
data: 'tracking information for the user'
});
Other way may be exposing the message to some JavaScript variable and using it within FB.ui call:
<script>
var exposedData = {
requestsDialogMessage: '<%= requestsDialogMessage %>'
};
</script>
And later in your JS code:
FB.ui({
method: 'apprequests',
message: exposedData.requestsDialogMessage,
data: 'tracking information for the user'
});