I find it hard to explain so I'm going to write down my code

test.php

<?php
if ($_GET['value']=="1")
{
    $x='It is working fine';
    exit();
}
?>
<html lang="en">
<head>
<script type="text/javascript" src="ajax.js"></script>    
</head>    
<body>
<form method="post" action="">
<select name="s" onchange="makerequest('test.php?value='+ this.value)">
<option value="">Select One</option>
<option value="1">One</option>    
</select><br/>
<input type="text" id="res" name="res" value="<?php if (isset($x)) echo $x;?>"/><br/>
<input type="submit" name="submit" value="go" />
</form>
</body>
</html>

ajax.js

// Creating the xmlhttp
function makerequest(serverpage)
{
    xmlhttp.open("GET",serverpage);
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        document.getElementById("res").value=xmlhttp.responseText;
    }
    xmlhttp.send(null);
}

When I try to echo $x, nothing happen although, $x is set in the same script (test.php).
What's wrong with this code?

Thanks for the help

Recommended Answers

All 10 Replies

I monkeyed around with your code for a little while, and I can see two problems with your implementation.

1. If your JS code above is truly all that's in the file 'ajax.js', then you never created an XMLHttpRequest object.
2. Once you've loaded the page, PHP will never have another chance to execute, so it's never going to fill in the $x value in that form field.

The simplest thing to make your app work 'as is', is simply to change your 'test.php' file to this:

if ($_GET['value']=="1")
{
echo 'It is working fine';
exit();
}

All I did here was change $x = to echo . This works, and I've tested it.

Also, I added the following line in 'ajax.js' to create the XMLHttpRequest object (works in all browsers except Internet Explorer):

xmlhttp = new XMLHttpRequest();

Let my try to get it right.
When I select (one) from the drop down menu, $x var will be set but the page already has been loaded, there will be no chance to get the $x set (inside the html not php).

I actually wanted to code a birthday consists of 3 drop down menus. Month, day, and year. When the user select let's say Jan, the day menu will contain numbers from 1-31. I mean the day menu will be changed according to the month without refreshing the page by using only PHP and AJAX.
My goal was when the user select a month, I process that selection in PHP and return a value and depending on that value, I populate the day menu.

Is there a way to do that?

By the way, I tried to shorten the ajax.js code. the actual code is pretty much good and working. Thanks anyway for mentioning

I'm taking this as an opportunity to teach myself some JavaScript, so I've been working on this all afternoon. It's not finished, and won't be till Monday, but here's what I've got so far (below). The only thing that doesn't work is emptying the options when you change the month, but so far it almost accomplishes your goal.

Here's 'test.php':

<?php
if ( $_GET['value'] === 0 OR ! empty($_GET['value']) )
{
	$month = (int) $_GET['value'];
	$days = 0;
	$options = '';
	
	switch($month)
	{
		case 0: $days = 31; break;
		case 1: $days = 29; break;
		case 2: $days = 31; break;
		case 3: $days = 30; break;
		case 4: $days = 31; break;
		case 5: $days = 30; break;
		case 6: $days = 31; break;
		case 7: $days = 31; break;
		case 8: $days = 30; break;
		case 9: $days = 31; break;
		case 10: $days = 30; break;
		case 11: $days = 31; break;
	}
	
	for($i = 1; $i <= $days; $i++)
	{
		if($i < $days) {
			$options .= "$i,";
		} else {
			$options .= "$i";
		}
	}
	
	echo $options;
}
?>

and here's the 'ajax.js' file:

xmlhttp = new XMLHttpRequest();

function makerequest(serverpage)
{
	day = document.getElementById('day');

	//code I was working on before stopping
	/*if(day)
	{
		if(day.length > 0)
		{
			for(a = 1; a <= day.length; a++)
			{
				day.remove(a);
			}
		}
	}*/

    xmlhttp.open("GET",serverpage);
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			
			day.setAttribute('style','display:block');
			var preconvoptions = xmlhttp.responseText;
			var options = preconvoptions.split(',');
			
			for(i = 1; i <= options.length; i++)
			{
				var newOpt = document.createElement('option');
				newOpt.text = i;
				newOpt.value = i;
			
				day.add(newOpt, null);

			}

			
			console.log(xmlhttp.responseText);
		}
    }
    xmlhttp.send(null);

}

Finally, here's the index.php (I separated the HTML from the PHP file that generates the request):

<html lang="en">
<head>
<script type="text/javascript" src="ajax.js"></script> 
</head> 
<body>
<form method="post" action="">
<select name="s" onchange="makerequest('test.php?value='+ this.value)">
	<option value="">Select One</option>
	<option value="0">January</option> 
	<option value="1">February</option>
	<option value="2">March</option>
	<option value="3">April</option>
	<option value="4">May</option>
	<option value="5">June</option>
	<option value="6">July</option>
	<option value="7">August</option>
	<option value="8">September</option>
	<option value="9">October</option>
	<option value="10">November</option>
	<option value="11">December</option>
</select>

<br/>
<select id='day' name='day' style="display:none;">
</select>
<input type="submit" name="submit" value="go" />
</form>
</body>
</html>

The steps I go through in this app are as follows:
1. Hide the select option that will receive the number of days
2. When the Month select box changes, send that value to 'test.php' to make a comma-separated list of numbers representing the number of days for the chosen month. Then send back that comma-separated list.
3. Take the response text and convert it to an array using the split method
4. Change the display property of the 'day' select element to block so it's shown
5. Iterate through that array and create the option tags with values and text.

I'm still learning this as well, so I wouldn't recommend just copying and pasting for production. This will hopefully get you on your way. Here's a good page I used in working this out for myself.

Thank you very much for the time and the effort. I'm going to check it out.

Member Avatar for diafol

This can be made to work in just js, without the need for ajax. JS can process the input from the dropdown or select and change the options for the next select. You can avoid involving server.

Let my try to get it right....

You may be overlooking a few things that are important when doing this sort of thing.

  • PHP runs on the server.
  • ECMAScript (JS) runs on the browser.
  • HTML is interpreted by the browser to render the display.
  • There is no 'hidden' communication channel between the server and the browser. Any data to be passed must be passed explicitly and deliberately.

What's this mean? You already know half of the communication: PHP generates HTML with ES embedded. You've forgotten the other half: the browser sends form values to the server via GET (embedded in the URL) or POST (sent in HTTP headers). To get anything sent back to the server, either the user or browser fills and submits a form, or you write an ES program to do it.

If you wanted to, you could write the entire UI in ES (that is, make the entire UI dynamic), and have the PHP generate only minimal HTML. Here the trick would be to build the 'response' URL to pass the info back to the server. But that's not hard, really. Put all your data into an ES associative array and pass that whole array written in PHP syntax as a single string to your response URL. Your PHP program will then be able to access the values without needing to do any special parsing or evaulation. (You already know the reverse part of this: programming your PHP to prepare ES variables that are ready to use.) Just note that while the PHP and ES array syntaces are similar and a complex array can be made using a single string, the two languages are different, sometimes in subtle ways.

Member Avatar for diafol

I use the prototype js library to handle most of my ajax calls. This just helps to avoid the browser-specific issues like the ActiveX object (IE) vs. all the others and you can use nifty shorthand for form and tag elements. JQuery is similar.

But as I mentioned JS (or ES, as called by Fest3er) could handle the whole lot. You're not actually dragging anything from a database or external store, so anything you're producing by your php script, you could effectively produce by JS alone. Of course, using pHp looks neater and you can actually mix areas of php and raw html in that file, but JS still has to grab hold of the ajax 'response' and parse it as a string to the appropriate place on your page.

JS supports the switch statement (just like php), so using this for recognising the month is straight forward.

My own solution:

1. onchange="makerequest();return false;" Notice there is no need to include a parameter because the makerequest function will pick this up from the document.getElementById('s') value.

2. Change the function makerequest(serverpage) to function makerequest() 3. Get the document.getElementById('s').value and check it in your switch code

4. Your switch code will return the innards of the day dropdown.

5. Write this to the document.getElementById('day').innerHTML property

(also ensure that the style way set to something else other than 'display:none' )

Job pretty much done - no php.

I agree with ardav. Pulling predictable static numerical data from a server does not make sense. Javascript can generate that. If, on the other hand, you need to retrieve some data from a database (or a file on the server) in order to fill in the secondary combobox, AJAX makes sense. Otherwise you are needlessly wasting bandwidth, which is not a big deal in a small or local setting. But if you expect major traffic, you need to minimize your server requests in order to cope :-)

Thanks guys for all the replies. I really appreciate it.
I'm going to use JS without involving PHP

Member Avatar for diafol

Cool. If the thread is finished, please mark it as Solved (click the link).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.