Link to home
Start Free TrialLog in
Avatar of dolan2go
dolan2goFlag for United States of America

asked on

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

Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

'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

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
Avatar of dolan2go

ASKER

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.
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.
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.
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.
SOLUTION
Avatar of experts1
experts1

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@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.
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

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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


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!
Avatar of experts1
experts1

Yep!
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....
I agree with you 100%, but sometimes we just make it work and move on!
I was hoping for some 'expert' understanding that might wrap back around to answering the original question and helping me gain good coding practices.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.