| | |
Return var from ajax to PHP
Please support our PHP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
•
•
Join Date: Nov 2004
Posts: 19
Reputation:
Solved Threads: 0
I find it hard to explain so I'm going to write down my code
test.php
ajax.js
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
test.php
php Syntax (Toggle Plain Text)
<?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
JavaScript Syntax (Toggle Plain Text)
// 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
Last edited by peter_budo; Jul 17th, 2009 at 3:03 pm. Reason: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks) and [icode] (inline code) tags.
•
•
Join Date: Jan 2008
Posts: 28
Reputation:
Solved Threads: 8
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
The simplest thing to make your app work 'as is', is simply to change your 'test.php' file to this:
All I did here was change
Also, I added the following line in 'ajax.js' to create the XMLHttpRequest object (works in all browsers except Internet Explorer):
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:
PHP Syntax (Toggle Plain Text)
if ($_GET['value']=="1") { echo 'It is working fine'; exit(); }
$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):
JavaScript Syntax (Toggle Plain Text)
xmlhttp = new XMLHttpRequest();
Last edited by jcacquiescent27; Jul 17th, 2009 at 3:31 pm.
•
•
Join Date: Nov 2004
Posts: 19
Reputation:
Solved Threads: 0
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
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
•
•
Join Date: Jan 2008
Posts: 28
Reputation:
Solved Threads: 8
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':
and here's the 'ajax.js' file:
Finally, here's the index.php (I separated the HTML from the PHP file that generates the request):
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
4. Change the
5. Iterate through that array and create the
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.
Here's 'test.php':
PHP Syntax (Toggle Plain Text)
<?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:
JavaScript Syntax (Toggle Plain Text)
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 Syntax (Toggle Plain Text)
<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 method4. Change the
display property of the 'day' select element to block so it's shown5. 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.
Last edited by jcacquiescent27; Jul 17th, 2009 at 6:44 pm.
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.
"...the woods would be a very silent place if no birds sang except for the best"
All opinions count.
F'enw i yw Mr. Blaidd. Byddwch yn ofalus - dwi'n cnoi.
All opinions count.
F'enw i yw Mr. Blaidd. Byddwch yn ofalus - dwi'n cnoi.
•
•
Join Date: Aug 2007
Posts: 165
Reputation:
Solved Threads: 18
You may be overlooking a few things that are important when doing this sort of thing.
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.
- 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.
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.
2. Change the
3. Get the
4. Your switch code will return the innards of the day dropdown.
5. Write this to the
(also ensure that the style way set to something else other than
Job pretty much done - no php.
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 code4. 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.
"...the woods would be a very silent place if no birds sang except for the best"
All opinions count.
F'enw i yw Mr. Blaidd. Byddwch yn ofalus - dwi'n cnoi.
All opinions count.
F'enw i yw Mr. Blaidd. Byddwch yn ofalus - dwi'n cnoi.
•
•
Join Date: Feb 2009
Posts: 9
Reputation:
Solved Threads: 6
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 :-)
![]() |
Similar Threads
- AJAX PHP multiple dropdown (JavaScript / DHTML / AJAX)
- Using AJAX and PHP Resources and Tutorial (JavaScript / DHTML / AJAX)
- Software Developer ( AJAX / PHP ) (Web Development Job Offers)
- AJAX & PHP Developer ( Full Time ) (Web Development Job Offers)
- Software Engineer ( AJAX / PHP ) (Software Development Job Offers)
- Hint Box using Ajax with Php (JavaScript / DHTML / AJAX)
- AJAX And PHP (PHP)
- Auto fill textbox using ajax in php (PHP)
Other Threads in the PHP Forum
- Previous Thread: Need help with mysql select statement and checkboxes
- Next Thread: http://www.xyz.com/?id=1 style URL
| Thread Tools | Search this Thread |
.htaccess alerts apache api archive array autocomplete beginner binary broken cakephp checkbox class cms code convert cron curl database dataentry date display duplicates dynamic echo email emptydisplayvalue error execute explodefunction file files firstoptioninphpdroplist folder form forms function functions google hack href htaccess html htmlspecialchars image include insert ip javasciptvalidation javascript joomla keywords limit link login mail matching menu methods mlm multiple mysql network object oop paypal pdf php problem query radio random recursion recursive redirect remote script search securephp server sessions shot sms source space sql subscription syntax system table tutorial tutorials update upload url validator variable video web youtube





