加载PHP变量值后触发函数

The intention is edit an invioce based on the invoice_id value received from the selection of a particular invoice from the invoice list table. Since this is an edit form, the invoice related details should be pre-loaded from the database.

The code looks as follows:

$invoice_id= base64_decode($_REQUEST['invoice_id']);
require_once '../model/invoice.php';
$obj=new Invoice();
$val=mysql_fetch_assoc($obj->getInvoiceDetailsForEdit($invoice_id));

The HTML of the hidden input text field is:-

<input type="hidden" name="inv_no" id="inv_no" value="<?php echo $invoice_id ?>"/>

The Script that is to be triggered inorder to get the preselected category is:-

<script>
        function getSelectedCategory(inv_no){
            if(inv_no!==""){
               var request = $.ajax({
                   url: "../controller/invoice.php",
                   type: "POST",
                   data: {inv_no:inv_no,action:'get_selected_category'},  
                   dataType: "json"
               });
               request.done(function(json_return){ 
                   $('#category').val(json_return['category_code']);
               });  
               request.fail(function(jqXHR, textStatus) {
                   alert( "Request failed: " + textStatus );
                   return false;
               });
           }
        }
</script>

The Controller code:-

function getSelectedCategory(){
    $inv=$_POST['inv_no'];
    require_once '../model/invoice.php';
    $obj=new Invoice();
    $result=mysql_fetch_assoc($obj->getAllInvoiceDetailsForViewing($inv));
    echo json_encode($result);
    exit;
}

Everything is working perfectly except the fact that I don't know what to do to run the script after the php variable $invoice_id is being loaded since the text field cannot accept events as it is a hidden field..

I had changed the code as similar to the below one and found it is working:

<input type="text" name="inv_no" id="inv_no" value="<?php echo $invoice_id ?> onblur="getSelectedCategory(this.value)"/>

Any suggestions would be very helpful!!

have you tried this:

function getSelectedCategory(inv_no){

window.onload = function(){
if(inv_no!==""){
               var request = $.ajax({
                   url: "../controller/invoice.php",
                   type: "POST",
                   data: {inv_no:inv_no,action:'get_selected_category'},  
                   dataType: "json"
               });
               request.done(function(json_return){ 
                   $('#category').val(json_return['category_code']);
               });  
               request.fail(function(jqXHR, textStatus) {
                   alert( "Request failed: " + textStatus );
                   return false;
               });
           }
        }

}


}

I have added window.onload event to your JS function to make sure every element is loaded.