Stop page refresh - javascript

I'm writing a small piece of code which takes input from a user via html form to then retrieve information (in xml) from a server (which is running locally) using XMLHttpRequest, once I get the information I output it into a list using the method I've written for the onreadystatechange. However once it's written the list to the page it automatically refreshes the page and the list disappears. I'm absolutely lost as to why it is doing this?! I've managed to forcefully stop the page refreshing using window.onbeforeunload and stopping the refresh, but I can't help but think there is a better way around this and that I must be doing something wrong. My code is as follows:
var xmlhttp=null;
function byObserver(){
var a = document.forms["byObserverForm"]["observerName"].value;
a = encodeURIComponent(a);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.onreadystatechange = onReadyStateByObserver;
xmlhttp.open("GET","http://localhost:8004/birdobs/observer/" + a, false);
xmlhttp.send();
}
return false;
}
function onReadyStateByObserver(){
if (xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
var xmlDoc = xmlhttp.responseXML;
var observations = xmlDoc.getElementsByTagName("observation");
if (observations.length != 0){
// output into unordered list
var f = document.createDocumentFragment();
var e = document.createElement("ul");
f.appendChild(e);
var ul = f.firstChild;
for (i = 0; i<observations.length; i++) {
var li = document.createElement("li");
var te = document.createTextNode(observations[i].getAttribute("observer"));
li.appendChild(te);
ul.appendChild(li);
} // end for
document.getElementById("content").appendChild(f);
window.onbeforeunload = function(){
return "Refresh";
}
}
}
}
//have also tried return false here
}
Any help would be highly appreciated as I've spent so long trying to fix this, many thanks in advance! (I haven't included the HTML as I thought it wasn't needed, but please ask if it would help and I'll post it up!) I'll just finally add I'm running this in chrome.

This is most likely because the browser is still submitting the form. You need to inform the browser that you do not wish for the default form submit handling to happen.
Returning false from your onsubmit method should do this.
** Update **
Presuming you are using the onsubmit handler and the function being called is byObserver then try the following:
<!-- HTML -->
<form ... onsubmit="return byObserver()">
// javascript
function byObserver() {
...
return false;
}

you should stop the default event when you submit the form, e.g. with return false at the end of the function called on submit. Maybe the page is refreshing because you're not stopping the submit event (and the browser is thus redirected to the page specified on action attribute of your form)

At the end of the method that's invoked by submitting your form you need to return false;
It looks like the function being fired is byObserver and so you'd do the following:
function byObserver(){
[...]
return false;
}

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.

Missing characters in text box with onkeyup listener in Firefox

I've got a text field that the user can use to search for items. There is an onkeyup listener attached that searches a database based on what has been entered. In Chrome this works very well, but in Firefox there is lag and fast typers will see missing characters in the text field. Is this a Firefox issue or is there a workaround for this?
To get the general idea of what I'm doing in the code I have something like this:
HTML
<input type="text" onkeyup="makeRequest()">
JS
function makeRequest() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url + parameters, false);
xmlhttp.send("#");
return xmlhttp.responseText;
}
Maybe make it asynchronous and have some kind of control so as not to trigger it if one request is still ongoing. In that context, I think it would make more sense and also maybe solve your problem on Firefox.
Right now if someone types many letters quickly you're sending unnecessary requests anyway.
Like that:
//html file
<input type="text" onkeyup="makeRequest()">
//java script file
function makeRequest() {
if(!req_called){
req_called = true;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url + parameters, true);
xmlhttp.load = function(){
req_called = false;
return xmlhttp.responseText;
}
xmlhttp.send("#");
}
}

Why would an Ajax Auto-Complete box stops working after navigating to a different page on the same site?

I am working on a site that has an auto-complete search box. The search box relies on Ajax, Javascript and PHP. The user begins typing into the search box and an ajax request calls a php file which polls a database and returns the possible results. This seems to work fine until the user navigates to a different page on the site and then returns to the search page. Once you return to the search page and try a new search, the auto-complete does nothing. If however you navigate to an outside page (Google for example) and return to the search page it works again.
I am not sure if this has to do with some kind of caching or binding that is taking place or if there is something in the code that I am actually doing wrong.
Relevant code in the search page:
<script>
var tax = document.getElementById("taxonomic");
var sea = document.getElementById("searchDiv");
var ctt = "";
function updateSearch(str, field)
{
str = str.split(",");
str = str.pop();
str = str.trim();
if(field == 1)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("resultsSpecies").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","http://.../UpdateSpecies.php?str="+str,true);
xmlhttp.send();
}
if(document.getElementById('taxonomic').value.length > 0)
{
document.getElementById('submitDiv').style.display= 'inline';
document.getElementById('searchDiv').style.display= 'inline';
}
else
{
document.getElementById('submitDiv').style.display= 'none';
document.getElementById('searchDiv').style.display= 'none';
}
}
</script>
<input name="species" class="form-control" id="taxonomic" placeholder="Taxonomic Information" onfocus="updateSearch(this.value, 1)" onkeyup="updateSearch(this.value, 1)">
<div id="resultsSpecies" class="results"></div>
Relevant code in PHP page (UpdateSpecies.php) called by the Ajax request:
<?php
$str=$_REQUEST["str"];
$con=mysqli_connect();
if
echo ...
else
echo ....
mysqli_close($con);
Any thoughts/suggestions would be greatly appreciated.
Sounds like there might be a 'onchange' event that does your Ajax call and it only gets added to the DOM in one particular circumstance.
Running with the Javascript console I found the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Adding the following line of code to UpdateSpecies.php solved the problem.
header('Access-Control-Allow-Origin: (your_url));
Thanks for the suggestions, I thought it was more likely to be a PHP error than Javascript.

php not returning any result to javascript ajax object

I'm trying to use ajax, I've used it before, copied the code from my previous html file and altered the values sent, php file to process the code and I'm using the POST method. However, the php script does not return anything to the html page. I've checked all i can, so I'm here now.
function look () {
var x = document.getElementsByTagName('option')[document.getElementById("region").selectedIndex].value;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// modal section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("accordion");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
ajaxRequest.open("POST", "search.php", true);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
alert(x);
ajaxRequest.send("region=" + x);
}
The php code is a simple
<?php
echo "The world is blue.";
?>
yet, it returns nothing to the chosen div.
You've probably not posted enough information for us to answer your question. But, I acknowledge that you probably are not sure what questions you need to ask in the first place.
First, I must agree with #cgf. jQuery or the alike will make this easier.
But lets focus on the problem at hand. We need to know what is happening behind the scenes.
The best way to do this is through a developer tool bar such as firebug. Chrome has one built in.
So, load up chrome and hit F12. This should bring up a very busy looking pane on the bottom of your window. Select the Network tab and then request your page / trigger your javascript. What output do you get in the network tab? Mainly, under status do you get 200, 500 (server error) or perhaps 404 (not found)? Update your question above with what you see / get.
My hope is that this should point you in the right direction.

AJAX / ASP - Simple Task But I'm stuck?

I'm trying to do a simple AJAX call to an ASP page, that resets session variables and posts a little message back on completion. I'm doing this purely to learn AJAX.
The example came from W3 Schools website but since applying it to my page, I can't seem to get it to work and it's not producing any errors, which is annoying, because I can't debug it.
This is my JS, which is called when a user hits a button [Clear Form]:
function resetSearchForm()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("notification").innerHTML=xmlhttp.responseText;
document.getElementById('notification').style.visibility = 'visible';
}
}
xmlhttp.open("GET","clearSearchData.asp",true);
xmlhttp.send();
document.searchFrm.searchStr.value='';
document.searchFrm.vertical.checked = true;
document.searchFrm.horizontal.checked = true;
document.getElementById('dateRange').selectedIndex = 0;
document.searchFrm.searchStr.focus();
}
And this is the ASP (clearSearchData.asp) that clears my session variables and writes a message:
Response.Expires = -1
Session("search-str-boolean") = ""
Session("search-str-plain") = ""
Session("date-range") = ""
Session("date-from") = ""
Session("date-to") = ""
Session("specificDate") = ""
Session("peopleStr") = ""
Session("orientation") = ""
Response.Write "Form has been reset"
Can anybody see where I'm going wrong? I have been looking at it for a long time and I just can't see it.
The function itself works because the last part of the function gets processed, the bit that clears the form values... but... the AJAX call doesn't happen because the session variables still contain data and the message doesn't appear.
Many thanks in advance...
UPDATE - - - - - - - - - - -
It now works. The problem was I didn't include the full URL to the ASP page. Thanks for 'thedaian' (below) for pointing that out
Chances are, something is wrong with the page you're trying to get via AJAX. Check what xmlhttp.status is, if it's 404, then you're never going to get to the point where you're printing the AJAX response. Make sure that "clearSearchData.asp" is accessible from the same directory as your javascript. This is a common problem if you have your javascript code in a separate folder from the rest of your site. Or simply put in the full URL path for the "clearSearchData.asp" so it'll definitely work.
Something to point out, the function in xmlhttp.onreadystatechange is (usually) called after it's declared in the code. In this case, it gets called after your search form fields are cleared out and reset.
The ajax call does not automatically send along a session cookie. That means the session you're clearing is not the user's session, but just a session that's been created for that ajax call alone.

Categories

Resources