Ajax reloads page instead of submitting the request - javascript

I have an Ajax script that causes the entire page to reload without ever submitting the URL for the request in the script. The server logs show the page URL as being re-submitted. Adding an alert demonstrates that the function is being run, but the embedded URL seems to be ignored. When used by itself, the request URL in the script returns the correct data.
Why isn't the embedded URL applied?
Another Ajax script on the same page works fine using a var named xhttp instead of xfiles so there's no conflict in that.
function rlist() {
var xfiles = new XMLHttpRequest();
xfiles.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("filelist").innerHTML =
this.responseText;
}
};
xfiles.open("GET", "/cgi-bin/cnc.cgi?precert~patients~rlist~813527153~0975184859230735~~6306919737~622156596S", true);
xfiles.send();
}
The objective is to refresh a small table of uploaded files. The responseText contains the table html with links. That can't be the issue here though since the URL is never submitted in the first place.

Swetank Poddar actually had the right idea... As it turns out, it was user error. I had left out the colon in javascript:void(0) and continuously overlooked it. So the Ajax was running correctly but the typo in the link was causing the page to subsequently reload. It was all so fast that it wasn't obvious and the database on the server showed the last processed hit as the link to load the page in the first place, which was the link to reload it as well.

Related

how to fix xmlhttprequest function problem when inserting data

my code works only if i add this code:
document.write(str);
which open a new page and write in it insert data in database
but if i try to the code without it like this :
function addcourse2(str,cn)
{
xmlhttp=new XMLHttpRequest();
//document.write(str);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status == 200) {
alert('response:'+xmlhttp.responseText);
} else {
alert('failure!');
}
};
xmlhttp.open("GET","tpages/addcourse2.php?q="+str+"&p="+cn,true);
xmlhttp.send();
}
here i get alert message failure and nothing gets inserted into database
i need and explanation to this a way to fix it
looking at your comments i understand that the page is refreshing after you click the button before the state is reaching 4 then this is the button code to prevent it from refreshing
add return false;
<button "onclick='addcourse2("value1","value2");return false;'>add course</button>
Let's try to describe.
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open.
https://developer.mozilla.org/en-US/docs/Web/API/Document/write
So, this AJAX script with document.write work as from new page and each case calls to URL ""tpages/addcourse2.php?q="+str+"&p="+cn"
If commented document.write Then browser may be cached URL and browser read from cache and doesn't call same URL. So, you can use unique URL string and test so.
Also, may be was an other case.

How To Get an HTML element from another HTML document and display in current document?

I'm building a web site which lets users post requests on site and others to respond. I have built an app-like form to collect information. In that form I need to display 3 pages.
So I have created one page with the from and and a JavaScript file to handle these 3 pages. Other form-pages are designed separately (HTML only).
I'm planning to load the other two pages into that 1st page with XMLHttpRequest and it works.
But I need to take 3rd page into the 1st form-page (display the 3rd page of form) and change the innerHTML of that 3rd page. I tried it with
function setFinalDetails() {
document.getElementById("topic").innerHTML = object1.start;
}
//creating a XMLHttpObject and sending a request
//requiredPage is the page we request.
//elementId is the element we need to display
function requestAPage(requiredPage) {
selectElementId(requiredPage);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
m = xhttp.responseXML;
y = m.getElementById(elementId).innerHTML;
document.getElementById("hireForm").innerHTML = y;
//m is a global variable
//m is the object recieved from XMLHttpRequest.
//it is used to change the innerHTML of itself(m) and display.
//y is displaying the 3rd page in the form-page one("id =hireForm")
return m;
}
};
xhttp.open("GET", requiredPage, true);
xhttp.responseType = "document";
xhttp.send();
}
but that gives an error:
Cannot set a .innerHTML property of null
find my work on https://github.com/infinitecodem/Taxi-app-form.git
It it hard to help you in detail because we do not have a way to reproduce your error and test your code. I can suggest you to use a service like plunker to share your code. I do not know if this service will support to do some xhrRequest on other files in its working tree, you can try.
Your error message seems to reveal that one of your document.getElementById(...) is returning null instead of the html elt you want (so the id do not exist in the page).
But again without a way to test, it is hard to help you more sry. I really encourage you to try to share a link to a service (like plunker, etc) that will help others to play with your use case.

Redirecting XMLHTTP request - Javascript

I have a web page that has a too much content and javascript. When the page loads it makes multiple requests using Ajax and XMLHttp to load data. Is there a way to hook up all these requests and direct them to a different server.
For example the webpage fetches data from www.apple.com/data and www.mango.com/data after it is loaded. Is is possible to insert a script somewhere in the webpage which automatically changes any request made to www.orange.com/data.
Waiting for answer. Thanks
You can add a global handler to the ajaxSend event, the event will be triggered right before the ajax request being sent out. So you can check the request uri, apply some filtering logic, and then redirect the request by abort the original and resend it.
Below is an example
$(document).ajaxSend(function(e, xhr, opt) {
if (opt.url.indexOf("www.apple.com") !== -1) {
// abort the request
xhr.abort();
// change the uri to www.orange.com
opt.url = opt.url.replace("www.apple.com", "www.orange.com");
$.ajax(opt);
}
});
Ok. So I followed Anthony C's answer and it did actually work. But the problem with his solution is that it only works with Ajax requests not XMLHttpRequests (I am not sure why, I am a beginner at this topic.) However digging on his idea of creating a hook I came across a similar post here How to get the URL of a xmlhttp request (AJAX). The code provided a way to fetch the requested URL for each request. So by a little tweak to the code I managed to come up with this:-
XMLHttpRequest.prototype.open = (function(open) {
return function(method,url,async) {
var uri=getLocation(url);// use get location function to convert requested url string into readable url
if(uri.hostname!="orange.com"){
url="https://orange.com" + url;
}
open.apply(this,arguments);
};
})(XMLHttpRequest.prototype.open);
var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
This code at top of the page allows me to change the host name of all XMLHttpRequests that are not directed towards orange.com. Though I am sure there are better ways to write this code as well but since I am not an expert over javascript this will suffice my need for the time.

Reload iframe only when iframe contents are new?

Short version:
How could an HTML file that has an iframe pointing to another HTML file on the same server automatically reload that iframe whenever the iframe's content is new?
Context:
I'm using an HTML/Javascript file to watch for new instructions from a Python program. The Python program rewrites a simple HTML file when there are new instructions to see.
So my easy solution is a bit of Javascript that forces a reload of the iframe src every second.
However, this causes a flash of the content every time the iframe loads, and most of the time the information isn't new.
Instead, I'd prefer for the HTML file to only force a reload of the iframe src when it's new. Is this possible?
You can use an AJAX request to check if the iframe has changed.
var value;
(function check() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/url/toIframe'); // change this to the correct URL
xhr.addEventListener('load', function() {
if(value === undefined) {
value = this.responseText;
} else if(value != this.responseText) {
value = this.responseText;
// refresh iframe!
}
setTimeout(check, 1000); // check again in another second
});
xhr.send();
})();
This makes requests to the server to see if the content has changed. There is one second between each the end of a request and the start of the next check. (And currently, there is no error handling if the server goes down.)
FYI, if the server sends a Last-Modified header, you could actually make a HEAD request and just check that header. If you don't know what I am talking about, don't worry about it.

Response.Redirect AFTER call to JS Alert or Confirm

I am working on a VB.NET web application. When someone successfully changes their password I want to show a popup message that lets them know it was changed successfully. After they click OK I want to redirect them to the main page. Code looks like this:
ClientScript.RegisterStartupScript(Me.GetType(), "confirmScript", "ConfirmNewUser();", True)
Response.Redirect("MainPage.aspx")
Why does the redirect happen and the alert popup never displays?
Try this:
1) Remove Response.Redirect from the code behind.
2) Change the ConfirmNewUser function as given below:
function ConfirmNewUser(){
//Existing Code of ConfirmNewUser
//New Code.
var msg = "Password changed successfully. Press OK to go to Home page Cancel to stay on current page.";
if(confirm(msg)){
window.location.href = "MainPage.aspx";
}
}
You are calling the redirect server side, your script never get a chance to run. use window.location to do the redirect client side, something like this:
function ConfirmNewUser() {
if(confirm("Your password has been changed, click OK to continue")) {
window.location = "MainPage.aspx"; //go to home page
}
}
The reason is because all server-side processing will take place prior to client-side.
One solution would be to pass "MainPage.aspx" to your client script as follows:
ConfirmNewUser('MainPage.aspx');
Your client script would then have to take a URL parameter:
function ConfirmNewUser(url) { ... }
and follow up with a window.location:
...
if(confirm(...))
{
window.location = url;
}
and remove the following from your server code:
Response.Redirect("MainPage.aspx")
Response.Redirect sets the Location http header and a 302-Moved response, the browser will act upon this as soon as it sees it. As headers come before content, your script is never seen or parsed.

Categories

Resources