943,754 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Unsolved
  • Views: 930
  • PHP RSS
You are currently viewing page 1 of this multi-page discussion thread
Jul 17th, 2009
0

Return var from ajax to PHP

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

test.php
php Syntax (Toggle Plain Text)
  1. <?php
  2. if ($_GET['value']=="1")
  3. {
  4. $x='It is working fine';
  5. exit();
  6. }
  7. ?>
  8. <html lang="en">
  9. <head>
  10. <script type="text/javascript" src="ajax.js"></script>
  11. </head>
  12. <body>
  13. <form method="post" action="">
  14. <select name="s" onchange="makerequest('test.php?value='+ this.value)">
  15. <option value="">Select One</option>
  16. <option value="1">One</option>
  17. </select><br/>
  18. <input type="text" id="res" name="res" value="<?php if (isset($x)) echo $x;?>"/><br/>
  19. <input type="submit" name="submit" value="go" />
  20. </form>
  21. </body>
  22. </html>

ajax.js
JavaScript Syntax (Toggle Plain Text)
  1. // Creating the xmlhttp
  2. function makerequest(serverpage)
  3. {
  4. xmlhttp.open("GET",serverpage);
  5. xmlhttp.onreadystatechange=function()
  6. {
  7. if (xmlhttp.readyState==4 && xmlhttp.status==200)
  8. document.getElementById("res").value=xmlhttp.responseText;
  9. }
  10. xmlhttp.send(null);
  11. }

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.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
codemaker is offline Offline
20 posts
since Nov 2004
Jul 17th, 2009
0

Re: Return var from ajax to PHP

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:
PHP Syntax (Toggle Plain Text)
  1. if ($_GET['value']=="1")
  2. {
  3. echo 'It is working fine';
  4. exit();
  5. }
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):
JavaScript Syntax (Toggle Plain Text)
  1. xmlhttp = new XMLHttpRequest();
Last edited by jcacquiescent27; Jul 17th, 2009 at 3:31 pm.
Reputation Points: 10
Solved Threads: 8
Light Poster
jcacquiescent27 is offline Offline
28 posts
since Jan 2008
Jul 17th, 2009
0

Re: Return var from ajax to PHP

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
Reputation Points: 10
Solved Threads: 0
Newbie Poster
codemaker is offline Offline
20 posts
since Nov 2004
Jul 17th, 2009
0

Re: Return var from ajax to PHP

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 Syntax (Toggle Plain Text)
  1. <?php
  2. if ( $_GET['value'] === 0 OR ! empty($_GET['value']) )
  3. {
  4. $month = (int) $_GET['value'];
  5. $days = 0;
  6. $options = '';
  7.  
  8. switch($month)
  9. {
  10. case 0: $days = 31; break;
  11. case 1: $days = 29; break;
  12. case 2: $days = 31; break;
  13. case 3: $days = 30; break;
  14. case 4: $days = 31; break;
  15. case 5: $days = 30; break;
  16. case 6: $days = 31; break;
  17. case 7: $days = 31; break;
  18. case 8: $days = 30; break;
  19. case 9: $days = 31; break;
  20. case 10: $days = 30; break;
  21. case 11: $days = 31; break;
  22. }
  23.  
  24. for($i = 1; $i <= $days; $i++)
  25. {
  26. if($i < $days) {
  27. $options .= "$i,";
  28. } else {
  29. $options .= "$i";
  30. }
  31. }
  32.  
  33. echo $options;
  34. }
  35. ?>

and here's the 'ajax.js' file:
JavaScript Syntax (Toggle Plain Text)
  1. xmlhttp = new XMLHttpRequest();
  2.  
  3. function makerequest(serverpage)
  4. {
  5. day = document.getElementById('day');
  6.  
  7. //code I was working on before stopping
  8. /*if(day)
  9. {
  10. if(day.length > 0)
  11. {
  12. for(a = 1; a <= day.length; a++)
  13. {
  14. day.remove(a);
  15. }
  16. }
  17. }*/
  18.  
  19. xmlhttp.open("GET",serverpage);
  20. xmlhttp.onreadystatechange=function()
  21. {
  22. if (xmlhttp.readyState==4 && xmlhttp.status==200) {
  23.  
  24. day.setAttribute('style','display:block');
  25. var preconvoptions = xmlhttp.responseText;
  26. var options = preconvoptions.split(',');
  27.  
  28. for(i = 1; i <= options.length; i++)
  29. {
  30. var newOpt = document.createElement('option');
  31. newOpt.text = i;
  32. newOpt.value = i;
  33.  
  34. day.add(newOpt, null);
  35.  
  36. }
  37.  
  38.  
  39. console.log(xmlhttp.responseText);
  40. }
  41. }
  42. xmlhttp.send(null);
  43.  
  44. }

Finally, here's the index.php (I separated the HTML from the PHP file that generates the request):
HTML Syntax (Toggle Plain Text)
  1. <html lang="en">
  2. <head>
  3. <script type="text/javascript" src="ajax.js"></script>
  4. </head>
  5. <body>
  6. <form method="post" action="">
  7. <select name="s" onchange="makerequest('test.php?value='+ this.value)">
  8. <option value="">Select One</option>
  9. <option value="0">January</option>
  10. <option value="1">February</option>
  11. <option value="2">March</option>
  12. <option value="3">April</option>
  13. <option value="4">May</option>
  14. <option value="5">June</option>
  15. <option value="6">July</option>
  16. <option value="7">August</option>
  17. <option value="8">September</option>
  18. <option value="9">October</option>
  19. <option value="10">November</option>
  20. <option value="11">December</option>
  21. </select>
  22.  
  23. <br/>
  24. <select id='day' name='day' style="display:none;">
  25. </select>
  26. <input type="submit" name="submit" value="go" />
  27. </form>
  28. </body>
  29. </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.
Last edited by jcacquiescent27; Jul 17th, 2009 at 6:44 pm.
Reputation Points: 10
Solved Threads: 8
Light Poster
jcacquiescent27 is offline Offline
28 posts
since Jan 2008
Jul 17th, 2009
0

Re: Return var from ajax to PHP

Thank you very much for the time and the effort. I'm going to check it out.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
codemaker is offline Offline
20 posts
since Nov 2004
Jul 17th, 2009
0

Re: Return var from ajax to PHP

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.
Sponsor
Featured Poster
Reputation Points: 1048
Solved Threads: 946
Sarcastic Poster
ardav is offline Offline
6,678 posts
since Oct 2006
Jul 18th, 2009
0

Re: Return var from ajax to PHP

Click to Expand / Collapse  Quote originally posted by codemaker ...
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.
Reputation Points: 51
Solved Threads: 35
Posting Whiz in Training
Fest3er is offline Offline
238 posts
since Aug 2007
Jul 18th, 2009
0

Re: Return var from ajax to PHP

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.
Sponsor
Featured Poster
Reputation Points: 1048
Solved Threads: 946
Sarcastic Poster
ardav is offline Offline
6,678 posts
since Oct 2006
Jul 18th, 2009
0

Re: Return var from ajax to 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 :-)
Reputation Points: 10
Solved Threads: 9
Light Poster
kokoro90 is offline Offline
25 posts
since Feb 2009
Jul 21st, 2009
0

Re: Return var from ajax to PHP

Thanks guys for all the replies. I really appreciate it.
I'm going to use JS without involving PHP
Reputation Points: 10
Solved Threads: 0
Newbie Poster
codemaker is offline Offline
20 posts
since Nov 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: Need help with mysql select statement and checkboxes
Next Thread in PHP Forum Timeline: http://www.xyz.com/?id=1 style URL





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC