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

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.

Related

passing localStorage data to PHP

I want to view and manipulate Javascript localStorage information on a PHP page using PHP. I have gotten pretty far with this, but I'm not where I need to be. I'm using PHP 7.3 and vanilla JS.
I have AJAX POSTing the data to a PHP processing page (not the one that calls the javascript function). However, I need to access the POST variable on the page that called the javascript. How can I pass the information back without a click?
The page wishlist.php contains a link to the js file and <div id="temporary_wishlist"></div>.
Javascript called from wishlist.php:
window.addEventListener("load", function() {
loadWishlist();
});
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var item_notes = wishlistStorage.data.item_notes.join("%20");
var comments = wishlistStorage.data.comments;
var wishlistRequest;
var response = null;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
response = wishlistRequest.responseText;
document.getElementById("temporary_wishlist").innerHTML = response;
}
}
wishlistRequest.open("POST", "/wishlist-processor.php", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items)
+ "&wishlist_itemnotes=" + encodeURIComponent(item_notes)
+ "&wishlist_comments=" + encodeURIComponent(comments));
}
Given the above, I have access to $_POST['wishlist_items'] inside wishlist-processor.php. Whatever I output inside of wishlist-processor.php is visible to the visitor on wishlist.php inside <div id="temporary_wishlist"></div>. It is not, however, visible in the Console.
On wishlist.php, I want to load the information into a PHP variable so I can send it to a MySQL query. If I could just POST to self like I do with form validation I would have access to $_POST['wishlist_items'] from wishlist.php. I already tried setting the URL in the open("POST", URL, true) function to _self or wishlist.php, and that didn't work for me.
I know it's suggested that I use Fetch, but I'm already overwhelmed learning new things I want to understand AJAX better. Also, Fetch doesn't work on Firefox Android.

Function execute after Ajax request is complete (pure JavaScript)

In my application I use MVC model and Views are built with JavaScript DOM API.
On each page I have to check user's information to find out if session is active and if user's role gives him ability to access that page.
To make this happen, on each page I have "onload" function that triggers "sessionCheck" function which sends AJAX request to controller and returns information with which application makes decisions.
As I said JavaScript is also used to build Views, which means that after "sessionCheck" function I also have "headerView", "sectionView" and other functions that build the structure of page.
So the problem is that, before "sessionCheck" is finished other functions are loaded and nearly for 1-2 seconds users have ability to see what happens on that page and only after that they are transported out of that page by application if that is needed.
I read that there are some solutions in JQuery where "ajax.Complete" functions are available, but I couldn't same solutions in pure JavaScript. Can someone help me to solve this problem ?
This is HTML
<body onload="sessionCheckAdmin(); adminHeaderView(); adminUser(); modalView();">
sessionCheckAdmin functions looks like this
function sessionCheckAdmin()
{
var formData = new FormData();
formData.append("Code", "3");
formData.append("Sequence", "27");
formData.append("TaskId", "All");
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
var array = JSON.parse(xmlHttp.responseText);
if(array["userRole"] != "Administrator")
window.location.href = "task.php";
}
}
xmlHttp.open("POST", "../Controller.php");
xmlHttp.send(formData);
}
Part of PHP controller
case 27:
$array = json_encode($_SESSION);
echo $array;
break;

AJAX call with common parameters gives always readyState = 1

I'm writing a ColdFusion application that fills with some HTML content some divs once the corresponding button is clicked.
What happens is that the readyState never goes up from the initial state of 1.
The fact that makes me crazy is that I used the same AJAX code in other modules that work fine.
I tried manually the code in my applet "___AJAX_load_translator.cfm" to see if works correctly (inputting a complete url with parameters and query string) and it works.
I put many alerts in these javascript functions to trace if the url was created correctly, the parameters were formatted correctly and so on. Everything seems fine. This is driving me crazy. The result is the same on FireFox and IE.
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else
if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("No AJAX support.");
return null;
}
}
function setOutput(divID){
if(httpObject.readyState == 4 && httpObject.status == 200){
document.getElementById(divID).innerHTML = httpObject.responseText;
} // else alert(httpObject.readyState + ' ' + httpObject.status);
}
function loadeditor(divID,CP,PP){
<CFOUTPUT>var CF_TOKENS = "CFID=#CFID#&CFTOKEN=#CFTOKEN#";</CFOUTPUT>
var operativeurl= "___AJAX_load_translator.cfm?"+CF_TOKENS+"&CP="+CP+"&PP="+PP;
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("POST", operativeurl, true);
httpObject.onreadystatechange = setOutput(divID);
httpObject.send(null);
}
}
I noticed that, putting an alert into the setOutput function, it displays a sudden readystate of 1. Then the browser statusbar shows the status of wait for a call to the server, that disappears quite immediately. It seems that the call is really done in that moment, and probably it is imho.
But it seems to me that after that readyness of the call (state 1) there is no more proceeding. It seems somehow blocked. Or, the function setOutput is deactivated. Maybe a second change to a state of 4 happens and this state is not registered by the callback ? In this case, why the DIV is not updated with the new content ?
Thanks for any help.
httpObject.onreadystatechange = setOutput(divID);
^^^^^^^
You're calling/executing your setouput function right then and there, and whatever the function returns becomes on the onreadystatechange callback "pointer".
Remove the (divID) portion, so you assign the function itself, not whatever it returns:
httpObject.onreadystatechange = setOutput;

POST to PHP using AJAX and refresh upon change

I am trying to build a web application that needs to refresh the entire page when there is a change in the database. I would like to achieve this using AJAX and PHP. I would like to POST a single piece of information to the PHP script every 5 seconds and if the returned value from the PHP script is different from a predefined variable, I would like to refresh the entire page.
For example, I have a predefined value in javascript of 200. If the PHP script returns a different value, I would like to refresh the entire page.
I know how to write the PHP, it is just the XJAX I am having issues with. I would also not like to use jquery if possible.
Thanks in advance for any guidance!
EDIT : I would not like to use jquery or any other framework, just raw javascript. I also need to refresh the entire page upon change and run the AJAX every 5 seconds.
Good question. You can do if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") { to check if the PHP-side value has changed. This watchdog method is called very 5 seconds through setInterval. If there is a change, then the page is refreshed via document.location.reload(true) (ref) to prevent reusing the cache.
function watchdog() {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// This is how you can discover a server-side change
if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
document.location.reload(true); // Don't reuse cache
}
}
};
xmlhttp.open("POST","page.php",true);
xmlhttp.send();
}
// Call watchdog() every 5 seconds
setInterval(function(){ watchdog(); }, 5000);
Note: I chose setInterval over setTimeout because if the connection to the server fails (500-error, timeout, etc.), then the response logic may otherwise fail to trigger another setTimeout. setInterval ensures the server is polled consistently regardless of connection failures.
Your AJAX can be executed every 5 seconds using the setInterval() function.
And you can call to refresh the page from AJAX request completion callback.
Please try below code. I have used javascript setInterval function which will make ajax call every 5 seconds. Now please make efforts to make changes in code as per your requirements and take it further.
<script type="text/javascript" >
var predefined_val = 'test';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"test/test_script.php", //put relative url here, script which will return php
data:{}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
// action you want to perform on value changes.
}
}
});
},5000);// function will run every 5 seconds
}));
</script>

Autorefresh a .gsp in Grails when a database table changes

What I have:
- A database table called 'orders' that is constantly populated by some java module on the back-end.
- A website running on Grails that displays those orders. More precisely - a list.gsp in the Orders view.
- the list.gsp will display new orders if the refresh button is pressed on the browser.
What I need:
- Some way for the .gsp page on a client to get refreshed automatically when a new order is placed on the database.
- The autorefresh needs only to autorefresh the .gsp page when the client is already in the .gsp page. i.e. if a client is on the show.gsp for a particular order, then no need for autorefresh.
Things I though might help:
option1: Having a grails service that will periodically (every 5sec.) query the database to see if there are any new orders. If there are, then somehow from the .gsp page call again and re-render the .gsp page ??!
- suboption1-1: create and destroy a new connection every 5 sec.
- suboption1-2: create and keep a connection alive ... forever
option2: Have the java module that places the orders call a refreshController thru the web and somehow re-render the .gsp page. i.e. Have the refreshController notify all clients currently in the .gsp page that a refresh is needed.
=================================================================================
Follow up:
How can I call a controller from java script?:
function checkDB()
{
t = setTimeout("com.mypackage.DBChecker.checkdbController.checkAction()", 5000)
}
==================================================================================
Follow up 2:
So I almost got what I wanted working except that I can't figure out how to AJAX back to my list.gsp page only part of itself. I dont want to refresh the whole page, but only a division with id="refresh table". i.e. .
I have the following code at the moment that is not working:
<script type="text/javascript">
function checkDB()
{
var xmlhttp;
var xmlDoc;
var x;
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)
{
xmlDoc=xmlhttp.responseText;
x=xmlDoc.getElementsByTagId("refreshTable");
for (i=0;i<x.length;i++)
{
txt = x[i].childNodes[0].nodeValue;
}
document.getElementById("refreshTable").innerHTML=txt;
}
else
{
}
}
xmlhttp.open("GET","http://localhost:8080/Orderlord/checkdb/checkdb",true);
xmlhttp.send();
}
window.load = checkDB();
</script>
=================================================================
Follow up 3:
I succeed in returning only a partial page through my ajax call by copy/paste the div that i wanted to a separate gsp. I dont know how It is working - it's a bit of a magic to me, but everything works, except for when I try to sort the columns of my table. Then, only that partial gsp is rendered on my browser, without the rest of the initial page resulting, in a simple tabulated text page. Also once I end up in that kind of html page - the autorefresh doesnt work anymore, but as long as I will stay in the checkDB list view, the page will refresh every 5 seconds.
...So , how do I fix my problem
Another thing i cant figure out is how to return True/False from a controller to a javascript function in the gsp and how exactly did you have in mind for me to use it?
And lastly, I am currently using 'window.load = timeDB' inside my tag to call the timer function. I tried using , but for some reason I cant get it to work no matter what. Is there something I should keep in mind when using ?
Very lastly: What can I do to simply refresh part of the gsp every 5 sec?
You could take the approach of setting a timer on the page via javascript. You would then invoke a lightweight ajax call from your gsp page back to your controller that would yield a true/false to indicate if you needed a full refresh. This is a fairly simple approach but you would want to be careful that the back end target of the ajax call is optimized as it will be called every 5 seconds for each user on that page. It also generates quite a bit of traffic.
I might explore the publish subscribe plugins from the earlier answer before falling back to this approach, however I have implemented the simple timer / ajax call (in the java struts world) on a medium size website with pretty good results.
What you're explaining is a typical publish - subscribe model.
There are a few plugins in grails that will help you do this. Look at Atmosphere and cometD for this. Both options provide this kind of pub/sub.
If they feel a little too heavy for what you want, you should checkout Pusher and the associated Grails plugin. It is a little nicer because you can just integrate a javascript library in your gsp page and do the push from the server side whenever an order is created. Feels slightly lighter than the 2 libraries above. It uses HTML5 web sockets.
So the following piece of code in my list.gsp did it for me. I decided that just refreshing the 'div id="myDiv"' under question every 5sec it's good enough, otherwise I would have hit the server every 5 seconds anyway since I am querying the database.
<script type="text/javascript">
function ajaxrefresh()
{
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("aaaaaaa")
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
else
{
//alert("state: "+xmlhttp.readyState)
//alert("status: "+xmlhttp.status)
}
}
xmlhttp.open("GET","http://${localHostAddress}:12080/Orderlord/refresh/refreshactiveorders",true);
xmlhttp.send();
var t=setTimeout(ajaxrefresh,5000);
}
window.load = ajaxrefresh();
</script>

Categories

Resources