• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 188
  • Last Modified:

AJAX request only works when containing an alert();

The intent is to set the value of $_SESSION['travel2']

I want to be able to remove the alert(), but the function does not perform the AJAX request without it. (It is a simple session variable setting) Live HTTP Headers confirms the AJAX request not sending. I'm really stumped. Please offer ideas. Thanks

Function definition (remove the alert and it stops functioning)
<script type="text/javascript">
function add_ses_var(a)
{
	var xmlhttp = false;
	if (window.XMLHttpRequest)		// IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else							// IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.open("GET","session_var.php?p="+a,true);
	xmlhttp.send();
	alert("Getting Request");
}
</script>

Open in new window

session_var.php
<?php
session_start ( );
if ( !empty ( $_GET['p'] ) )
{
	$v = $_GET['p'];
	$_SESSION[$v] = 'good';
}
?>

Open in new window

Sent with this form button
<input class="btn" type="submit" value=" Do-it For Me " onclick="add_ses_var('travel2')" />

Open in new window

0
dolan2go
Asked:
dolan2go
  • 10
  • 4
  • 4
  • +1
4 Solutions
 
Dave BaldwinFixer of ProblemsCommented:
'GET's can be cached by the browser.  A way around that is to add a random number parameter to the URL so it is different every time.

http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
xmlhttp.open("GET","session_var.php?p="+a+"&t=" + Math.random(),true);
xmlhttp.send();

Open in new window

0
 
varontronCommented:
Hi,

Assuming your 'input' tag is in a form, possibly your form is being submitted before the onclick handler fires?

What is the form action?  Is it possible to chain the call to 'session_var.php' in the form action?  You can redirect the form action to a js function that calls 'add_ses_var' and then submits.

You could also change the input type to 'button' and submit the form with a callback in the xmlhttprequest.

You could also find another action on the form to call 'add_ses_var', so it's not coupled to form submission.  

These things are much easier with jquery.  Have you ruled that out?

Hope this helps,
Dave
0
 
dolan2goAuthor Commented:
Dave,

Thanks. I had tried that. It works for one time then returns to not sending the AJAX request.

I may switch to POST, but would like to understand this GET.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
dolan2goAuthor Commented:
Oops. Kinda confusing here. 2 Daves & a David

Last reply was to DaveBaldwin.

@varontron

The form action:
<form class="form" method="post" action="travel_easy2.php" autocorrect="off" autocapitalize="off">

Open in new window


Let me give the 'button' idea a try.

For now, I'm not keen on learning jQuery also.
0
 
dolan2goAuthor Commented:
1) Changing to 'button' from 'submit', doesn't cause the function to be called.
<input class="btn" type="button" value=" Do-it For Me " onclick="add_ses_var('travel2')" />

Open in new window


2) Neither does adding it to the form tag.
<form class="form" method="post" action="travel_easy2.php" onsubmit="add_ses_var('travel2')" autocorrect="off" autocapitalize="off">

Open in new window


This is a 'bit' over my head. Hence the request for help.
0
 
dolan2goAuthor Commented:
With the original source code (minus the alert), the AJAX is being sent, just a few seconds AFTER travel_easy2.php.

So the session variable is being set too late.
0
 
experts1Commented:
Try replacing the Alert message, with a window status message as below:

window.status="Getting Request"

Your function should work fine with above filler instruction which
is not such a nuisance as he alert message.

0
 
varontronCommented:
Your last comment about the order of requests indicates the form submission is occurring when you click submit, and is being processed before the onclick.

To prevent a form submission, the form's onsubmit handler should return false, but that is not entirely what you want.  You want the form to submit after returning the session var. Your comment putting add_ses_var in the onsubmit is close.

So, modify 'add_ses_var' to include a callback function for xmlhttprequest.  On success, return true.  That will submit the form.  This function should otherwise return false to suppress form submission if the session var is not set.  When doing ajax "by hand" this is done with the onreadystatechange field.  I.e.:

<script>
function add_ses_var(a)
{
	var xmlhttp = false;
	if (window.XMLHttpRequest)		// IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else							// IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.open("GET","session_var.php?p="+a,true);
	xmlhttp.send();
	xmlhttp.onreadystatechange = function() {
           if (xmlhttp.readyState != 4)  { return false; }
           // add code here to check if the xmlhttp.responseText is valid before returning true
           return true;
           };
        return false;
}


}
...
</script>
<form ... onsubmit="add_ses_var('travel_2')">

Open in new window


I think that'll do it.

Dave
0
 
dolan2goAuthor Commented:
@experts1,

Thank you for the suggestion. I am searching for a more elegant solution.

@varontron,

Great explanation. Thank you.

When mentioning 'by hand', are you implying writing AJAX this way and jQuery is the more 'automated'?

Please allow a bit of time for testing and response.
0
 
dolan2goAuthor Commented:
Still not working.... The function must be returning 'false'.

Using varantron's example (minus one unclosed curly brace), the function is being called, but no ajax request reported by Live Headers or a session variable being set. As it stands now, the code:
<script type="text/javascript">
function add_ses_var(a)
{
    alert("Request Sent");
	var xmlhttp = false;
	if (window.XMLHttpRequest)		// IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else							// IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.open("GET","session_var.php?p="+a,true);
	xmlhttp.send();
	xmlhttp.onreadystatechange = function() {
           if (xmlhttp.readyState != 4)  { return false; }
           // add code here to check if the xmlhttp.responseText is valid before returning true
           return true;
           };
        return false;
}
</script>

Open in new window

<form class="form" method="post" action="travel_easy2.php" onsubmit="add_ses_var('travel2')" autocorrect="off" autocapitalize="off">

Open in new window

0
 
experts1Commented:
My guess is that the AJAX query expects some action
to be taken after data is returned!
0
 
varontronCommented:
sorry about the bracket :(

try putting the form submission into the callback and add a name to the form, and a return statement to the onsubmit declaration.

Also, try these things:  1) comment out the 'return false;' in the onreadystatechange function.  it may be calling that early, before the reponse returns.  2) uncomment the 'return false;' in the that function, but change the 3rd argument to 'open' to false to make the request synchronous.  You may have to do that anyway, if the form submission keeps happening before the session var is set.  3) you can also add an error handler to the check bad responses, once the request starts working.

<script type="text/javascript">
function add_ses_var(a)
{
    alert("Request Sent");
	var xmlhttp = false;
	if (window.XMLHttpRequest)		// IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	else							// IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	xmlhttp.open("GET","session_var.php?p="+a,true);
	xmlhttp.send();
	xmlhttp.onreadystatechange = function() {
           if (xmlhttp.readyState != 4)  { return false; }
           // add code here to check if the xmlhttp.responseText is valid before returning true
           // new code here
           document.foo.submit();
           return true;
           };
        return false;
}
</script>

Open in new window


<form name="foo" class="form" method="post" action="travel_easy2.php" onsubmit="add_ses_var('travel2');return false;" autocorrect="off" autocapitalize="off">

Open in new window

0
 
dolan2goAuthor Commented:

try putting the form submission into the callback and add a name to the form, and a return statement to the onsubmit declaration.

Don't know why, but that did it. The variable has been repeatedly & consistently set.

What does 'document.foo.submit();' in the function do?

@experts1: Is this what your're suggesting?

My guess is that the AJAX query expects some action
to be taken after data is returned!
0
 
experts1Commented:
Yep!
0
 
dolan2goAuthor Commented:
So, is that the ONLY way to fool the function into doing it's task?

Adding the extra code doesn't seem clean. It's appears to be fake / unnecessary code. Well, necessary to get the function working, but overall, not so....
0
 
experts1Commented:
I agree with you 100%, but sometimes we just make it work and move on!
0
 
dolan2goAuthor Commented:
I was hoping for some 'expert' understanding that might wrap back around to answering the original question and helping me gain good coding practices.
0
 
varontronCommented:
I'm not sure _exactly_ why this happens, however I can offer this.  DOM elements have default handlers which, unless overridden will do what they are supposed to.  Returning false from a custom handler (like you do with the 'onsubmit' attribute value, is a typical way to defeat the default, and to branch processing.

In your scenario, you are diverting the submit button behavior to send an xmlhttprequest (xhr).  The xhr, being asynchronous, will run it's own course and return control back to the normal flow as soon as it is called, rather than when it returns.  You want to tell the form to submit eventually, so you have 2 choices,  call submit from the callback in the xhr, or set the xhr to be synchronous (with the 'false' arg3 to 'xhr.open') and then call form submission a separate function.

You have other options which you may prefer, like passing the session var value into the page with the initial response, or if it's form dependent, calling the var setting function with a rollover or blur on another element.  That could decouple it from submit.  Doing it the way you've got it working now is not uncommon.  Your intuition may be right though that decoupling is better, so you can reuse the function elsewhere.  If you only use it on forms, you could always just pass the form name as an arg as well.

Glad it's working.
Dave
0
 
dolan2goAuthor Commented:
Thanks to you both for your comments.

It may not be a common idea, but solutions are best when explanations are provided. With a question often comes a low level of understanding, and a desire to learn the best, if not correct, answer.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 10
  • 4
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now