Meimuri
Meimuri

Reputation: 71

AJAX run onchange event before the page load

So here's the scenario. I have 2 drop downs. The first one has the onchange function to load the data on the 2nd drop down. It's fully working but I would like to implement loading the data on the 2nd dropdown using the onchange function onload.

Here's my function:

function fetch_select(val)
    {
       $.ajax({
         type: 'post',
         url: '../function/fetch_car_package.php',
         data: {
           get_option:val
         },
         success: function (response) {
           document.getElementById("new_select").innerHTML=response; 
         }
       });
    }

Here's my dropdown:

<select name='cItemID' onchange="fetch_select(this.value);">
    <?php
    $sql = "";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $result = $sth->fetchAll();

    foreach($result as $row) {
        if ($_SESSION['cItemID'] == $row['Item ID']) {
            $selected = "selected";
        } else {
            $selected = '';
        }
        echo "<option value='".$row['Item ID']."' $selected>".$row['Item Name']."</option>";
    }
    ?>
</select>

My ajax processing page:

if(isset($_POST['get_option'])){
    $ItemID = $_POST['get_option'];
    $sql = "";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $result = $sth->fetchAll();

    foreach($result as $row) {
        echo "<option value='".$row['cCLID']."'    $selected>".$row['cDescription']."</option>";
    }

    exit;
}

Upvotes: 7

Views: 1114

Answers (2)

Santosh D
Santosh D

Reputation: 1302

Try adding a counter variable to keep track of 2nd <option> in the foreach iteration:

<select name='cItemID' > 
    <?php 
    $sql = $store =""; 
    $sth = $dbh->prepare($sql);
    $sth->execute(); 
    $count=0;
    $result = $sth->fetchAll();

    foreach($result as $row) {
        $count++;
         if ($_SESSION['cItemID'] == $row['Item ID']) {
            $selected = "selected";
        } 
        else {
            $selected = '';
        }

        $store = ($count==2)? "fetch_select(this.value)" : " ";
        echo "<option onselect='".$store."' value='".$row['Item ID']."' $selected>".$row['Item Name']."</option>";
    } 
    ?> 
</select>

It will add a string $store containing required javascript if the $count value reaches 2 otherwise leaves onselect=" ", if you select the 2nd option , it triggers the function with selected value.

You can go for onfocus or onclick or any other javascript event on <option> tag that gets your work done.

Upvotes: 1

Rasclatt
Rasclatt

Reputation: 12505

I (personally) don't like to run inline javascript if I can help it, so I would just use $(document).ready() for the load and .on('change') for the change action, both utilizing the same function:

<script>
// I am making an object for ajax reuse. You don't necessarily have to have this...premise is the same.
var Ajaxer  =   function($)
    {
        var $j      =   $;
        var useUrl  =   '../function/fetch_car_package.php';
        var url;

        this.setUrl =   function(url)
            {
                useUrl  =   url;
                return this;
            }

        this.ajax   =   function(data,func)
            {
                $j.ajax({
                    type: 'post',
                    url: useUrl,
                    data: data,
                    success: function (response) {
                        func(response);
                    }
               });
            }
    }
// When document loads
$(document).ready(function() {
    // Create ajax instance, pass jQuery
    var nAjax   =   new Ajaxer($);
    // Set the send function
    function getSelect(obj)
        {
            // Save the value
            var val =   obj.val();
            // Run the ajax
            nAjax.ajax({
                    "get_option":val
                },
                function(response){
                    // Send data to our container
                    $("#new_select").html(response);
                }
            );
        }
    // On load, save our select object
    var SelectMenu  =   $('select[name=cItemID]');
    // Run the function on load
    getSelect(SelectMenu);
    // On change, run the function
    SelectMenu.on('change',function(e) {
        // Use $(this) to reference itself
        getSelect($(this));
    });
});
</script>

Upvotes: 2

Related Questions