简体   繁体   中英

How to make script tag work inside a div?

I am building an edit feature of a post on a website, so i am using jquery ajax and php as the script file that makes the edit inside a database. The problem is in the return script, i have a script tag which contains some jquery and then i place the returned data inside a div, but the script tag is being printed as if it was a text. Can someone help me please to let the script tag act as an actual script and not being printed as text ?

here is my html div :

<div class="board_post_span" id="<?php echo $board_id."-".$board_user_id;?>-spanBoardEdit"><?php echo $board_post;?></div>

and here is my php script :

<?php 
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
require_once '../includes/create_thumbnail.php';

// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
    exit;
}

if(isset($_POST['board_id'], $_POST['board_textarea'])) {
    $board_id = (int)$_POST['board_id'];
    $board_textarea = mysql_prep($_POST['board_textarea']);

    // UPDATE table
    $query  = "UPDATE board_table ";
    $query .= "SET board_post = '$board_textarea' ";
    $query .= "WHERE board_id = $board_id";
    $result = mysqli_query($connection, $query);

    // now we select the updated board post
    $query2 = "SELECT * FROM board_table ";
    $query2 .= "WHERE board_id = $board_id ";
    $result2 = mysqli_query($connection, $query2);
    confirm_query($result2);
    $result_array = mysqli_fetch_assoc($result2);


}
    ?>

    <?php
        echo $result_array['board_post'];
    ?>


    <script>
        // This takes care of the board Continue Reading feature ---------------------------------------------------------
        $(".board_post_span").each(function(){
            var boardPostText = $(this).text();
            var boardPostLength = boardPostText.length;
            var boardIdAttribute1 = $(this).attr("id");
            var boardIdAttributeArray1 = boardIdAttribute1.split("-");
            var boardPostId = boardIdAttributeArray1[0];
            var boardPostUserId = boardIdAttributeArray1[1];

            if(boardPostLength > 250) {
                var boardPostTextCut = boardPostText.substr(0, 250);
                $(this).text(boardPostTextCut+"...");
                $("#"+boardPostId+"-continueReading").remove();
                $(this).after('<a href="board_comment.php?user_id='+boardPostUserId+'&board_id='+boardPostId+'" class="board_continue_reading" target="_blank" id="'+boardPostId+'-continueReading">Continue Reading</a>');

            } else {
                $(this).text(boardPostText);
            }

        });
    </script>

and here is my jquery and ajax :

$.ajax({
    url: url_edit_board, 
    method: "POST",
    data: {
        board_id: saveBoardButtonId,
        board_textarea: editBoardTextareaVal
    },
    beforeSend: function() {
        CustomSending("Sending...");
    },
    success: function(data){
        $("#sending_box").fadeOut("Slow");
        $("#dialogoverlay").fadeOut("Slow");

        // this makes the scroll feature comes back
        $("body").css("overflow", "scroll");

        console.log(data);
        $("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").html(data);
        $("#"+saveBoardButtonId+"-formBoardEdit").hide();
        $("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").show();
    }
});

The reason is that you're setting boardPostText to the text of the entire DIV, which includes the <script> tag inside the DIV. You should put the text that you want to abbreviate inside another span, and process just that.

So change:

echo $result_array["board_post"];

to:

echo "<span class='board_post_text'>" . $result_array["board_post"] . "</span>";

Then in the JavaScript you're returning you can do:

    $(".board_post_text").each(function(){
        var boardPostText = $(this).text();
        var boardPostLength = boardPostText.length;
        var boardIdAttribute1 = $(this).attr("id");
        var boardIdAttributeArray1 = boardIdAttribute1.split("-");
        var boardPostId = boardIdAttributeArray1[0];
        var boardPostUserId = boardIdAttributeArray1[1];

        if(boardPostLength > 250) {
            var boardPostTextCut = boardPostText.substr(0, 250);
            $(this).text(boardPostTextCut+"...");
            $("#"+boardPostId+"-continueReading").remove();
            $(this).after('<a href="board_comment.php?user_id='+boardPostUserId+'&board_id='+boardPostId+'" class="board_continue_reading" target="_blank" id="'+boardPostId+'-continueReading">Continue Reading</a>');

        } else {
            $(this).text(boardPostText);
        }

    });

First of all, it seems you don't need else part:

 else {
     $(this).text(boardPostText);
 }

Then, before do anything, make sure that your return data from PHP file, the text has not become encrypted in some way. if < becomes &lt; then the text never consider as JS code.

You can create a script tag then place your JS script into it as a function then call it yourself right after injecting.

replace your script in PHP file with this:

<script>
var scriptText = `function editPost() {
    $(".board_post_span").each(function(){
        var boardPostText = $(this).text();
        var boardPostLength = boardPostText.length;
        var boardIdAttribute1 = $(this).attr("id");
        var boardIdAttributeArray1 = boardIdAttribute1.split("-");
        var boardPostId = boardIdAttributeArray1[0];
        var boardPostUserId = boardIdAttributeArray1[1];

        if (boardPostLength > 250) {
            var boardPostTextCut = boardPostText.substr(0, 250);
            $(this).text(boardPostTextCut+"...");
            $("#"+boardPostId+"-continueReading").remove();
            $(this).after('<a href="board_comment.php? 
 user_id='+boardPostUserId+'&board_id='+boardPostId+'" class="board_continue_reading" target="_blank" id="'+boardPostId+'-continueReading">Continue Reading</a>');
        }
    });
}`
</script>

then change your js file to:

$.ajax({
    // ...
    success: function(data) {
        // ...

        var container = $("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit")
        container.html(data)
        var scriptEl = $('<script></script>').html(scriptText).appendTo(container)

        // now call the editPost function
        editPost()

        $("#"+saveBoardButtonId+"-formBoardEdit").hide();
        container.show();
    }
});

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