0

I have multiple pages of html code saved into a database. I want a file to be able to flip through each of these pages without reloading.

I created a PHP file to pull all the pages into a database.

The page shows the first page and navigation buttons.

There is also javascript to put all the other pages into an array so I can quickly switch pages.

var pages = new Array();
<?php foreach ($coursePages as $page): ?>
    pages[pageCount] = "<?php echo ($page['body']) ?>";
    pageCount++;
<?php endforeach ?>

My problem is creating the javascript array. How can I escape the data from the echo properly so it can eventually change the page content using the following:

$(document).ready(function() {
    $('.navNext, .navPrevious').click(function({
        if ($(this).hasClass('navNext')) {
            page++;
            if (page > pageCount) {
                page = 0;
            }
        } else {
            page--;
            if (page < 0) {
                page = 0;
            }
        }

        $('.page').html(pages[page]);
    }))
});
1
  • 1
    May be it's better to render this pages to <div id="page1" class="pages hidden"> content </div> and than just switch divs visibiblity? $('.pages').hide();$('#page'+uid).show(); ? Commented Dec 11, 2013 at 19:32

2 Answers 2

1

Anytime you send values dynamically from PHP to JavaScript, you can simply use json_encode(). It will always produce valid JavaScript and handle all data types. Example:

<script>
    var a = <?php echo json_encode($var)?>;
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

This was kind of where I was going but for some reason it didn't seem to work properly. I tried it again and now it is.
1

you can use this function to escape js values:

function js_escape_string($str)
{
    $str = str_replace("\\", "\\\\", strval($str));
    $str = str_replace("'", "\\'", $str);
    $str = str_replace("\r", "\\r", $str);
    $str = str_replace("\n", "\\n", $str);
    $str = str_replace("\t", "\\t", $str);
    $str = str_replace("</script>", "</'+'script>", $str);
    return $str;
}

NOTE: use single quote ' around JS values, like:

<script>
var a = '<?php echo js_escape_string(....); ?>';
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.