I am using javascript to make call to server. The javascript code is following,
function cs() {
alert("");
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "lp.aspx?pb=true", true);
xmlhttp.send();
}
And my server code is following
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["pb"] != null)
{
Response.Redirect("main.aspx");
}
}
The problem is my Response.Redirect is not working with my ajax call. Why is that?
You can not redirect on ajax call, because, it expects some return value from the invoked page. And if that page itself redirects, it has no way to tell calling function to redirect, as it simply expects some return value in success callback.
So to solve this, you can return a param lets say { redirect: true } if condition satisfied. And on success callback , if redirect is true, then redirect using JS - window.location.href="required".
I believe that redirect doesn't work because the Response for the page with the javascript is closed before the AJAX call is even made.
Instead of using Response.Redirect you could send back a string containing the url and in your script use location.href to redirect.
Simple you can not use response on ur ajax call. use
window.location
Related
I am using following Ajax javascript code to get response from another php page.
I below code, main page is sending request to mypage.php which is located in same directory and getting response.
But mypage.php page is accessible separately through http:// ... /mypage.php
I want to send request the non public files and get response to prevent mypage.php access from http web access.
say i want to access it from /home/privatefolder/mypage.php from ajax
<script type="text/javascript">
function checkmypage(str)
{
//alert(str);
if (str=="")
{
document.getElementById("mypageResponse").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mypageResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mypage.php?mypage="+str,true);
xmlhttp.send();
}
</script>
Note: I know javascript cannot access non http:// files. please provide alternate solution
Add request check at the top of your mypage.php and if true, include another php script from your privatefolder which does the jobs of mypage.php:
1- Check if request is an AJAX request or not in mypage.php :
if(empty($_SERVER['HTTP_X_REQUESTED_WITH'])
|| strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
// Not an AJAX request!
header('Locate to an error page or other page');
exit();
}
2- Include your script in else statement:
else {
// $_SERVER["DOCUMENT_ROOT"] is a good usage in here
include('Path to your script in privatefolder');
}
I'm trying to execute a block of code when my XMLHttpRequest reaches state 2. The reason why I want it to be in state 2 is that I don't want the user to wait for a response of the server( I would like to redirect the user at this point).
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 2) {
window.location.href = urlFromPreviousAjaxcall;
}
}
xmlhttp.open("POST", "url", true);
xmlhttp.send();
However the block of code inside the if(xmlhttp.readyState == 2) will only be called as soon as the server is done processing the call. This part has to be executed as soon as the call is made( without the waiting from the server).
In the documentation I found that state 2 is reached as soon as the call is send. However that is not the case.
Update:
the call I am trying to make involves calling a Api on the server( this takes time to complete). For the client it doesn't matter what happens to the call.The only thing I want is that the call is executed. So basicly I'm trying to gain speed here.
I know that as soon as I redirect the user, the code will stop running. However the call to the server should have been made(and send away).
What am I missing or doing wrong?
Thanks you all for your help.
I found the solution:
[HttpPost]
public void methode(String parameter,String parameter)
{
Task.Factory.StartNew<string>(() => RunTask(accessToken, parameter, parameter));
}
private string RunTask(String parameter, String parameter)
{
try
{
// Code to execute here
return "Done!";
}
catch (Exception e)
{
return "Error: " + e.Message;
}
}
At the server I started a Task. In this task I execute the long procces. It still takes a brief moment before the server returns the call to the user.
When debuggin ( in visual studio) you can see that the task is running without the presents of the user.
Note : all sessions are gone at the moment I redirected the user to an other page.
I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.
I'm wondering what is the simplest way to fill a div by grabbing a PHP script (and send data like POST or GET) to process what data to return.
But without the use of a library... All I ever find is prototype and jquery examples.
Has any one done this without a library?
var xmlhttp;
function showUser()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="yourpage.php";
url=url+"?q="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("yourdiv_id").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
I'd suggest you look at this code.
You will see how to handle perfectly XHR objects, and it also gives you some sugar syntax.
Btw, a less-than-one-hundred-lines "library" should be fine, since it basically does what you want it to, and no more.
current i am trying to use ajax for my site ....... because of size of data is not limited i need to use post method for send data to database but the problem is i am unable to fetch the Post variables in the test.asp
here is the script i am using
function SaveData(content )
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
msg=xmlhttp.responseText;
alert(msg);
}
}
var para = encodeURIComponent("content="+content)
xmlhttp.open("POST","test.asp",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(para)
}
and here is test.asp code
t = Request.form("content")
Response.write(t)
please help me solving this problem of fetching the Post method variable in test.asp
if possible any one can share code of jquery ajax with post method in asp classic too that would also be helpful
You need to change this:
var para = encodeURIComponent("content="+content)
into this:
var para = "content=" + encodeURIComponent(content);
The way that it was, you were submitting something like this to the server:
content%3Dtest%20data%20123
With the adjusted line of code, you're submitting something like this, which is as it should be:
content=test%20data%20123
Have you considered using a JavaScript library such as jQuery? A library will abstract away all this unpleasantness:
$.post("test.asp", { 'content': content }, function(data) {
alert("Returned data: " + data);
});