how to rexcute javascript with out reloading page

i have a form that send data to php page

 $.ajax({
                    type: "POST",
                    url: "/page.php",
                    data: 'comment='+variable+'&postid='+variable1+'&postid2='+variable2,
					cache:false,
                    success: function(html){
							
                        })
                    }  
                });

the php echo back some html code and add it to my html page

like this

<span style="margin-left:17px;font-weight: bold;cursor: pointer;" onclick="showText();" id="commentsh10"> show text</span>

the new html contain on-click that fire function but the function dont recognize this new element so that i need a way to re execute the function and all JavaScript on the same page

Note : that this javascript function not include in file that have a src in the header like some js script

1 answer

  • answered 2017-01-11 14:21 P. Frank

    This is because is a dynamic element. Remove your onclick function and add the below code in your Jquery:

    $(document).on("click","#commentsh10",function(){
       showText();
    })
    

    UPDATE

    You can construct your js file in a way that all your script is accessible. Example:

    $(document).ready(function(){
    
       $(document).on("click","#commentsh10",function(){
           showText()
       })
    
        $.ajax({
            type: "POST",
            url: "/page.php",
            data: 'comment='+variable+'&postid='+variable1+'&postid2='+variable2,
            cache:false,
            success: function(html){
                loadScript()    
            })
        }  
    
    });
    
    function loadScript(){
        a = 0;
        b = 1;
    
        if(a == 0){
            b=2;
            showText();
        }
    }
    
    function showText(){
        $(".myElement").html(yourvalue);
    }