• Resolved A31

    (@a31)


    Hi,
    I am really struggling to get a second dropdown / select box to be automatically populated and I hope someone here can help me find my mistake.

    Before moving to WordPress, I have been using the example by W3Schools but now in wordpress, I can’t seem to get it working.

    My Code is as follows:

    <script type="text/javascript">
    function showUser(str)
    {
    if (str=="")
      {
      document.getElementById("txtHint").innerHTML="";
      return;
      }
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","Fin_GetAllocation.php?q="+str,true);
    xmlhttp.send();
    }
    </script>
    <form>
    	<select name="sel_CostCentre" id="sel_CostCentre" onchange="showUser(this.value)">
    		<option value=0>Please Select Cost Centre: <?php echo $CostCentreDescriptionOptions; ?>
    	</select>
        <select name="Sel" id="txtHint"></select>
    </form>

    then the code in the file “Fin_GetAllocation.php” is as follows:

    <?php
    	global $wpdb;
    
    	$q=$_GET["q"];
    
    	$SQL_Query01 = ("SELECT * FROM wp_allocations_tbl WHERE CostCentreDescription = '$q'");
    	$SQL_Results01 = $wpdb->get_results($SQL_Query01);
    
    	foreach($SQL_Results01 as $myResult01)
    		{
    			$AccountDescription = $myResult01->AccountDescription; //Field in DB
    			$AccountDescriptionOptions.="<option value='$AccountDescription'>" . $AccountDescription . "</option>";
    		}

    So my first dropdown / select box works perfectly, but I can’t seem to get the second box to populate.

    Can you please help?

Viewing 6 replies - 16 through 21 (of 21 total)
  • Thread Starter A31

    (@a31)

    I have installed Firebug to help me troubleshoot, and the error I get is:

    SyntaxError: JSON.parse: unexpected character

    data = JSON.parse(xhr.responseText);

    Does that help?

    Thread Starter A31

    (@a31)

    I have managed to trace one error in the jQuery code:

    success: function(data) {
               //data = JSON.parse(xhr.responseText); //WRONG CODE
    	   $("#responsecontainer").html(data); // RIGHT CODE

    so now that error is sorted, but I get the following:

    Fatal error: Call to undefined function wp_get_current_user() in C:\xampp\htdocs\WPTest\wp-content\plugins\NewAjaxTry\inc\MyData.php on line 11

    I presume this is the part that you are referring to that I have not yet linked / hooked / enqueued the needed files.

    But I still have no idea where I am missing that…

    Any advice?

    Moderator bcworkz

    (@bcworkz)

    I’m glad you resolved the jQuery error, it’s not something I have a lot of experience with. I see now why you are confused, it’s a natural mistake for a novice. I’m not so sure how to make it more clear, but here goes…

    First the URL for the destination of the AJAX request. When you use wp_localize_script(), you are merely defining a global javascript object that contains useful data. There are only a couple ways to pass dynamic data from PHP to javascript, this is one of them. This function sets up the data, making it available to javascript. It does not actually use the data. That is javascript/jQuery’s job.

    Where you want to make use of the data is where you tell jQuery where to send the AJAX request, in this part:

    $.ajax({
       type:"POST",
       url: "https://localhost/WPTest/wp-content/plugins/AJAXTest/inc/MyData.php",

    This is the crux of why all of this is even necessary. You cannot send a request directly to MyData.php, which is what you are trying to do. Every request starts a new process thread. Each new thread is in isolation, what ever happened in a different thread has no bearing on this thread. Even though MyData.php was loaded as part of your plugin in another thread, it has nothing to do with this request. We’re starting over. Thus, none of the WP functions have been defined. This is why you are getting function not defined errors.

    By sending the request to the URL that was setup in wp_localize_script() you are causing WP to load itself on your behalf. In doing so, MyData.php can again be part of your plugin, gaining access to all WP resources.

    So, to use the localized value as the URL value in the ajax call, you just use the object name, dot, property name like so:
    url: custom-script_vars1.ajaxurl,

    And don’t forget to provide an ‘action’ value as part of the data passed in the AJAX call. It is used to construct an action tag name your PHP script hooks to.

    So now the AJAX handler callback function. wp_enqueue_script() has nothing to do with this. When we enqueue scripts, we are referring to javascript and jquery. All that enqueuing does is cause the correct .js files to be referenced in the page’s head section. While it is PHP script itself, it doesn’t have anything to do with other PHP script.

    In order for your AJAX handler to be used when a request is received, it must be hooked into the right action tag. The tag is composed by appending your ‘action’ property passed in the AJAX request to one of the prefixes determined by the context, login page, user logged in, or user not logged in. This is how admin-ajax.php routes the request to the proper handler function.

    I hope this all is starting to make sense. The whole thing is rather complex and difficult to grasp at first. After a while, you’ll see it’s really not so difficult. At it’s most abstract, the browser sends a request and the server responds. That’s it. Everything else are just setup measures to enable this to happen. No element by itself is that difficult, it’s just that there are a lot of them that all need to happen. It’s easy to feel overwhelmed. Try to just focus on what any one thing does at one time. Go through a list and be sure you’ve done each thing, and they will then all come together on their own accord.

    Thread Starter A31

    (@a31)

    Ok, so I KNOW this has been such a long struggle for me, I finally got something right!!

    I am posting it here so that HOPEFULLY the next person won’t have to struggle so much as what I did.

    Please note that this is a VERY minimalistic approach, nothing has been properly escaped / validated or is secure.

    It really is only to demonstrate how I managed after more than 3 months to get AJAX working:

    Let’s start with the main plugin file:

    <?php
    /*
    Plugin Name: AJAX Multiple Selectbox
    Plugin URI: https://www.tigita.co.za/
    Description: AJAX Multiple Selectbox
    Author: Adrian Beyers
    Version: 1.0
    Author URI: https://www.tigita.co.za/
    */
    
    /***************************
    * GLOBAL VARIABLES
    ***************************/
    
    if (!isset($wpdb)) $wpdb = $GLOBALS['wpdb'];
    global $wpdb;
    
    /***************************
    * SCRIPTS
    ***************************/
    
    function ASB_load_scripts()
    {	
    
    	//Include Javascript library
    	wp_enqueue_script("jquery");
    	wp_enqueue_script("sack");
    
    	wp_enqueue_script('ASB_jQuery', plugins_url( '/js/myScripts.js' , __FILE__ ) , array( 'jquery' ));
    
    	// including ajax script in the plugin Myajax.ajaxurl
    	wp_localize_script( 'ASB_jQuery', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
    }
    add_action('wp_enqueue_scripts', 'ASB_load_scripts');
    add_action( 'admin_enqueue_scripts', 'ASB_load_scripts');
    
    /***************************
    * INCLUDES
    ***************************/
    
    include ('inc/setup_addPages.php');
    include ('inc/setup_shortcodes.php');
    include ("inc/setup_addFunctions.php");
    
    /***************************
    * REGISTER PAGES
    ***************************/
    
    register_activation_hook(__FILE__,'ASB_Func_addPage');
    register_deactivation_hook(__FILE__,'ASB_Func_removePage');

    Next the setup_addFunctions.php:

    <?php
    
    //*******************************************************************************************************************************************
    	function form_SelectBoxExample()
    	{
    		echo 	'
    					<form id="AddNewSubject_Form" onsubmit="return false;">
    
    						<p>
    							<label>Select Option 1: </label>
    							<select class="" name="sel_Option1" id="sel_Option1" required="required">
    								<option value="">Please Select... </option>
    								<option value="Ford">Ford</option>
    								<option value="Mercedes">Mercedes</option>
    							</select>
    						</p>
    						<p>
    							<label>Select Option 2: </label>
    							<select class="" name="sel_Option2" id="sel_Option2" required="required">
    								<option value="">Please Select... </option>
    							</select>
    						</p>
    					</form>
    				';
    	}
    	add_action('SelectBoxExample_Form', 'form_SelectBoxExample');
    
    //*******************************************************************************************************************************************
    
    //*******************************************************************************************************************************************
    
    	function ASB_func_GetOption2()
    	{
    		global $wpdb;
    
    		if (isset($_POST['SelectedOption1']))
    		{
    			$Option1 = $_POST['SelectedOption1'];
    
    			$SQL_Query = 	("SELECT Option2 FROM customOptions_tbl WHERE Option1 = '" . $Option1 . "'");
    			$SQL_Result = $wpdb->get_results($SQL_Query);
    
    			foreach($SQL_Result as $mySQL_Result)
    			{
    				$Option2 = $mySQL_Result->Option2;
    				echo '<option value=' . $Option2 . '>' . $Option2 . '</option>';
    			}
    
    		}
    
    		die();
    		return true;
    	}
    	add_action('wp_ajax_ASB_func_GetOption2', 'ASB_func_GetOption2');
    	add_action('wp_ajax_nopriv_ASB_func_GetOption2', 'ASB_func_GetOption2');
    
    //*******************************************************************************************************************************************
    ?>

    Now the myScript.js:

    // JavaScript Document
    
    jQuery(document).ready(function ($)
    {
    	jQuery('#sel_Option1').change(function()
    	{
    		var SelectedOption1 = jQuery("#sel_Option1").val();
    
    		jQuery.ajax(
    		{
    			type: 'POST',
    			url: MyAjax.ajaxurl,
    			data: 	{
    						"action": "ASB_func_GetOption2",
    						"SelectedOption1": SelectedOption1
    					},
    			success: function(data)
    			{
    				jQuery('#sel_Option2').html(data);
    			}
    		});
    	});
    });

    setup_shortcodes.php:

    <?php
    
    	global $wpdb;
    
    	/***************************
    	* SETUP FRONT-END SHORTCODES
    	***************************/
    
    	add_shortcode("ASB_MultiSelect","ASB_MultiSelect_Shortcode");
    
    	function ASB_MultiSelect_Shortcode($atts)
    	{
    		  include ('MultiSelect.php');
    	}
    
    ?>

    And lastly MultiSelect.php:

    <?php
    
    	do_action('SelectBoxExample_Form');

    I REALLY hope that this helps someone else!

    Thread Starter A31

    (@a31)

    Thnx to bcworkz for all your help!!

    Moderator bcworkz

    (@bcworkz)

    You are most welcome! You must be truly elated to finally conquer this!

    Isn’t it ironic that after so much struggle, the final code is fairly simple? If it helps any, I too struggled at first to get AJAX working, many silly errors because I didn’t understand what was going on. But by struggling through it all, I learned a lot. It was worth the struggle for me. Maybe not right now, but I think you will eventually feel the same.

Viewing 6 replies - 16 through 21 (of 21 total)
  • The topic ‘Nested Select Menu’ is closed to new replies.