SitePoint Sponsor

User Tag List

Results 1 to 22 of 22
  1. #1
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Display other data based on dropdown selection

    OK, I have searched the internet and here and have not found what I need.

    I am a noob to javascipt/java so need a LOT of help.

    What I have is a form to update meeting places with certain data. The data for the meeting place is from a MySQL table and that table has the place, address, city, state, zip. So I need to have the address, city, state, zip changed based on the dropdown of the meeting place. My current code is below (and includes other things).

    Code:
    <?php
    	session_start();
    
    		include 'db_connect.php';
    		
    			
    	if ($_SERVER['REQUEST_METHOD'] == 'POST') 
      { 
        $task = isset($_POST['task']) ? $_POST['task'] : false; 
         if ($task == "Register") {
          $formValues = $_POST; 
          $formErrors = array();  
          if (!VerifyForm($formValues, $formErrors)) 
          DisplayForm($formValues, $formErrors); 
          else     {
    //        echo 'Processing form' ;
            ProcessForm($formValues);     }
          }
          else if ($task == 'ReturnToMainPage')   
            header('Location: index.php');
      }  
      else 
      {
    
        DisplayForm(null, null);
    }
    
    
    function DisplayForm($values, $errors) 
    { ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>SACCC Meeting Information Change</title>
    <link rel="stylesheet" type="text/css" href="view.css" media="all">
    <script type="text/javascript" src="view.js"></script>
    <script type="text/javascript" src="calendar.js"></script>
    </head>
    <body id="main_body" >
    
    	<img id="top" src="top.png" alt="">
    	<div id="form_container">
    	
    		<h1><a> Meeting Information Change</a></h1>
    		<form id="form_754506" class="appnitro"  method="post" action="">
    					<div class="form_description">
    			<h2>Meeting Information Change</h2>
    			<p>Use this form to change the Monthly Meeting information.</p>
    		</div>						
    		<ul >		
    			</li>		<li id="li_4" >
    			<label class="description" for="element_4">Meeting Place </label>
    			<div>
    				<input id="element_4" name="element_4" class="element text medium" type="text" maxlength="255" value=""/> 
    			</div> 
    			</li>		
    			<li id="li_5" >
    			<label class="description" for="element_5">Meeting Address </label>
    			
    			<div>
    				<input id="element_5_1" name="element_5_1" class="element text large" value="" type="text">
    				<label for="element_5_1">Street Address</label>
    			</div>
    		
    			<div>
    			<span style="float:left">
    				<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" value="" type="text">
    				<label for="element_5_3">City</label>
    			</span>
    			<span style="float:left">
    				<select id="element_5_4" name="element_5_4" class="element text medium" style="width:3.5em"  maxlength="2" value="" type="text">
    				<label for="element_5_4">State</label>
    				</select>
    			</span>
    			<span style="float:left">
    				<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" maxlength="5" value="" type="text">
    				<label for="element_5_5">Zip Code</label>
    				</span>
    			</div>
    		
    			</li>		
    			
    				
    			<li class="buttons">
    				<input type="hidden" name="form_id" value="754506" />
    				<input id="saveForm" method="post" class="button_text" type="submit" name="addNew" value="Add New" action="<?= $_SERVER['PHP_SELF'] ?>"/>
    				<input id="saveForm" method="post" class="button_text" type="submit" name="submit" value="Submit" action="<?= $_SERVER['PHP_SELF'] ?>"/>
    			</li>
    		</ul>
    		</form>	
    		<?php }
    		?>		
    	</div>
    	<img id="bottom" src="bottom.png" alt="">
    	</body>
    </html>
    So, I assume I need some kind of javascript to be triggered when the dropdown place box changes. Right? And what is that code since I don't know javascript.

    Thanks
    F

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    I think the best way to do this is to attach an onchange event handler to your select element, then have it fire off an AJAX request to your PHP script every time the user selects something.
    The PHP script can then fetch whatever it needs from the database and return it to the JavaScript which can then insert it into the page.

  3. #3
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    I think the best way to do this is to attach an onchange event handler to your select element, then have it fire off an AJAX request to your PHP script every time the user selects something.
    The PHP script can then fetch whatever it needs from the database and return it to the JavaScript which can then insert it into the page.
    OK, I think that approach would work but since my knowledge of this is, well, non-existent so far and I know this is asking a lot, but could you give me the code as to how it would work?

    Thanks

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by fredep57 View Post
    could you give me the code as to how it would work?
    Lol. Nice try.
    I won't just write the whole thing for you, but I don't mind demonstrating how the principle works, so that you can apply it to your site.
    This way, if you need to make any changes further down the line, you'll be able to make them on your own.

    Sound like a plan?

  5. #5
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    Lol. Nice try.
    I won't just write the whole thing for you, but I don't mind demonstrating how the principle works, so that you can apply it to your site.
    This way, if you need to make any changes further down the line, you'll be able to make them on your own.

    Sound like a plan?

    Ah, was worth a try. And, yes, please demo the principles so I can get some more knowledge. If I don't understand, I will comment as such, OK?

  6. #6
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Okay then. In light of this statement:

    Quote Originally Posted by fredep57 View Post
    my knowledge of this is, well, non-existent
    let's use the jQuery library, as this will simplify the syntax of what we want to do considerably.

    You include it in your page like this:

    Code:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    This will pull in the most recent minified version of the 1.x branch of the library.

    Then we need a select. I was about to say, let's use yours, but there doesn't appear to be one in the code you posted above.
    What do you mean by "the dropdown of the meeting place"?

    Let's use a select anyway, we can change it if it isn't correct:

    Code:
    <label for="meetingPlace">Meeting place: </label>
    <select id="meetingPlace">
      <option>Please select</option>
      <option>Buckingham Palace</option>
      <option>The White House</option>
      <option>Mount Everest</option>
    </select>
    With that in place we need to hook into the select's on change event.
    We can do this in our JavaScript:

    Code:
    $("#meetingPlace").on("change", function(){
      // This code will fire every time the user selects something
    })
    All this does is select the element with an id of "#meetingPlace" and declare an anonymous function which should be run every time the user selects something different.

    As a final step for this post, let's have the JS output what the user selected to the page.

    Create a div with an id of "results":

    Code:
    <div id="results"></div>
    Then within the onchange callback add the following code:

    Code:
    var selected = $(this).val();
    $("#results").html("You selected: " + selected);
    What this does is assign the value of the selected option element to a variable, then set the innerHTML of the results <div> accordingly.

    Note: we haven't actually specifed a value for the options tags, so jQuery defaults to the selected text instead.
    Setting a value would be: <option value="Buck House">Buckingham Palace</option>
    And this would cause our script to output "You selected: Buck House".

    Here's the whole code.

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Select - onchange example</title>
      </head>
      
      <body>
        <label for="meetingPlace">Meeting place: </label>
        <select id="meetingPlace">
          <option>Please select</option>
          <option>Buckingham Palace</option>
          <option>The White House</option>
          <option>Mount Everest</option>
        </select>
        <div id="results"></div>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
          $("#meetingPlace").on("change", function(){
            var selected = $(this).val();
            $("#results").html("You selected: " + selected);
          })
        </script>
      </body>
    </html>
    Have a look at that, try and understand what is going on, then let me know if you have any questions.
    If you don't, we'll move on to contacting the server from within our JS as a second step.

  7. #7
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK,I think I understand. No matter what you select in the SELECT statement, the js will put the "results" in the div called "results".

    So, now on to the next step please. Am really awaiting how to the the DB info into these areas.

  8. #8
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    OK, well the next step involves firing off an AJAX request every time the user selects something in the dropdown.

    We'll start off by adding value attributes to the option tags:

    Code:
    <select id="meetingPlace">
      <option value="">Please select</option>
      <option value="buckingham-palace">Buckingham Palace</option>
      <option value="white-house">The White House</option>
      <option value="mount-everest">Mount Everest</option>
    </select>
    Then in the onchange callback change the code as follows:

    Code:
    $("#meetingPlace").on("change", function(){
      var selected = $(this).val();
      makeAjaxRequest(selected);
    });
    Now we have to define the makeAjaxRequest function, where we can use jQuery's $.ajax() method to contact the server:

    Code:
    function makeAjaxRequest(opts){
      $.ajax({
        type: "POST",
        data: { opts: opts },
        url: "process_ajax.php",
        success: function(res) {
          // We'll put some code here in a minute
        }
      });
    }
    What this does is to POST any data it is passed to the file process_ajax.php.
    The success callback is executed if the AJAX request is successful.
    We'll come to that in a minute.

    Let's hop into process_ajax.php.
    All we'll do here is output the contents of the $_POST array, but in reality, this is where your database queries and so would go, before returning the appropriate results:

    Code:
    <?php 
      // Database logic here
    
      echo '<pre>'; 
      print_r($_POST);
      echo '</pre>';
    ?>
    Then in the success callback, we'll insert the server's response into the results div:

    Code:
    $("#results").html("<p>$_POST contained: " + res + "</p>");
    And there you go, that's all there is to it

    index.html:
    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Select - onchange AJAX example</title>
      </head>
    
      <body>
        <label for="meetingPlace">Meeting place: </label>
        <select id="meetingPlace">
          <option value="">Please select</option>
          <option value="buckingham-palace">Buckingham Palace</option>
          <option value="white-house">The White House</option>
          <option value="mount-everest">Mount Everest</option>
        </select>
        <div id="results"></div>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
          function makeAjaxRequest(opts){
            $.ajax({
              type: "POST",
              data: { opts: opts },
              url: "process_ajax.php",
              success: function(res) {
                $("#results").html("<p>$_POST contained: " + res + "</p>");
              }
            });
          }
    
          $("#meetingPlace").on("change", function(){
            var selected = $(this).val();
            makeAjaxRequest(selected);
          });
        </script>
      </body>
    </html>
    process_ajax.php:
    Code:
    <?php 
      // Database logic here
    
      echo '<pre>'; 
      print_r($_POST);
      echo '</pre>';
    ?>
    Last edited by Pullo; Dec 15, 2013 at 15:06. Reason: Typo

  9. #9
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK, now I might be confused - but most say I am that by nature.

    First, in my page, I fill the "<option>" areas from the same database that has the address, etc. So, how do I pass the "link" to the database to the "process_ajax.php" module?

    Second, depending on your answer to the first question, what really is the best way to handle this?

    Last, how do I use the information to post to my database?

    Thanks

  10. #10
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Quote Originally Posted by fredep57 View Post
    OK, now I might be confused - but most say I am that by nature.
    No probs

    Quote Originally Posted by fredep57 View Post
    First, in my page, I fill the "<option>" areas from the same database that has the address, etc. So, how do I pass the "link" to the database to the "process_ajax.php" module?
    I'm not sure I understand.
    As far as the JS is concerned, it doesn't matter where you fill the option tags from.
    Main thing is that they exist in the DOM when the JS executes.

    Quote Originally Posted by fredep57 View Post
    Second, depending on your answer to the first question, what really is the best way to handle this?
    Again, I'm not sure I follow.
    What you want to do, is have "process_ajax.php" extract whatever parameters it needs from the $_POST array, build a db query, execute it and then echo the (relevant parts of the) results back to your original page.
    Then your success callback will receive this information and update the page accordingly.

    Quote Originally Posted by fredep57 View Post
    So I need to have the address, city, state, zip changed based on the dropdown of the meeting place.
    To give you a concrete example:
    When your meeting place dropdown changes, use AJAX to send the value of the dropdown to process_ajax.php
    In process_ajax.php extract the value from the $_POST array into (for example) a variable named $place
    Make a db query:
    Code:
    $stmt = $db->prepare("SELECT address, city, state, zip FROM table-nameWHERE place = :place;");
    $stmt->bindParam(':place', $place);
    Echo the results back to your original page, then from within the success callback, insert them into the page (as previously demonstrated).

    Edit:

    Or do you mean that you need dependent selects (i.e. the options in the ZIP select change depending on what you select in the meeting place select?

  11. #11
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Oh, I must be really dense as I am getting more confused as this goes on.

    Based on which "place" is selected (in the query), the appropriate address, city, state and zip need to be displayed in their own Input boxes. So, based on what examples you have given, I am not sure how the javascript will put the info in the right place - or where I would like it to be.

    So, I guess either (1) I am really not "qualified" to use this and/or (2) I am not getting what you have tried to teach me.

    Please let me know if I can continue with this endeavor.

    And I really do appreciate your time and help - even if I might still need more (and really MORE) handholding so to speak.

  12. #12
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Quote Originally Posted by fredep57 View Post
    Please let me know if I can continue with this endeavor.
    Yeah, sure
    It might seem a bit frustrating that nothing is working right now, but we'll get there in the end.

    I think now it is important for me to understand what you are trying to do.
    Let's also try to use the same terminology, as we can then avoid confusion.

    What I have understood:

    You have a select menu on a webpage which you can use to select places:
    Code:
    <select>
      <option>Place 1</option>
      <option>Place 2</option>
    </select>
    Based on what the user selects in this select menu, you would like to display additional information about the place, namely address, city, state and zip.
    This additional information is stored in a database.

    In order to fetch this additional information every time the select menu changes, we are sending an AJAX request to a PHP script, passing it the value of the selected option in the select menu.

    Based on what parameters it receives, the PHP script then builds and executes a database query.

    The PHP script then returns the results of this database query to the JavaScript that initialised the AJAX request.

    The JavaScript uses the information it received from the PHP script to update the page.

    Did I get all of that right?
    If not please let me know what I have misunderstood.

  13. #13
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi there,
    You have a select menu on a webpage which you can use to select places:
    Code:
    <select>
      <option>Place 1</option>
      <option>Place 2</option>
    </select>
    Based on what the user selects in this select menu, you would like to display additional information about the place, namely address, city, state and zip.
    This additional information is stored in a database.

    Yes, the info is selected using the place. Yes, the info is in a database. The "Place1", "Place2", etc. is from the same db queried in a different place to start all of this.

    In order to fetch this additional information every time the select menu changes, we are sending an AJAX request to a PHP script, passing it the value of the selected option in the select menu.

    Based on what parameters it receives, the PHP script then builds and executes a database query.

    The PHP script then returns the results of this database query to the JavaScript that initialised the AJAX request.

    So, in the PHP script, does the db need to be re-opened? I would like it to not be as that is somewhat inefficient, yes?

    The JavaScript uses the information it received from the PHP script to update the page.
    This part is where I need to be clear. The first page has an input box (html) that I want to place the information. So... need to see how that is going to work.


    Did I get all of that right?
    If not please let me know what I have misunderstood.
    Looks like you have a good understanding of what I want/need for this project.

    Thanks again

  14. #14
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Quote Originally Posted by fredep57 View Post
    So, in the PHP script, does the db need to be re-opened? I would like it to not be as that is somewhat inefficient, yes?
    Yes and no (in that order).
    You would render your initial page (which I'm assuming is a PHP script). In this initial page, you open a connection to a database, so that you can get the information necessary to output your place select menu.
    On the same page, you then use JavaScript to attach the event handler to the select menu.

    When the select menu changes, the event handler is executed and sends an AJAX request to a separate second page (which you have created solely for this purpose)
    This second page opens a database connection, selects a record, based on the parameters it was passed, then returns these to your initial page.

    The JavaScript code in your initial page receives the results from the PHP script and inserts them into the page.

    This is not inefficient, as there is no page reload for your user (it's asynchronous) and only the necessary part of the page is updated.

    Quote Originally Posted by fredep57 View Post
    This part is where I need to be clear. The first page has an input box (html) that I want to place the information. So... need to see how that is going to work.
    What do you mean by input box?
    Do you mean a div container, or a text input element (<input type="text />) or a text area (<textarea></textarea>), or something else?
    Either way, it won't be difficult - you just need to select the element using JavaScript and set it's content to whatever came back from the AJAX request.

    How to proceed:
    Let me know about the input box, then I'll make you a small demo that queries a live database and inserts the results into the page.
    Also, if you could give me three examples of meeting places, as well as their corresponding address, city, state, zip information, that'd be great.

    HTH

  15. #15
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What do you mean by input box?
    Please check post #1 as that is my code for the form that I want the information to show.


    How to proceed:
    Let me know about the input box, then I'll make you a small demo that queries a live database and inserts the results into the page.
    Also, if you could give me three examples of meeting places, as well as their corresponding address, city, state, zip information, that'd be great.
    Post #1 has that in it (the input boxes that is - they are id'd as "element_5_x" where x is an incrementing number).
    Here is some data for the db.
    Darcy's Restaurant and Spirits
    10502 E Sprague Ave
    Spokane Valley, WA 99206

    Shari's of Spokane Valley
    320 N Sullivan Rd
    Veradale, WA 99037

    Elmers Restaurant
    290 W Appleway Ave
    Coeur d'Alene, ID 83814


    Thanks once more and I am starting to grasp this but still have a LONG way to go.
    F

  16. #16
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    Now I'm confused

    We have been talking about a select menu the whle time from which you can select a meeting place.
    However, in the code from post#1 Meeting place is a text input field.

    Also, there are two text input fields for Street address (as far as I can see), whereas City state is a select element.
    Zip code seems to be ok as a text input field.

    In addition to that (and please don't take this the wrong way) the markup is quite broken.
    Running the following code through the W3 validator produces 19 errors and 3 warnings:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>SACCC Meeting Information Change</title>
    <link rel="stylesheet" type="text/css" href="view.css" media="all">
    <script type="text/javascript" src="view.js"></script>
    <script type="text/javascript" src="calendar.js"></script>
    </head>
    <body id="main_body" >
    
    	<img id="top" src="top.png" alt="">
    	<div id="form_container">
    	
    		<h1><a> Meeting Information Change</a></h1>
    		<form id="form_754506" class="appnitro"  method="post" action="">
    					<div class="form_description">
    			<h2>Meeting Information Change</h2>
    			<p>Use this form to change the Monthly Meeting information.</p>
    		</div>						
    		<ul >		
    			</li>		<li id="li_4" >
    			<label class="description" for="element_4">Meeting Place </label>
    			<div>
    				<input id="element_4" name="element_4" class="element text medium" type="text" maxlength="255" value=""/> 
    			</div> 
    			</li>		
    			<li id="li_5" >
    			<label class="description" for="element_5">Meeting Address </label>
    			
    			<div>
    				<input id="element_5_1" name="element_5_1" class="element text large" value="" type="text">
    				<label for="element_5_1">Street Address</label>
    			</div>
    		
    			<div>
    			<span style="float:left">
    				<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" value="" type="text">
    				<label for="element_5_3">City</label>
    			</span>
    			<span style="float:left">
    				<select id="element_5_4" name="element_5_4" class="element text medium" style="width:3.5em"  maxlength="2" value="" type="text">
    				<label for="element_5_4">State</label>
    				</select>
    			</span>
    			<span style="float:left">
    				<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" maxlength="5" value="" type="text">
    				<label for="element_5_5">Zip Code</label>
    				</span>
    			</div>
    		
    			</li>		
    			
    				
    			<li class="buttons">
    				<input type="hidden" name="form_id" value="754506" />
    				<input id="saveForm" method="post" class="button_text" type="submit" name="addNew" value="Add New" action=""/>
    				<input id="saveForm" method="post" class="button_text" type="submit" name="submit" value="Submit" action=""/>
    			</li>
    		</ul>
    		</form>	
    	
    	</div>
    	<img id="bottom" src="bottom.png" alt="">
    	</body>
    </html>
    We need to fix this and agree on the markup we are going to use before we can implement any JS.

  17. #17
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK, found out that what I posted in the first one is not good. I started with something from the internet form design site and, well, will change that later.

    For now, how about this code to get started.

    Code:
    <?php
    // Call the db connection routine
    include 'db_connect.php';
    
      
      $db_selected = mysql_select_db($database, $link);
      if (!$db_selected) {
          die ('Can\'t use ' . $database . ' : ' . mysql_error());
      }
      
      	mysql_select_db($database, $link);
    
        $myQuery = "SELECT * FROM Meeting_Places ";
    
    	mysql_query($myQuery) or die('Error: ' . mysql_error());
    	
    	$result = mysql_query($myQuery, $link);
    
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8">
        <title>Select - onchange AJAX example</title>
      </head>
    
      <body>
        <label for="meetingPlace">Meeting place: </label>
        <select id="meetingPlace">
          <option value="">Please select</option>
    	  <?php
    		  $myQuery = "SELECT * FROM Meeting_Places ";
    
    		mysql_query($myQuery) or die('Error: ' . mysql_error());
    		
    		$result = mysql_query($myQuery, $link);
    		
    		while ($info = mysql_fetch_assoc($result))
    		{
    			echo '<option>' . $info['MeetingPlace'] . '</option>';
    		}
    	  ?>
    
        </select>
    		<div>
    			<label for="element_5_1">Street Address</label>
    			<input id="element_5_1" name="element_5_1" class="element text large" type="text">
    		</div>
    		<div>
    		<span style="float:left">
    			<label for="element_5_3">City</label>
    			<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
    
    		</span>
    		<span style="float:left">
    			<label for="element_5_4">State</label>
    			<input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
    			</select>
    		</span>
    		<span style="float:left">
    			<label for="element_5_5">Zip Code</label>		
    			<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
    
    			</span>
    		</div>
      </body>
    </html>
    Hope this can help get us started

  18. #18
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    That's much better. Thanks!

    So I did this:

    Code:
    CREATE TABLE Meeting_Places(
      id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
      MeetingPlace varchar(256),
      StreetAddress varchar(256),
      City varchar(256),
      State varchar(256),
      ZipCode smallint(6)
    ) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
    Then:

    Code:
    INSERT INTO meeting_places SET
    MeetingPlace = "Darcy's Restaurant and Spirits",
    StreetAddress = "10502 E Sprague Ave",
    City = "Spokane Valley",
    State = "WA",
    ZipCode = "99206"
    
    INSERT INTO meeting_places SET
    MeetingPlace = "Shari's of Spokane Valley",
    StreetAddress = "320 N Sullivan Rd",
    City = "Veradale",
    State = "WA",
    ZipCode = "99037"
    
    INSERT INTO meeting_places
    SET MeetingPlace =  "Elmers Restaurant",
    StreetAddress =  "290 W Appleway Ave",
    City =  "Coeur d'Alene",
    State =  "ID",
    ZipCode =  "83814"
    Now we should be on the same page.

    Before we start, I want to point out that it is not good practice to use PHP's old mysql API to connect to your databases.
    You should really migrate to PDO.
    See here for more info.

    That out of the way, I tidied up your PHP a little. In the code you posted above you were selecting everything twice from the DB. There is no need.
    This gives us what we need and outputs a list of meeting places accordingly.:

    Code:
    <?php
      # Connect
      mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
       
      # Choose a database
      mysql_select_db('sitepoint') or die('Could not select database');
       
      # Perform database query
      $query = "SELECT * from meeting_places";
      $result = mysql_query($query) or die('Query failed: ' . mysql_error());
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta charset="utf-8">
        <title>Select - onchange AJAX example</title>
      </head>
    
      <body>
        <label for="meetingPlace">Meeting place: </label>
        <select id="meetingPlace">
          <option value="0">Please select</option>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
                echo '<option value="' . $row['id'] . '">' . $row['MeetingPlace'] . '</option>';
            }
          ?>
        </select>
    
        <div>
          <label for="element_5_1">Street Address</label>
          <input id="element_5_1" name="element_5_1" class="element text large" type="text">
        </div>
    
        <div>
          <span class="floatLeft">
            <label for="element_5_3">City</label>
            <input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
          </span>
    
          <span style="float:left">
            <label for="element_5_4">State</label>
            <input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
            </select>
          </span>
    
          <span style="float:left">
            <label for="element_5_5">Zip Code</label>   
            <input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
          </span>
        </div>
      </body>
    </html>
    Now we need to hook into the onchange event of the select element:

    Code:
    $("#meetingPlace").on("change", function(){
      var id = $(this).val();
      if (id === "0"){
        clearForm();
      } else {
        makeAjaxRequest(id);
      }
    });
    I have given all of the option elements a value. If the value is 0, the user has selected the default and we want to clear the remaining fields.
    If the value is something else, we want to fire our AJAX request, passing the function the id of the place that has just been selected.

    On to the AJAX:

    Code:
    function makeAjaxRequest(placeId){
      $.ajax({
        type: "POST",
        data: { placeId: placeId },
        dataType: "json", 
        url: "process_ajax.php",
        success: function(json) {
          insertResults(json);
        }
      });
    }
    Nothing new here, except that we are specifying dataType: "json", as we want json back from the server.

    And finally the success callback and the function to clear the fields:

    Code:
    function insertResults(json){
      $("#element_5_1").val(json["StreetAddress"]);
      $("#element_5_3").val(json["City"]);
      $("#element_5_4").val(json["State"]);
      $("#element_5_5").val(json["ZipCode"]);
    }
    
    function clearForm(){
      $("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
    }
    Nothing exciting here, either. Our server will return a json object representing the database record (as we will see in a minute) and we are setting those values as the values of the input elements.

    In the clearForm() function, we are simply setting the values of all inputs to that of an empty string.

    And on the serever:

    Code:
    <?php
      mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
      mysql_select_db('sitepoint') or die('Could not select database');
       
      $placeId = $_POST['placeId'];
    
      $query = "SELECT * from meeting_places";
      $result = mysql_query($query) or die('Query failed: ' . mysql_error());
      while ($row = mysql_fetch_assoc($result)) {
        if ($placeId == $row['id']){
          echo json_encode($row);
        }
      }
    ?>
    We are retrieving the id of the place selected in the select element from $_POST, then querying the database for all records.
    When we have the records, we are looping through them to find the one which matches the place id, encoding it as json and returning it to our script.

    Note: you could do this more efficiently if you sanitise the input from the JS and use it directly. This is where PDO and prepared statements shine.

    And finally here's the complete code.

    index.php:

    Code:
    <?php
      # Connect
      mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
       
      # Choose a database
      mysql_select_db('sitepoint') or die('Could not select database');
       
      # Perform database query
      $query = "SELECT * from meeting_places";
      $result = mysql_query($query) or die('Query failed: ' . mysql_error());
    ?>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta charset="utf-8">
        <title>Select - onchange AJAX example</title>
      </head>
    
      <body>
        <label for="meetingPlace">Meeting place: </label>
        <select id="meetingPlace">
          <option value="0">Please select</option>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
                echo '<option value="' . $row['id'] . '">' . $row['MeetingPlace'] . '</option>';
            }
          ?>
        </select>
    
        <div>
          <label for="element_5_1">Street Address</label>
          <input id="element_5_1" name="element_5_1" class="element text large" type="text">
        </div>
    
        <div>
          <span class="floatLeft">
            <label for="element_5_3">City</label>
            <input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
          </span>
    
          <span style="float:left">
            <label for="element_5_4">State</label>
            <input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
            </select>
          </span>
    
          <span style="float:left">
            <label for="element_5_5">Zip Code</label>   
            <input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
          </span>
        </div>
    
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
          function insertResults(json){
            $("#element_5_1").val(json["StreetAddress"]);
            $("#element_5_3").val(json["City"]);
            $("#element_5_4").val(json["State"]);
            $("#element_5_5").val(json["ZipCode"]);
          }
    
          function clearForm(){
            $("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
          }
    
          function makeAjaxRequest(placeId){
            $.ajax({
              type: "POST",
              data: { placeId: placeId },
              dataType: "json", 
              url: "process_ajax.php",
              success: function(json) {
                insertResults(json);
              }
            });
          }
    
          $("#meetingPlace").on("change", function(){
            var id = $(this).val();
            if (id === "0"){
              clearForm();
            } else {
              makeAjaxRequest(id);
            }
          });
        </script>
      </body>
    </html>
    process_ajax.php:

    Code:
    <?php
      mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
      mysql_select_db('sitepoint') or die('Could not select database');
       
      $placeId = $_POST['placeId'];
    
      $query = "SELECT * from meeting_places";
      $result = mysql_query($query) or die('Query failed: ' . mysql_error());
      while ($row = mysql_fetch_assoc($result)) {
        if ($placeId == $row['id']){
          echo json_encode($row);
        }
      }
    ?>
    I hope that helps. Let me know how you get on

  19. #19
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I hope that helps. Let me know how you get on
    YES, this helps. I have tried this but have one problem. The information works - the other data is put in and works pretty well. However, why does the last line have State, Zip then City instead of like it is listed in my code?

    Thanks

  20. #20
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    I'm glad it works.

    Quote Originally Posted by fredep57 View Post
    However, why does the last line have State, Zip then City instead of like it is listed in my code?
    I'm really not sure what you mean by this. Could you expand a little?

  21. #21
    SitePoint Zealot fredep57's Avatar
    Join Date
    Aug 2009
    Location
    Pacific Northwest
    Posts
    137
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Pullo, figured it out. Also, I am using the old PHP MySQL commands since I am trying to maintain a site that was built over 10 years ago and have to correct/fix things but do not have time to update all of it to current, good stuff.

    OK, thanks to Pullo, I now somewhat understand what is going on to possibly make my form update if the right information is entered. That being said, I have tried to integrate into my form the lessons taught here.

    However, I have done something wrong as it does not return anything - well, at least the information is not placed in the appropriate boxes.

    Please review this and let me know where I messed up - besides trying to do this at all

    Here is my code thus far. It is using the data Pullo posted earlier since I know that was working in the sample he authored above.

    InputForm.php
    Code:
    <?php
    	session_start();
    
    	// Connection Variables
    	$hostname="localhost";
    	$mysql_login="user";
    	$mysql_password="pw";
    	$database='sitepoint';
    	
    
    	// Connect to the database server
    	$link = mysql_connect($hostname, $mysql_login, $mysql_password);
    	if (!$link) 
    	{
    		die('Could not connect: ' . mysql_error());
    	}
       $db_selected = mysql_select_db($database, $link);
      if (!$db_selected) {
          die ('Can\'t use ' . $database . ' : ' . mysql_error());
      }
      
      $myQuery = "SELECT * FROM Meeting_Places ";
    			
    	if ($_SERVER['REQUEST_METHOD'] == 'POST') 
      { 
        $task = isset($_POST['task']) ? $_POST['task'] : false; 
         if ($task == "Register") {
          $formValues = $_POST; 
          $formErrors = array();  
          if (!VerifyForm($formValues, $formErrors)) 
          DisplayForm($formValues, $formErrors); 
          else     {
            ProcessForm($formValues);     }
          }
          else if ($task == 'ReturnToMainPage')   
            header('Location: index.php');
      }  
      else 
      {
        DisplayForm(null, null);
    }
    
    
    function DisplayForm($values, $errors) 
    { ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
    <title>SACCC Meeting Information Change</title>
    <link rel="stylesheet" type="text/css" href="view.css" media="all" />
    <script type="text/javascript" src="view.js"></script>
    <script type="text/javascript" src="calendar.js"></script>
    </head>
    <body id="main_body" >
    
    	<img id="top" src="top.png" alt=""></img>
    	<div id="form_container">
    	
    		<h1><a>SACCC Meeting Information Change</a></h1>
    		<form id="form_754506" class="appnitro"  method="post" action="">
    					<div class="form_description">
    			<h2>SACCC Meeting Information Change</h2>
    			<p>Use this form to change the SACCC Monthly Meeting information.</p>
    		</div>						
    			<ul >		
    				<li id="li_2" >
    					<label class="description" >Meeting Date: </label>
    					<span>
    						<input id="element_2_1" name="element_2_1" class="element text" size="2" maxlength="2" value="" type="text" />
    						<label for="element_2_1">MM</label>
    					</span>
    					<span>
    						<input id="element_2_2" name="element_2_2" class="element text" size="2" maxlength="2" value="" type="text" />
    						<label for="element_2_2">DD</label>
    					</span>
    					<span>
    						<input id="element_2_3" name="element_2_3" class="element text" size="4" maxlength="4" value="" type="text" />
    						<label for="element_2_3">YYYY</label>
    					</span>
    				
    					<span id="calendar_2">
    						<img id="cal_img_2" class="datepicker" src="calendar.gif" alt="Pick a date." />	
    					</span>
    					<script type="text/javascript">
    						Calendar.setup({
    						inputField	 : "element_2_3",
    						baseField    : "element_2",
    						displayArea  : "calendar_2",
    						button		 : "cal_img_2",
    						ifFormat	 : "%B %e, %Y",
    						onSelect	 : selectDate
    						});
    					</script>
    				</li>		
    				<li id="li_3" >
    		<label class="description" for="element_3">Meeting Time </label>
    		<span>
    			<label>HH</label>		
    			<select id="element_3_1" name="element_3_1" class="element text" >
    				<?php
    					for($i=0; $i<12 ; ++$i)
    					{
    						if($i<9)
    						{
    							$j = $i + 1;
    							echo "<option value=\"0" . $j . "\">0" .$j . "</option>";
    						}
    						else
    						{
    							$j = $i + 1;
    							echo "<option value=\"" . $j . "\">" .$j . "</option>";
    						}
    					}
    				?>
    				
    			</select>
    		</span>
    		<span>
    			<label>MM</label>		
    			<select id="element_3_2" name="element_3_2" class="element text" >
    			<option value = "00" selected = "selected">00</option>
    			<option value = "15">15</option>
    			<option value = "30">30</option>
    			<option value = "45">45</option>
    			</select>
    		</span>
    		<span>
    			<label>AM/PM</label>		
    			<select class="element select" id="element_3_4" name="element_3_4">
    				<option value="AM" >AM</option>
    				<option value="PM" >PM</option>
    			</select>
    
    		</span> 
    		</li>		<li id="li_4" >
    		<label class="description" >Meeting Place </label>
    		<div>
    		in meeting place div
    			<select>
    			<option value="0">Please Select</option>
    <?php
     		  $myQuery = "SELECT * FROM meeting_places ";
    	
    		$result = mysql_query($myQuery);
    
    		while ($info = mysql_fetch_assoc($result))
    		{
    			echo '<option value="' . $info['id'] . '">' . $info['MeetingPlace'] . '</option>';
    		}
    
    ?>			
    			</select>
    		</div> 
    		</li>		
    		<li id="li_5" >
    		<label class="description" >Meeting Address </label>
    		
    		<div>
    			<input id="element_5_1" name="element_5_1" class="element text large" type="text" />
    			<label for="element_5_1">Street Address</label>
    		</div>
    	
    		<div>
    		<span style="float:left">
    			<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text" />
    			<label for="element_5_3">City</label>
    		</span>
    		<span style="float:left">
    
    			<select id="element_5_4" name="element_5_4" class="element text medium" type="text" >
    
    				<option value="ID">ID</option>
    				<option value="WA">WA</option>
    			</select>
    			<label for="element_5_4">State</label>			
    		</span>
    		<span style="float:left">
    			<input id="element_5_5" name="element_5_5" class="element text medium" type="text" />
    			<label for="element_5_5">Zip Code</label>
    			</span>
    		</div>
    	
    		</li>		
    		
    		<li id="li_6" >
    		<label class="description" for="element_6">Comments </label>
    		<div>
    			<textarea id="element_6" name="element_6" class="element textarea medium" rows="4" cols="50"></textarea> 
    		</div> 
    		</li>
    			
    					<li class="buttons">
    			    <input type="hidden" name="form_id" value="754506" />
    			    <input id="newForm" method="post" class="button_text" type="submit" name="addNew" value="Add New" action="<?= $_SERVER['PHP_SELF'] ?>"/>
    				<input id="saveForm" method="post" class="button_text" type="submit" name="submit" value="Submit" action="<?= $_SERVER['PHP_SELF'] ?>"/>
    		</li>
    			</ul>
    		</form>	
    		<?php }
    		?>		
    	</div>
    	
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          function insertResults(json){
            $("#element_5_1").val(json["StreetAddress"]);
            $("#element_5_3").val(json["City"]);
            $("#element_5_4").val(json["State"]);
            $("#element_5_5").val(json["ZipCode"]);
    		$("#element_6").val(json["Comments"]);
          }
    
          function clearForm(){
            $("#element_5_1, #element_5_3, #element_5_4, #element_5_5, #element_6").val("");
          }
    
          function makeAjaxRequest(placeId){
            $.ajax({
              type: "POST",
              data: { placeId: placeId },
              dataType: "json", 
              url: "process_ajax999.php",
              success: function(json) {
                insertResults(json);
              }
            });
          }
    
          $("#meetingPlace").on("change", function(){
            var id = $(this).val();
            if (id === "0"){
    		alert('id is zero');
              clearForm();
            } else {
              makeAjaxRequest(id);
            }
          });
        </script>
    	</body>
    </html>

    process_ajax.php
    Code:
    <?php
    	// Connection Variables
    	$hostname="localhost";
    	$mysql_login="user";
    	$mysql_password="pw";
    	$database='sitepoint';
    	
    
    	// Connect to the database server
    	$link = mysql_connect($hostname, $mysql_login, $mysql_password);
    	if (!$link) 
    	{
    		die('Could not connect: ' . mysql_error());
    	}
       $db_selected = mysql_select_db($database, $link);
      if (!$db_selected) {
          die ('Can\'t use ' . $database . ' : ' . mysql_error());
      }
      $placeId = $_POST['placeId'];
    
      $query = "SELECT * from meeting_places";
      $result = mysql_query($query) or die('Query failed: ' . mysql_error());
     echo 'in process_ajax99.php<br>';
    	while ($row = mysql_fetch_assoc($result)) {
        if ($placeId == $row['id']){
          echo json_encode($row);
        }
      }
    ?>

  22. #22
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    There are a number of errors with the code you posted, but no probs, let's go through them.

    InputForm.php

    • During my debugging, I removed the following, as these lines reference files on your server I have no access to:

      Code:
      <link rel="stylesheet" type="text/css" href="view.css" media="all" />
      <script type="text/javascript" src="view.js"></script>
      <script type="text/javascript" src="calendar.js"></script>
      <script type="text/javascript">
        Calendar.setup({
          inputField   : "element_2_3",
          baseField    : "element_2",
          displayArea  : "calendar_2",
          button     : "cal_img_2",
          ifFormat   : "%B %e, %Y",
          onSelect   : selectDate
      });
      </script>
      This is not an error, more something to be aware of.
    • You forgot to give the select element an id. Without an id, nothing will happen when its value changes.

      So, this:
      Code:
      <select>
        <option value="0">Please Select</option>
        <?php
          $myQuery = "SELECT * FROM meeting_places ";
          $result = mysql_query($myQuery);
          while ($info = mysql_fetch_assoc($result)) {
            echo '<option value="' . $info['id'] . '">' . $info['MeetingPlace'] . '</option>';
          }
        ?>      
      </select>
      Should be:
      Code:
      <select id="meetingPlace">
        <option value="0">Please Select</option>
        <?php
          $myQuery = "SELECT * FROM meeting_places ";
          $result = mysql_query($myQuery);
          while ($info = mysql_fetch_assoc($result)) {
            echo '<option value="' . $info['id'] . '">' . $info['MeetingPlace'] . '</option>';
          }
        ?>      
      </select>
    • This might be a typo, but above you called your file "process_ajax.php", yet in the JavaScript you have:
      Code:
      function makeAjaxRequest(placeId){
        $.ajax({
          type: "POST",
          data: { placeId: placeId },
          dataType: "json", 
          url: "process_ajax999.php",
          success: function(json) {
            insertResults(json);
          }
        });
      }
      Obviously the file referenced under the URL attribute should correspond with the name of the actual file.


    process_ajax.php

    In this file, the first value echoed will be the return value, so your request was returning "in process_ajax99.php<br>".

    Remove this line:

    Code:
    echo 'in process_ajax99.php<br>';
    Then everything will work as expected.

    Happy Christmas


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •