简体   繁体   中英

How can i call a php function on a dynamically created html element in .js file

This is my product.php file which include the following php function

      <?php
       function getOfferName($conn,$companyID){
       $sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers` 
        WHERE `company_id`='$companyID'";
        if ($result=mysqli_query($conn,$sql)) {
          while ($row=mysqli_fetch_assoc($result)) {
          ?>
          <option value="<?php echo $row['id'] ?>"><?php echo $row['offer_name'] ?></option>
          <?php
           }
         }
       }
   ?>

This product.php file include the custom-js.js file in which i am creating a html element dynamically (Select dropdown).

$('.offerCheckBox').on('change', function() { 
    var id=$(this).data('id');
    if (!this.checked) {
    var sure = confirm("Are you sure want to remove offer ?");
    this.checked = !sure;
    }else{
        $(this).parent().parent().append('<select name="" id=""><?php getOfferName($conn,$companyID) ?></select>');

    }
});

Here i call php function getOfferName but it is showing me output like this enter image description here

<select name="" id=""><!--?php getOfferName($conn,$companyID) ?--></select>

You can do by below code

getdata.php

if($_POST['action'] == 1){
    $companyID = $_POST['id'];
    $sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers` 
     WHERE `company_id`='$companyID'";
     if ($result=mysqli_query($conn,$sql)) {
       $html = '';
       while ($row=mysqli_fetch_assoc($result)) {
       $html .= '<option value="'.$row['id'].'">'.$row['offer_name'].'</option>';
        }
      }
      echo json_encode($html);
      exit(0);
    }

?>

Ajax Call to Get Data

$('.offerCheckBox').on('change', function() { 
    var id=$(this).data('id');
    if (!this.checked) {
    var sure = confirm("Are you sure want to remove offer ?");
    this.checked = !sure;
    }else{

        $.ajax({
            url: "getdata.php",
            type: 'POST',
            data: {id:id,action:1},
            dataType: "json",
            contentType: false,
            cache: false,
            processData: false,
            success: function(response) {

                if (response) {

                    $(this).parent().parent().append('<select name="" id="">'+response+'</select>');

                } else {
                    //Error
                }

                return true;
            }
        });



    }
});

the JavaScript file is on the client side writing code in this file will not will not create a server call that runs the PHP file.

if you want to combine JavaScript with a server call you should use ajax.

JavaScript:

 $('.offerCheckBox').on('change', function() { var id=$(this).data('id'); if (!this.checked) { var sure = confirm("Are you sure want to remove offer ?"); this.checked = !sure; } else { let fd = new FormData(); let companyID = $(this).val(); fd.append('companyID', companyID); $.ajax ({ url: "getOffer.php", type: "POST", data: fd, processData: false, contentType: false, complete: function (results) { let response = JSON.parse(results.responseText); my_function.call(this, response); } }); } }); // in this function you will put the append of the select box that php has created function my_function(response) { console.log("response", response); } 

PHP code (the file name is : getOffer.php)

   <?php

    $companyID = $_REQUEST['companyID'];
    $options = array[];

    $sql="SELECT `id`, `offer_name`, `offer_discount` FROM `oiw_product_offers` 
    WHERE `company_id`='$companyID'";
    if ($result=mysqli_query($conn,$sql)) {

        while ($row=mysqli_fetch_assoc($result)) {
                $options[$row['id']] = $row['offer_name'];    
        }
    }  

     $resBack = (json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
     echo ($resBack);  

?>

Now in the callback function my_function as we wrote above you have an array of key value pair from the PHP. iterate on this array in JavaScript build your option select items and append them to the select box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM