Cakephp Ajax drop down menu, one drop down list populate the next
This is how you create a ajax drop down menu, where the first drop down list populates the next
Cakephp Ajax drop down menu, one drop down list populate the next
This is how you create a ajax drop down menu, where the first drop down list populates the next
at the top of your page add the following javascript
<script type="text/javascript"> function changeContent(str) { if (str=="") { // if blank, we'll set our innerHTML to be blank. document.getElementById("ajaxcontent").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari // create a new XML http Request that will go to our generator webpage. xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 // create an activeX object xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // on state change xmlhttp.onreadystatechange=function() { // if we get a good response from the webpage, display the output if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("ajaxcontent").innerHTML=xmlhttp.responseText; } } // use our XML HTTP Request object to send a get to our content php. xmlhttp.open("GET","getproducts?metal_id="+str, true); xmlhttp.send(); } </script>
Now in your first drop down box include the call to this javascript code like so:
The id ajaxcontent is where our ajax is going to load the next drop down list
echo $this->Form->input('metal_id', ['options' => $metals, 'class'=>'form-control', 'label' => 'Select a Metal', 'placeholder'=>'metal_id', 'empty' => '--Select--', 'onchange'=>"changeContent(this.value)"]);
<div id="ajaxcontent">--Select one above--</div>Now the function that you are calling mentioned in the javascript:
Notice that we set the layout to ajax, as we don't want to include any other html in the return
public function getproducts() { $metal_id = $_REQUEST['metal_id']; $this->loadModel('Products'); $products = $this->Products->find('all', [ 'conditions'=>['Products.metal_id'=>$metal_id] ]); $pro = array(); foreach($products as $product) { $pro[$product['id']] = $product['name']; } $this->set('products', $pro); $this->viewBuilder()->layout('ajax'); }
The view for this function looks now like this, and if you want you can call a third drop down list here aswell
<?php echo $this->Form->input('product_id', ['options' => $products, 'class'=>'form-control', 'label' => 'Select a Product', 'empty' => '--Select--', 'placeholder'=>'product_id', 'onchange'=>"changePicture(this.value)"]); ?>
Second way of doing it
function getProducts(weight_id) {var metal_id = $('#metal').val();
var type_id = $('#type').val();
$("#loader").show();
$.ajax({
type: "POST",
url: "getproducts",
data: { metal_id: metal_id, type_id: type_id, weight_id: weight_id },
success: function(data){
$("#showproducts").html(data);
$("#loader").hide();
}
});
}
Published: 30th January 2021 by source:gabriel kolbe