WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Select change using AJAX (9 posts)

  1. Chris Sanders
    Member
    Posted 3 years ago #

    I am trying to use two selectors. When the first is selected, it should populate the second using records from a custom table I created within the wordpress database.

    To do this I tried to use the following tutorial: http://www.1stwebdesigner.com/wordpress/implement-ajax-wordpress-themes/

    The first selector name is called: parent_Select
    The second selector name is called: secondary_Select

    I've always made the assumption that the below is PHP code...I just don't have much familiarity with Javascript and AJAX.

    The following block of code is giving me problems:

    $(function(){
    	$('#parent_Select').change(function()
    	{
    		var $parentID=$('#parent_Select').val();
    
    		// call ajax
    		$("#secondary_Select).empty();
    		$.ajax(
    		{
    			url:"/wp-admin/admin-ajax.php",
    			type:'POST',
    			data:'action=my_special_action&selectParentID=' + $parentID,
    
    			success:function(results)
                {
                	/  alert(results);
                    $("#secondary_Select").removeAttr("disabled");
                    $("#secondary_Select").append(results);
    			}
             });
         });
    })

    Could someone please let me know what might be off? Thank you!

  2. fgjordan
    Member
    Posted 3 years ago #

    First off, there are some syntax errors in your code:

    You are missing the closing quotes for your $("#secondary_Select").empty(); line. Also, you are missing the second forward slash to comment out the alert(results); line.

    Apart from that, everything looks good in this code. There could be other problems in the html file, such as incorrect selector types or names.

    Here is your code with the errors removed:

    $(function(){
    		$('#main_cat').change(function(){
    			var $parentID=$('#parent_Select').val();
    
    			//Empty secondary categories
    			$('#secondary_Select').empty();
    
    			//Call ajax
    			$.ajax({
    				url:"/wp-admin/admin-ajax.php",
    				type:'POST',
    				data:'action=my_special_action&selectedParentID=' + $parentID,
    				success:function(results) {
    					//alert(results);
    					$('#secondary_Select').removeAttr("disabled");
    					$('#secondary_Select').append(results);
    				}
    			});
    		}
    	);
    });

    To more accurately debug javascript in the future, I recommend using Firebug. Here is a good tutorial to help you get started.

  3. Chris Sanders
    Member
    Posted 3 years ago #

    The page still won't load unless I comment out the below code:

    $(function(){
    		$('#main_cat').change(function(){
    			var $parentID=$('#parent_Select').val();
    
    			//Empty secondary categories
    			$('#secondary_Select').empty();
    
    			//Call ajax
    			$.ajax({
    				url:"/wp-admin/admin-ajax.php",
    				type:'POST',
    				data:'action=my_special_action&selectedParentID=' + $parentID,
    				success:function(results)
    				{
    					//alert(results);
    					$('#secondary_Select').removeAttr("disabled");
    					$('#secondary_Select').append(results);
    				}
    			});
    		});
    });
  4. Chris Sanders
    Member
    Posted 3 years ago #

    Here is the AJAX Code:

    [Large code excerpt removed by moderator per forum rules. Please use the pastebin for all large code excerpts. It works better anyway.]

    Here is the html code:

    <select name ="parentSelect" onChange=populate_Select(this.options[this.selectedIndex].value)>
    	<?php
    	// For each key of the array assign variable name "topID"
    	// For each value of the array assign variable name "topName".
    	foreach($array1 as $element)
    	{
    		$topID = $element->CustomH_Id;
    		$topName = $element->CustomH_Name;
    
    		echo "<option value='".$topID."'>".$topName;
    		?>
    	<?php
    	}
    
    	//echo close selector
    	echo "</select>";
    
    	// Secondary Element Label
      echo '<label for="hCustomFields_secondary_element">' . __("Secondary Element: ", 'hCustomFields_textdomain' ) . '</label> ';
    
      // create selector that will be populated by AJAX
    	echo "<select id='secondarySelect' name='secondarySelect' disabled='disabled'>";
    
    	// close selector
    	echo "</select>";
  5. Chris Sanders
    Member
    Posted 3 years ago #

    AJAX (with variable += 10 line removed)

    [Large code excerpt removed by moderator per forum rules. Please use the pastebin for all large code excerpts. It works better anyway.]

    html code:

    <select name ="parentSelect" onChange=populate_Select(this.options[this.selectedIndex].value)>
    	<?php
    	// For each key of the array assign variable name "topID"
    	// For each value of the array assign variable name "topName".
    	foreach($array1 as $element)
    	{
    		$topID = $element->CustomH_Id;
    		$topName = $element->CustomH_Name;
    
    		echo "<option value='".$topID."'>".$topName;
    		?>
    	<?php
    	}
    
    	//echo close selector
    	echo "</select>";
    
    	// Secondary Element Label
      echo '<label for="hCustomFields_secondary_element">' . __("Secondary Element: ", 'hCustomFields_textdomain' ) . '</label> ';
    
      // create selector that will be populated by AJAX
    	echo "<select id='secondarySelect' name='secondarySelect' disabled='disabled'>";
    
    	// close selector
    	echo "</select>";
  6. Chris Sanders
    Member
    Posted 3 years ago #

    Got it!

    Thanks to fgjordan for the assistance. Final code:

    php/ajax:

    [Large code excerpt removed by moderator per forum rules. Please use the pastebin for all large code excerpts. It works better anyway.]

    html:

    <select name ="parentSelect" onChange=populate_Select(this.options[this.selectedIndex].value)>
    	<?php
    	// For each key of the array assign variable name "topID"
    	// For each value of the array assign variable name "topName".
    	foreach($array1 as $element)
    	{
    		$topID = $element->CustomH_Id;
    		$topName = $element->CustomH_Name;
    
    		echo "<option value='".$topID."'>".$topName;
    		?>
    	<?php
    	}
    
    	//echo close selector
    	echo "</select>";
    
    	// Secondary Element Label
      echo '<label for="hCustomFields_secondary_element">' . __("Secondary Element: ", 'hCustomFields_textdomain' ) . '</label> ';
    
      // create selector that will be populated by AJAX
    	echo "<select id='secondarySelect' name='secondarySelect' disabled='true'>";
    
    	// close selector
    	echo "</select>";
  7. Chris Sanders
    Member
    Posted 3 years ago #

  8. kokomaungoo
    Member
    Posted 2 years ago #

    I am trying to use this in my website, but it doesn't seem to work.
    My code in theme function.php is
    ===================
    function city_ajax() {
    if(isset($_POST['country'])){
    global $wpdb;
    $c=$_POST['country'];
    $cities = $wpdb->get_col("SELECT city_name FROM $wpdb->Country_City WHERE country_name='".$c."' order by city_name");
    foreach ($cities as $city)
    {
    $option .= '<option value="'.$city.'">';
    $option .= $city;
    $option .= '</option>';
    }
    echo '<option value="-1" selected="selected">Scegli...</option>'.$option;
    die();

    }
    }
    add_action('wp_ajax_my_special_ajax_call', 'city_ajax');
    add_action('wp_ajax_nopriv_my_special_ajax_call', 'city_ajax');
    ======================
    My html code for this website http://www.business-directory.greatmyanmar.com/singapore/submit-company-website-listing/ is
    <div class="field">
    <label for="city"><?php _e('City', "wpct");?></label>
    <?php
    echo "<select name='city' id='city' disabled='disabled'>";
    echo "</select>";
    ?>
    </div>
    ============
    You can check my jquery code in page source.

    I am not sure how does jquery work. I just try to use this example.But somehow it is not working.

    Can someone pls let me know what wrong with my code or integration ?

  9. kokomaungoo
    Member
    Posted 2 years ago #

    Forget to mentioned what I am try to do.
    I am try to get the list of the cities form DB when user select a country name from country2 drop down selection.
    So I call jquery code with onChange from country2 dropdown list and jquery call the DB query in theme function.php through ajax.
    That is what I understand it will work based on this original post.

    And I found that there is something worng in $('#country2').change(function() because it keep looping more than one time after select a country name. you will experience yourself when you select the countr2 drop down list.
    Here is my jquery/ajax code
    ===================
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>

    <script type="text/javascript" >
    function populate_select()
    {
    alert("1");
    $(function(){
    alert("2");
    $('#country2').change(function(){
    alert("3");
    var $tmp_Country2=$('#country2').val();
    alert($tmp_Country2);
    // call ajax
    $("#city").empty();
    $.ajax({
    url:"/business-directory.greatmyanmar.com/singapore/wp-admin/admin-ajax.php",
    type:'POST', data:'action=my_special_ajax_call&country=' + $tmp_Country2,
    success:function(results)
    {
    //alert(results);
    $("#city").removeAttr("disabled");
    $("#city").append(results);
    }
    });
    alert("aft ajx call.");

    }
    );
    });
    }
    </script>

    ===================

Topic Closed

This topic has been closed to new replies.

About this Topic