#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Location
    Burb of Detroit, Michigan
    Posts
    107
    Rep Power
    97

    JQuery, Ajax and PHP - Need Help Please


    This is driving me bonkers, I'm trying to use jQuery(JavaScript) with my CMS that I developed using PHP (Which is working great, so far). This will enable the user to add/edit a page without having the page reloading. I can get it where it loads the data in correctly:

    data.php
    PHP Code:
    <?php

    require('includes/utilities.inc.php');

    $id 80;

    try {
        
    $query 'SELECT title, content FROM pages WHERE id=:id';
        
    $stmt $pdo->prepare($query);
        
    $result $stmt->execute(array(':id' => htmlspecialchars($id)));

        
    // If the query ran OK, fetch the record into an object:
        
    if ($result) {
            
    $stmt->setFetchMode(PDO::FETCH_CLASS'Page');
            
    $page $stmt->fetch();
            
    $title $page->getTitle();
            
    $content nl2br($page->getContent());
        } else {
            throw new 
    Exception('An invalid page ID was provided to this page');
        }
        
    } catch (
    Exception $e) { // Catch generic exceptions
        
    include('views/error.html');
    }

    class 
    ReadPage {

        public 
    $title;
        public 
    $content;

        public function 
    __construct($title$content) {
            
    $this->title $title;
            
    $this->content $content;
        }

    }

    $e = new ReadPage($title$content);


    print 
    json_encode($e);
    ?>
    Retrieves data fine:
    Building a website doesn't start with actual writing of code for the website, it starts with research that the Web Designer has done on the Client. Pepster's Place will research the business and will have a full understanding of your needs. We will ask the important questions about target audience, goals, creative direction and other variables, such as budget and deadlines. After the Researching phase is complete, Pepster's Place will have a solid background for the site that will eventually lead to designing and developing the website.
    However, when I go save the data:

    save_data.php
    PHP Code:
    <?php

    require('includes/utilities.inc.php');

    $id 80;

    try {
        
    $query 'SELECT  title, content FROM pages WHERE id=:id';
        
    $stmt $pdo->prepare($query);
        
    $result $stmt->execute(array(':id' => htmlspecialchars($id)));

        
    // If the query ran OK, fetch the record into an object:
        
    if ($result) {
            
    $stmt->setFetchMode(PDO::FETCH_CLASS'Page');
            
    $page $stmt->fetch();
            
    $title $page->getTitle();
            
    $content nl2br($page->getContent());
        } else {
            throw new 
    Exception('An invalid page ID was provided to this page');
        }
        
    } catch (
    Exception $e) { // Catch generic exceptions
        
    include('views/error.html');
    }

    class 
    ReadPage {

        public 
    $title;
        public 
    $content;

        public function 
    __construct($title$content) {
            
    $this->title $title;
            
    $this->content $content;
        }

    }

    $e = new ReadPage($title$content);


    print 
    json_encode($e);
    ?>
    When I go pull it up from the database after editing this, I get this:

    Loaded data:
    "Building a website doesn't start with actual writing of code for the \nwebsite, it starts with research that the Web Designer has done on the \nClient. Pepster's Place will research the business and will have a full \nunderstanding of your needs. We will ask the important questions about \ntarget audience, goals, creative direction and other variables, such as \nbudget and deadlines. After the Researching phase is complete, Pepster's\n Place will have a solid background for the site that will eventually \nlead to designing and developing the website."

    It puts " and \n into the string (content) and finally here's my html file:

    index.html
    PHP Code:
    <!DOCTYPE html>
    <
    html>
        <
    head>
            <
    title>Demo JSONAJAX and CMS Website</title>
            <
    link href="css/stylesheet.css" rel="stylesheet">
            <
    meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <
    script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
            <script type="text/javascript">

                $(document).ready(function() {



                    $.getJSON("data.php", function(info) { // Load data:

                        var updateTitle = document.getElementById('titleCMS');
                        updateTitle.innerHTML = info.title;
                        var updateContent = document.getElementById('contentCMS');
                        updateContent.innerHTML = info.content;



                    }); //getJSON

                    $("#save").click(function() {
                        
                        var content = $('#contentCMS').html();
                        
                        $.ajax(
                                {
                                    type: "POST",
                                    url: "save_data.php",                            
                                    dataType: 'json',
                                    data: {content: content},
                                    success: function(data) {
                                        $("#debug_message").html("saved file");
                                    },
                                    failure: function() {
                                        $("#debug_message").html(
                                                "An error has occured trying to save the file");
                                    }
                                });
                    });

                }); // ready

            </script>
        </head>
        <body> 
    Sorry for being so long, but I sometimes have a hard time conveying what the problem is, if anyone wants I can shorten down the code (just let me know). Anyways, I have tried almost everything (obviously to not the correct way ) I can think off, searched Google, read a few books on JQuery, AJAX, JSON and PHP but to no avail. Any help will be greatly appreciated.

    John

    P.S. This code won't be going on my live site, I'm just testing this out on my local server seeing if I can get it work properly.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Location
    Burb of Detroit, Michigan
    Posts
    107
    Rep Power
    97
    Well, I solved it on my own

    Change index.html:

    Code:
                $(document).ready(function() {
    
                    $.getJSON("data.php", function(info) { // Load data:
                        var title = info.title;
                        var content = info.content;
                        
                        var updateTitle = document.getElementById('titleCMS');
                        updateTitle.innerHTML = title;
                        
                        var updateContent = document.getElementById('content');
                        updateContent.innerHTML = '<p>' + content + '</p>';
                        
                    }); //getJSON
    
                    $("#save").click(function() {
                        
                        var content = $('#content').html();
                        
                        $.ajax(
                                {
                                    type: "POST",
                                    url: "save_data.php",                            
                                    dataType: 'text',
                                    data: {content: content},
                                    success: function(data) {
                                        $("#debug_message").html("saved file");
                                    },
                                    failure: function() {
                                        $("#debug_message").html(
                                                "An error has occured trying to save the file");
                                    }
                                });
                    });
    
                }); // ready
    Code:
            <section>
                <header></header>
                <article>
                    <div id="debug_message"></div>
                    <div id="title"><h1 id="titleCMS"></h1></div>
                    <div id="content" contentEditable="true"></div>
                    <button id="save">Save</button>
                </article>
                <footer></footer>
            </section>

    save_data.php
    PHP Code:
    <?php

    $id 
    80;

    require(
    'includes/utilities.inc.php');

    // Strip the <p> tags from content
    $content =  strip_tags($_POST['content'], '<br>');

    // Update the edited text:     
    $query 'UPDATE  pages SET content=:content, dateUpdated=NOW() WHERE id=:id';

    // Prepare the Statement:
    $stmt $pdo->prepare($query);

    $data = array('content' => $content);



    // execute the statement:
    $show_details $stmt->execute(array(':content' => $content':id' => $id));
    ?>

    Comments on this post

    • ManiacDan agrees : Good work

IMN logo majestic logo threadwatch logo seochat tools logo