If I use the solution posted here, I won't get transferred to the new page. But if i inspect the $.ajax() call in the console, the actual .aspx page seems to be in the response body. So my guess is that the .ashx gets redirected to the .aspx.
void ProcessRequest(HttpContext context)
{
context.Response.Redirect(newUrl);
}
How do I redirect the user from the .aspx page that sends the ajax request? Do I need to call a method on that .aspx from my handler.ashx?
The Response.Redirect command is nothing more than instructions to the browser to move to some other page. This commands are first a header instruction to the browser. Also there is a javascript small script that is written on the page in case the header is fail.
Now, when you make the call with Ajax (no matter if its handler or page) the results return to the page but inside the ajax buffer, the redirect headers are "eaten" and not go to the browser itself to runs them. So no redirect can be directly done via ajax call.
What you should do, is to return a signal to your ajax call, and see that signal/flag and make the redirect using javascript call window.location.replace("redirectPage.aspx")
For example, something like:
$.ajax({
url: "action.ashx",
type: "GET",
dataType: 'json',
success: function(data)
{
if(data.NeedRedirect)
window.location.replace("WhereToMove.aspx");
},
error: function(responseText, textStatus, XMLHttpRequest)
{
window.location.replace("WhereToMove.aspx");
}
});
Related
I am having unexplained behavior when I post from jquery using ajax to C#.
1) The main page is called not the method I am requesting in jQuery.
To work around this I simply put an if in the page load so that if a particular item is in the querystring it will trigger a series of commands. It does hit that if statement and runs the code perfectly fine. There are some methods that do things like change a color on the map. These never actually happen. I can set a label and it will pass right over it but the label remains unset.
2) strangely enough.... my page has a timer with a refresh on it. It refreshes the page and now the changes are processed.
Here is the way I am calling my method in jQUery:
function mycmethod(param)
{
//alert(precinct);
$.ajax({
url: "myPage.aspx/someMethod",
type: 'POST',
data: "params=" + param,
success: function iGotData(responseJSON) {
// alert("Worked");
},
error: function (xhr, status, errorThrown) {
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.log(xhr);
alert("Didnt work:" + errorThrown);
},
})
};
It was originally set to async: true but that didn't make a difference.
The method its not calling on load is:
[WebMethod][ScriptMethod]
public Boolean someMethod(string param)
{
setFeatures();
GenerateMap();
return true;
}
I doubt its relevant but I am calling a jquery call with over mouse over of a specific element. That jquery calls a function which calls a asmx web service that returns some jSON. I am calling the mycmethod after the JSON is returned.
Why is my UI elements not responding until the page refreshes. If not, is there a way I can force a refresh like the timer does?
[WebMethods] methods should be declared as static.
I've also found that you might need to specify the content type in your ajax call:
contentType: "application/json; charset=utf-8"
Also, your data option looks suspicious. Maybe you should append it to the url option:
url: "myPage.aspx/someMethod?params" + parm
or, more ideally, send it as either a JSON object or a JSON string:
data: {
params: param
}
or
data: JSON.stringify({
params: param
})
If I understand you correctly, you're loading the page, then calling the server via ajax and expecting the server to change UI elements of the currently loaded page.
It doesn't work like that, unfortunately. Once you've served the page, the server itself cannot manipulate that page without doing a refresh/post back (or something along those lines).
If you want to update the UI without doing a refresh/post back you can have your WebMethod return HTML, and your jQuery success method can update the relevant controls.
Alternatively you could use jQuery's .get() to retrieve a fresh copy of the page via ajax, and update your current page like that. (although it's less efficient)
Requirement:
User calls a page and I display page is loading while i execute a method in background and redirect to the url that the method returns.
Tried using async method call in pageload ,pagenotredirected as already loaded.
Tried updating textbox from the async method and call textboxonchange not working as page aleady loaded
Have added the code for ajax per ur suggestion please review
I call a async method inside pageload and in the pageload I display loading message ,after the async methos completes I get a url ,iam trying to redirect to that url but iam unable to do it inside the async as the page is already loaded ,so iam updating an hidden textbox with this url and using the onchange event in that text box and redirecting but still the page is not redirected,can someone please suggest a better way to do this-Thanks
<asp:TextBox runat="server" ID="urlTextBox" Value="" Style="display:none;" AutoPostBack="true" ></asp:TextBox>
$(document).ready(function () {
$('#urlTextBox').change(function () {
var keyword = $("#urlTextBox").val();
if (keyword.length > 0) {
window.location.href = keyword;
}
});
urlTextBox.Text = url;
the urltextbox gets value inside the async method as I process a long running process inside the async to get this url
I have added a js file in which I call the c# method like this
$(document).ready(function () {
$('#outputFromCmdLine').Text = "Loading...";
GetOutputFromCommandLine();
});
function GetOutputFromCommandLine() {
$.ajax({
type: "POST",
url: "Page.aspx/ConvertToBatch", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:true,
success: function (Result) {
window.location.href = Result;
},
error: function (request, status, error) {
alert(request.responseText);
}
});
and the c# method is sync method and returns the url like this
[System.Web.Services.WebMethod()]
public static string ConvertToBatch()
{
some process
return urlstring;
}
I also added the js file name in top of aspx page ,but nothing gets called ,is this the right way to do it
<script type="text/javascript" src="/Scripts/jqueryFile.js"></script>
Instead of calling the async method from inside the page load you should call it using AJAX in JavaScript once the page is loaded. Then you can use the response from the AJAX request to retrieve the URL with which to trigger navigation to.
<script>
$(function()
{
$.ajax(
{
url: "/api/request",
}).done(function(responseUrl)
{
window.location.href = responseUrl;
});
});
</script>
This will wait for the page to be loaded, make some request to the server, and navigate to the response string (expecting the HTTP response body to be a URL).
I think you would use an ASMX web service or better yet an ASP.NET Web API controller to handle the actual request/response.
I know that with Visual Studio 2013 you can create an ASP.NET Web Forms project which includes Web API and configures them automatically to work together. If you are working with an existing project you could add Web API as a NuGet package and add the appropriate plumbing to make it work manually by simply looking at the VS2013 wizard-generated project as an example of how it is done.
EDIT:
It seems you found another way to handle AJAX calls which is using a WebMethod. WebMethods are described in this question.
i have this need.. I hope someone can give me a right advice !
i have to read the whole html content of a page using an ajax call, it is necessary that the client who is visiting my page is who that make this request to read the html content, and not my application (i mean using downloadstring method of c#)
After this, i need to read the response of the ajax call (in this case the html content of the page setted in the "url:" parameter of the ajax call) server-side (in my code-behind)
how i can do that? is possible?
Thank you for your help..
Stefano
Stefano,
You could get the html content through ajax using, for exemplo, jquery get like this:
$.get('ajax/test.html', function(data) {
//data is the html
});
After that you can make another ajax call sending the data to your "code-behind", as you can see in the complete code:
$.get('ajax/test.html', function(data) {
$.ajax({
dataType: "json",
data: "htmlData=" data
type: "POST",
url: '/code_behind.aspx',
success: function(response){
console.log(response);
}
});
});
I hope that this helps.
Pardon my noobiness in web development terminology.
I am trying to execute the following [WebMethod]:
public static void CreatePendingCaseFromChat(string userInputs)
{
//Do a bunch of stuff here with the userInputs string
}
With the following AJAX (which resides on another server):
$.ajax({ type: "POST",
url: "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat",
crossDomain: true,
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){alert("success in ajax call")},
error: function (data){alert("error in ajax call")}
});
MyCode.aspx contains the following lines within the Page_Load() method:
Response.AppendHeader("Access-Control-Allow-Origin", "*"); //Allow Cross domain AJAX call, update the "*" to be a specific URL
Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
Response.AppendHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
If I do the following, instead of the ajax call:
var invocation = new XMLHttpRequest();
var url = "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat"
if (invocation) {
invocation.open('POST', url, false);
invocation.send();
}
else {
alert("no invocation");
}
Then I can confirm with FireBug that the following Response Headers are set:
Access-Control-Allow-Head... content-type, x-requested-with
Access-Control-Allow-Meth... GET, POST, OPTIONS
Access-Control-Allow-Orig... *
With the AJAX call, none of those headers are shown.
I would like to make this work either way, whether with the AJAX call, or with the XHR call.
For the XHR call I can't figure out how to send the userInputs string to the WebMethod.
For the AJAX call I can't get it passed preflight or w/e it's called (the OPTIONS call).
I've posted a bunch of code on question:
CORS - Ajax error function reports error code as 0 for an API request returning 401
It is using MVC4, but should give you everything you need to get this working.
Can anyone help? I am trying to interrogate the UrlReferer whcih should contain Google.com but it contains my current site. My web page is a standard HTM page and jquery calls a static method like so
[WebMethod]
public static void ProcessTracking(string jsonString)
Inside this method i do a standard lookup on Request.UrlReferrer like so
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
But it always contains my current domain, this was a little suspect so i created a standard asp.net page and did the same and it works 100% without issue..
So it appears that when my htm page calls via jquery my webmethod (static) and interrogates the UrlReferrer it return ALWAYS my current site which is wrong.
Does anyone know a work around?
I even tried doing something in session_start etc in global.asax but no fix.
EDIT: How i am calling the page from jquery in html
$.ajax({
type: "POST",
url: "MyService.aspx/ProcessTracking",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
},
error: function(msg) {
alert(error);
}
});
That script is hosted on your page, right? In that case, the referrer will be your site.
If you want the referrer for the page itself, then you need to pass it as an argument with your Ajax call; it won't be present in the HTTP header.
You can read the referrer of the page from the document.referrer property.
Surely it should contain your current domain, as that is webpage doing the post?
If you want to retrieve the original callers page, you'll need to store that in the original webpage, before calling your ajax code, and then passing that through.
Resources called via AJAX requests will consider the calling page as the referrer, which is why your domain is showing up as the referrer.
You had the right idea to use the Global.asax, but try hooking in to the BeginRequest method:
void Application_BeginRequest(Object Sender, EventArgs e)
{
string referrerDomain = HttpContext.Current.Request.UrlReferrer.Host ;
}
This is working as intended. When you use AJAX to post, you are sending a request from your page (your domain!) to the target server.
One workaround would be to store the original referrer's host name in a javascript variable when constructing your page:
var referrerHost = '<%= HttpContext.Current.Request.UrlReferrer.Host %>';
Then package that into the jsonData variable you're sending to the ProcessTracking method in the ajax function's data parameter.