简体   繁体   English

如何在.js文件中动态创建的html元素上调用php函数

[英]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 这是我的product.php文件,其中包含以下php函数

      <?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). 这个product.php文件包含custom-js.js文件,在其中我正在动态创建html元素(选择下拉列表)。

$('.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 在这里,我调用php函数getOfferName,但它向我显示了这样的输出, 在此处输入图像描述

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

You can do by below code 你可以通过下面的代码

getdata.php 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 Ajax调用以获取数据

$('.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. JavaScript文件位于客户端,在此文件中编写代码将不会创建运行PHP文件的服务器调用。

if you want to combine JavaScript with a server call you should use ajax. 如果要将JavaScript与服务器调用结合使用,则应使用ajax。

JavaScript: 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代码(文件名为: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. 现在在上面我们写的回调函数my_function中,您有一个来自PHP的键值对数组。 iterate on this array in JavaScript build your option select items and append them to the select box. 在JavaScript中对该数组进行迭代,构建您的选项选择项并将其附加到选择框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何调用一个函数,该函数的名称是通过结合node.js中的一些变量来动态创建的? - How can i call a function, whose name is dynamically created by combining some variables in node.js? 如何在动态创建的元素上调用jQuery函数 - How to call a jQuery function on dynamically created element 如何在JS中将创建的对象作为函数调用 - How can I call a created object as a function in JS 如何在js函数中使用我用php创建的数组 - How can I use an array I created with php in a js function 我无法在html的js文件中调用函数 - I can't call a function in js file at html 如何在DOM中的每个元素中调用函数,即使它们是动态创建的 - How to call a function in every element in the DOM even if they are dynamically created 如何从我的php文件中调用位于我的html文件中的javascript函数? - How can I call a javascript function located in my html file from my php file? 我无法选择使用jquery动态创建的html元素 - I can't select an html element that was created dynamically with jquery 我可以为动态创建的two.js元素添加类吗? - Can I add class to dynamically created two.js element? 如何将javascript对象连接到函数内动态创建的html元素 - how to connect a javascript object to a dynamically created html element inside a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM