3

I'm working on my first Single Page Application, and I'm not sure the best way to go about storing the page data.

I have it set up so that the page contents is saved in my database, and when a user clicks on one of the navigation links, it does an ajax call to a process file which extracts the page contents, formats it as json and echos it back so that the jQuery can populate the page.

The issue I'm having is that if any of the page contents in the database contains PHP, the PHP is not being processed or even displayed (however if I view source I see the raw php). Is their a better way to go about this so that the code will run?

My Ajax Call:

$("nav a").click(function(e) {
    e.preventDefault();
    var page = $(this).attr("href");
    $("nav a").removeClass("menuSelected");
    $(this).addClass("menuSelected");

    form_data = {
        action: "load",
        page: page,
        is_ajax: 1
    }

    $.ajax({
        type: "post",
        url: "process.php",
        dataType: "json",
        data: form_data,
        success: function(data) {
            if(data.success === "true") {
                $("#asideLeft").html(data.aside_left);
                $("#contentMiddle").html(data.content_middle);
                $("#asideRight").html(data.aside_right);
            } else {
                $("#contentMiddle").html("<h1>AJAX Failure</h1>");
            }
        }
    });

My PHP Code that get called when a user clicks on the link:

if($action == "load") {
    $pms->connect();
    $result = $pms->dbh->prepare("SELECT * FROM pages WHERE name=:name");
    $result->execute(array(':name' => $page));
    $page = $result->fetch(PDO::FETCH_OBJ);
    $data['success'] = "true";
    $data['aside_left'] = $page->aside_left;
    $data['content_middle'] = $page->content_middle;
    $data['aside_right'] = $page->aside_right;
    echo json_encode($data);
}

and a sample of the HTML/PHP that is being saved in the database:

<h1>Content Middle</h1>
<p>Today is <?php echo date("Y-m-d H:i:s"); ?> </p>

Thank you for any help or suggestions you can provide.

3
  • do you really need it to be all-ajax? Why not take a classical approach with having the code where it belongs - in seperate files? Or are you trying to build something cms-like? Commented Nov 14, 2012 at 0:04
  • Thank you for using prepared statements. It's refreshing to see ha Commented Nov 14, 2012 at 0:05
  • I want it to run as a Single Page Application, meaning no page refreshes, so far every other aspect is working. I want the code in a database to make it easy to retrieve and change. I'm open to other methods of storing the data, but it must be retrievable via an ajax call so I avoid page flashes. Thanks for commenting! Commented Nov 14, 2012 at 0:07

3 Answers 3

1

+1 for the question. I agree that php code and the html (from the database) should be separated. In particular, while assembling the json data on the server side, you should invoke all the php code that you are now storing in the database. So, instead of storing in the database something like:

<p>Today is <?php echo date("Y-m-d H:i:s"); ?> </p>

You could write something like:

$data['success'] = "true";
$data['aside_left'] = $page->aside_left;
$data['content_middle'] = $page->content_middle;
$data['aside_right'] = "<p>Today is" . date("Y-m-d H:i:s") . "</p>";
echo json_encode($data);

Yes, this is not as clean as just retrieving data from the database, but all the server-side scripts should be executed on the server side. Problems like this one in particular - like printing today's date and similar - can be solved using JavaScript, which can be stored in the database hassle-free (e.g. you store in the database a function that,once loaded on the server side, returns current date). This can be achieved if you store in the database a record like this one:

"<p><script>(new Date()).toString('dddd, MMMM ,yyyy');</script></p>"

Once loaded, it will display the current date inside the p tags.

Another solution, if JavaScript simply isn't an option and you have to use PHP, this could be achieved with another request to the server side, as such:

.
.
$data['aside_right'] = "<p>Today is:<script> $.ajax({type:'post',url:'processSomeMore.php',dataType:'json',data:form_data,success:function(data) {...}});
</script></p>";
echo json_encode($data);

Once the JavaScript code is sent to the client along with the rest of the html retrieved from the database, it will issue another request to the server, demanding for additional data through ajax. Hope this is not too confusing :-).

Sign up to request clarification or add additional context in comments.

2 Comments

Not to confusing at all. The date thing was just theory code I was using to try and get PHP to execute. The real request will contain very complex data that will invoke other Ajax calls. I think I'm going to take some of what you have written, and try and rework a new solution. Thank you for the comment, and I'll post back with my results.
After working around a little bit, I have found a solution that works, just not as gracefully as I had hoped. I've created several files, one for each section of each page, and I dynamically load them with jQuery's .load event. I really wanted to avoid using a ton of files, but it seems to be the only good way to get the PHP code to run without the downfall of eval(). Thank you for your time and suggestion.
0

it is because php is a server side scripting lan and you cant parse it to client unless instead it was js/jquery script that will load result from php script via ajax.

Comments

0

Well, you can't just export the database content; you'll have to go through eval(). But where this is particularly hard in your example is that eval only handles PHP code; it can't deal with the mix of PHP and HTML that you provide. So either you make the database snippets all be PHP only (by having the HTML stuff echo-ed or printed) or you'll have to invest time and energy into understanding how to seperate out the stuff. (The latter problem at first might look as something for a regexp, but turns out to be truly hard to completely solve).

But maybe what you want to be looking at is not a combination of full PHP and HTML, but rather a templating language – storing, for example, Smarty snippets in the database that you process with Smarty before you deliver them? (We've used such a data flow -- smarty output over AJAX -- successfully in two products of our own.)

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.