简体   繁体   English

如何在php foreach循环中调用javascript函数

[英]How to call javascript function inside php foreach loop

Good day, i am having a trouble regarding calling my ajax function inside php for each loop, the objective of my code is to create a dynamic count of comments and appreciations, my problem is the the console says that my function is not defined 美好的一天,我在每次循环中在php内调用ajax函数时遇到麻烦,我的代码目标是创建动态的注释和赞赏计数,我的问题是控制台说我的函数未定义

Here is where i called my script, it is inside a foreach loop, take note. 这是我调用脚本的地方,它在foreach循环中,请注意。

    <?php foreach($allDiscussion as $data): ?>
        <div class="col s12 com_app_count_section">
            <script>count_app_and_com('<?=$data->discussion_id?>');</script>
        </div>
<?php endforeach; ?>



and here is my script code 这是我的脚本代码

<script>
    $(function(){
    //Add New
    $('.btnCommentSubmit').click(function(e){
        e.preventDefault();
        var discussion_id_val = $(this).data("value");
        var account_user_id_val = $(this).data("id");
        $('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/');
        var url = $('#formAddComment').attr('action');
        var addCommentTxt = $(this).closest('#formAddComment').find('.addCommentTxt').val();
        $.ajax({
            type: 'post',
            url: url,
            data: {
                addCommentTxt:addCommentTxt,
                discussion_id:discussion_id_val,
                account_user_id:account_user_id_val,
            },
            success: function(e){
                $('.addCommentTxt').val("");
                showAllComments(discussion_id_val);
            },
            error: function(e){
                console.log(e);
                alert('Could not add data');
            }
        });

    });

});

    function count_app_and_com(discussion_id_val){
        console.log(discussion_id_val);
    }


    function showAllComments(discussion_id_val){
        $.ajax({
            type: 'post',
            url: '<?php echo base_url() ?>Discussion/showAllComments/'+discussion_id_val,
            async: false,
            dataType: 'json',
            success: function(data){
                var html = '';
                var i;
                console.log(data);
                for(i=0; i<data.length; i++){
                    html += '<div class="row">'+
                    '<div class="chip ">'+
                    '<img src="<?=base_url()?>assets/img/sample.svg" alt="Contact Person">'+
                    data[i].name+
                    '</div>'+
                    '<span class="color-grey hide-on-med-and-down" style="font-size: 0.8vw;">'+
                    data[i].comment_at_formatted+'</span>'+
                    '<span class="color-grey hide-on-large-only" ><?=date('M d, Y',$data->discussion_posted_at)?>'+data[i].comment_at_formatted+'</span>'+
                    '<p class=" Comment'+data[i].comment_id+'">'+
                    data[i].comment_content+
                    '</p>'+
                    '</div>';
                }
                $('.comment_section').html(html);
            },
            error: function(){

            }
        });
    }   
</script>

You can simply call java script in you PHP file like this way. 您可以像这样以简单的方式在PHP文件中调用Java脚本。

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php

$arr = array('1','2','3','4','5','6','7');

foreach($arr as $val){
    echo "<script type='text/javascript'>$( document ).ready(function() {
    alert( '".$val."');
});</script>";
}
?>
</html>

You are calling the function before it's defined 您正在定义该函数之前

Here we can do a minimum example of your issue: 在这里我们可以为您的问题做一个最小的例子:

 <div class="col s12 com_app_count_section"> <script> count_app_and_com('10'); </script> </div> <script> function count_app_and_com(discussion_id_val){ console.log(discussion_id_val); } </script> 

Here you can see, by using a timeout, we show that the function is defined after the call is made. 在这里您可以看到,通过使用超时,我们可以看到该函数是在调用之后定义的。 The timeout allows the function to be registered while the code doing the executing is waiting. 超时允许在执行代码等待时注册功能。 This is an easy way to debug the issue as you don't have to move code around. 这是调试问题的简便方法,因为您无需四处移动代码。 However it's not a real "fix", unless your name is Trevor ... long story. 但是,这不是一个真正的“解决办法”,除非您的名字叫Trevor ...长话短说。

 <div class="col s12 com_app_count_section"> <script type="text/javascript" > setTimeout(function(){ count_app_and_com('10'); },1000); </script> </div> <script type="text/javascript" > function count_app_and_com(discussion_id_val){ console.log(discussion_id_val); } </script> 

So the easy fix, is to put the second script block ( the one the functions are defined in ) before the script block in the foreach. 因此,简单的解决方法是将第二个脚本块(在中定义函数的一个)放在foreach中的脚本块之前。 For example place the function definitions in the <head> of the document. 例如,将功能定义放在文档的<head>中。 Function defined first: 首先定义的功能:

 <script> function count_app_and_com(discussion_id_val){ console.log(discussion_id_val); } </script> <div class="col s12 com_app_count_section"> <script> count_app_and_com('10'); </script> </div> 

This last example, shows how this is an easy mistake to make, it's counter-intuitive. 最后一个示例显示了这是一个容易犯的错误,这是违反直觉的。 When placed in the same <script> tag it works fine. 当放置在相同的<script>标记中时,它可以正常工作。 I am sure there is some fancy technical reason for this: 我敢肯定这有一些花哨的技术原因:

 <script> count_app_and_com('10'); function count_app_and_com(discussion_id_val){ console.log(discussion_id_val); } </script> 

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

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