开发者

How can I move this ajax program to wordpress?

Update: someone answered and suggested that I write a plugin, but that is a solution that is way above my skill level at this point. Is there a simpler way?

I have a little program that uses jQuery/Ajax to interact with the database via a php script Shoutbox.php.

It's a really simple set up (perfect for a newbie to understand).

However, I want to put the program in a WordPress CMS, which is making it more complicated for me. Can anyone give me advice on these three issues?

a) where would I put shoutbox.php (see below) in the wordpress files? Can I add an extra file or would it go in another file, like custom_functions.php?

example.com/wp-content/themes/thesis_18/custom/custom_functions.php

b) how to connect to the database from wherever shoutbox.php ends up?

c) how would I refer to the path in the javascript? The javascript will be in a custom functions file, but then how do I get the path to where the shoutbox.php is?

The jquery code moved into a php file in the plugin folder.

<?php

/*
Plugin Name: Shoutbox plugin
Plugin URI: http://www.eslangel.com/aboutmyplugin
Description: Shoutbox plugin
Author: Me!
Version: 1.0
Author URI: http://www.eslangel.com
*/



function my_function (){  ?>

<script type="text/javascript">

$(document).ready(function(){
    //global vars
    var inputUser = $("#nick");
    var inputMessage = $("#message");
    var loading = $("#loading");
    var messageList = $(".content > ul");

    //functions
    function updateShoutbox(){
        //just for the fade effect
        messageList.hide();
        loading.fadeIn();
        //send the post to shoutbox.php
        $.ajax({
            type: "POST", url: "<?php echo $pluginDirectory = dirname(plugin_basename(__FILE__));?>/shoutbox.php", data: "action=update",
            complete: function(data){
                loading.fadeOut();
                messageList.html(data.responseText);
                messageList.fadeIn(2000);
            }
        });
    }
    //check if all fields are filled
    function checkForm(){
        if(inputUser.attr("value") && inputMessage.attr("value"))
            return true;
        else
            return false;
    }

    //Load for the first time the shoutbox data
    updateShoutbox();

    //on submit event
    $("#form").submit(function(){
        if(checkForm()){
            var nick = inputUser.attr("value");
            var message = inputMessage.attr("value");
            //we deactivate submit button while sending
            $("#send").attr({ disabled:true, value:"Sending..." });
            $("#send").blur();
            //send the post to shoutbox.php
            $.ajax({
                type: "POST", url: "<?php echo $pluginDirectory = dirname(plugin_basename(__FILE__));?>/shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message,
                complete: function(data){
                    messageList.html(data.responseText);
                    updateShoutbox();
                    //reactivate the send button
                    $("#send").attr({ disabled:false, value:"Shout it!" });
                }
             });
        }
        else alert("Please fill all fields!");
        //we prevent the refresh of the page after submitting the form
        return false;
    });
});

</script>
<?php

}

add_action('wp_head', 'my_function');

Shoutbox.php

<?php
define("HOST", "localhost:8889");  
define("USER", "root");  
define("PASSWORD", "root");  
define("DB", "shoutbox");  

/************************
    FUNCTIONS
/************************/
function connect($db, $user, $password){
    $link = @mysql_connect($db, $user, $password);
    if (!$link)
        die("Could not connect: ".mysql_error());
    else{
        $db = mysql_select_db(DB);
        if(!$db)
            die("Could not select database: ".mysql_error());
        else return $link;
    }
}
function getContent($link, $num){
    $res = @mysql_query("SELECT date, user, message FROM shoutbox ORDER BY date DESC LIMIT ".$num, $link);
    if(!$res)
        die("Error: ".mysql_error());
    else
        return $res;
}
function insertMessage($user, $message){
    $query = sprintf("INSERT INTO shoutbox(user, message) VALUES('%s', '%s');", mysql_real_escape_string(strip_tags($user)), mysql_real_escape_string(strip_tags($message)));
    $res = @mysql_query($query);
    if(!$res)
        die("Error: ".mysql_error());
    else
        return $res;
}

/******************************
    MANAGE REQUESTS
/******************************/
if(!$_POST['action']){
    //We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php
    header ("Location: index.html"); 
}
else{
    $link = connect(HOST, USER, PASSWORD);
    switch($_POST['action']){
        case "update":
            $res = getContent($link, 20);
            while($row = mysql_fetch_array($res)){
                $result .= "<li><strong>".$row['user']."</strong><img src=\"css/images/bullet.gif\" alt=\"-\" />".$row['message']." <span class=\"date\">".$row['date']."</span></li>";
            }
            echo $result;
            break;
        case "insert":
            echo insertMessage($_POST['nick'], $_POST['message']);
            break;
    }
    mysql_close($link);
}

I took the html from my index.html page in the original applicaiton and put it i开发者_Python百科n a text widget in the sidebar.

   <a id="logo" title="Go to eslangel!" href="http://www.eslangel.com"><img src="http://eslangel.com/wp-content/plugins/myplugin/css/images/logo.jpg" alt="eslangel.com" /></a>  
    <form method="post" id="form">  
        <table>  
            <tr>  
                <td><label>User</label></td>  
                <td><input class="text user" id="nick" type="text" MAXLENGTH="25" /></td>  
            </tr>  
            <tr>  
                <td><label>Message</label></td>  
                <td><input class="text" id="message" type="text" MAXLENGTH="255" /></td>  
            </tr>  
            <tr>  
                <td></td>  
                <td><input id="send" type="submit" value="Shout it!" /></td>  
            </tr>  
        </table>  
    </form>  
    <div id="container">  
        <ul class="menu">  
            <li>Shoutbox</li>  
        </ul>  
        <span class="clear"></span>  
        <div class="content">  
            <h1>Latest Messages</h1>  
            <div id="loading"><img src="http://eslangel.com/wp-content/plugins/myplugin/css/images/loading.gif" alt="Loading..." /></div>  
            <ul>  
            <ul>  
        </div>  
    </div>  


I would create a plugin. This is very useful for a few reasons

  1. It can easily be turned on and off. So it can be distributed quickly or versioned for testing purposes.
  2. You can sandbox it so that it won't interfere with Wordpress. This let's you see whether it could be breaking WP (perhaps after an update)
  3. Plugins get access to special functions. Like asking WP what your plugin directory is. Now you can move your plugin between different sites and the paths won't break.

Read more about plugin development on Wordpress! http://codex.wordpress.org/Writing_a_Plugin

Creating a plugin is actually really easy. Just go to the plugins folder located in your wp-content directory and make a new folder. Place a myplugin.php file in it with the following comment structure at the top

/*
Plugin Name: Shoutbox plugin
Plugin URI: http://www.mywebsite.com/aboutmyplugin
Description: Shoutbox plugin
Author: Me!
Version: 1.0
Author URI: http://www.mywebsite.com
*/

Copy shoutbox.php into this folder also. Don't include the header info above.

In your main file now you just have to do two things.

  1. Inject the javascript into each pages head by adding this to myplugin.php -

    add_action('wp_head', 'my_function');
    function my_function() { 
      //your javascript from above. make sure it is php escaped
    }
    
  2. Point the ajax bit at the shoutbox.php file so that it can do its thing.

    //change
    url: "shoutbox.php"
    //to
    <?php $pluginDirectory = dirname(plugin_basename(__FILE__)); ?>
    url: <?php $pluginDirectory + /shoutbox.php; ?>
    

Make sure you activate your plugin from the plugins page of your wordpress site. What this whole sequence basically does is:

  1. Creates a plugin
  2. Injects your javascript into the top of every wordpress page
  3. Modifies the javascript dynamically so that it can find the location of shoutbox.php in your plugin directory.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜