Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 947
Meimuri Avatar asked Jul 19 '16 03:07

Meimuri


People also ask

What can I use instead of Onchange?

Another JavaScript event that is quite similar to onchange is oninput . The difference is that oninput is triggered every time the value of an element changes even while it still is in focus.

Can a div have Onchange?

No; the onchange attribute is only applicable to form field elements ( input , select , textarea , etc). Thanks for your answer. How do I do it?

How to use onchange method in jQuery?

Definition and UsageThe change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.


1 Answers

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>
like image 187
Rasclatt Avatar answered Sep 28 '22 05:09

Rasclatt