简体   繁体   中英

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

Here is where i called my script, it is inside a foreach loop, take note.

    <?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.

<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.

 <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. For example place the function definitions in the <head> of the document. 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. 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> 

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