views:

77

answers:

2

So on my site, a user can post a comment on 2 things: a user's profile and an app. The code works fine in PHP but we decided to add Ajax to make it more stylish. The comment just fades into the page and works fine.

I decided I wanted to make a function so that I wouldn't have to manage 2 (or more) blocks of codes in different files. Right now, the code is as follows for the two pages (not in a separate .js file, they're written inside the head tags for the pages.):

// App page
$("input#comment_submit").click(function() {
var comment = $("#comment_box").val();
$.ajax({
type: "POST",
url: "app.php?id=<?php echo $id; ?>",
data: {comment: comment},
success: function() {
$("input#comment_submit").attr("disabled", "disabled").val("Comment Submitted!");
$("textarea#comment_box").attr("disabled", "disabled")
$("#comments").prepend("<div class=\"comment new\"></div>");
$(".new").prepend("<a href=\"profile.php?username=<?php echo $_SESSION['username']; ?>\" class=\"commentname\"><?php echo $_SESSION['username']; ?></a><p class=\"commentdate\"><?php echo date("M. d, Y", time()) ?> - <?php echo date("g:i A", time()); ?></p><p class=\"commentpost\">" + comment + "</p>").hide().fadeIn(1000);
}
});
return false;
});

And next up,

// Profile page
$("input#comment_submit").click(function() {
var comment = $("#comment_box").val();
$.ajax({
type: "POST",
url: "profile.php?username=<?php echo $user; ?>",
data: {comment: comment},
success: function() {
$("input#comment_submit").attr("disabled", "disabled").val("Comment Submitted!");
$("textarea#comment_box").attr("disabled", "disabled")
$("#comments").prepend("<div class=\"comment new\"></div>");
$(".new").prepend("<a href=\"profile.php?username=<?php echo $_SESSION['username']; ?>\" class=\"commentname\"><?php echo $_SESSION['username']; ?></a><p class=\"commentdate\"><?php echo date("M. d, Y", time()) ?> - <?php echo date("g:i A", time()); ?></p><p class=\"commentpost\">" + comment + "</p>").hide().fadeIn(1000);
}
});
return false;
});

Now, on each page the box names will always be the same (comment_box and comment_submit) so what do you guys think of this function (Note, the postComment is in the head tag on the page.):

// On the page, (profile.php)
$(function() {
    $("input#comment_submit").click(function() {
        postComment("profile", "<?php echo $user ?>", "<?php echo $_SESSION['username']; ?>", "<?php echo date("M. d, Y", time()) ?>", "<?php echo date("g:i A", time()); ?>");
    });
});

Which leads to this function (which is stored in a separate file called functions.js):

function postComment(page, argvalue, username, date, time) {
    if (page == "app") { var arg = "id"; }
    if (page == "profile") { var arg = "username"; }
    var comment = $("#comment_box").val();

    $.ajax({
        type: "POST",
        url: page + ".php?" + arg + "=" + argvalue,
        data: {comment: comment},
        success: function() {
            $("textarea#comment_box").attr("disabled", "disabled")
            $("input#comment_submit").attr("disabled", "disabled").val("Comment Submitted!");
            $("#comments").prepend("<div class=\"comment new\"></div>");
            $(".new").prepend("<a href=\"" + page + ".php?" + arg + "=" + username + "\" class=\"commentname\">" + username + "</a><p class=\"commentdate\">" + date + " - " + time + "</p><p class=\"commentpost\">" + nl2br(comment) + "</p>").hide().fadeIn(1000);
        }
    });
    return false;
}

That's what I came up with! So, some problems: When I hit the button the page refreshes. What fixed this was taking the return false from the function and putting it into the button click. Any way to keep it in the function and have the same effect?

But my real question is this: Can any coders out there that are familiar to jQuery tell me techniques, coding practices, or ways to write my code more efficiently/elegantly? I've done a lot of work in PHP but I know that echoing the date may not be the most efficient way to get the date and time.

So any tips that can really help me streamline this function and also make me better with writing jQuery are very welcome!

+1  A: 

To address your big overarching question, I'd suggest getting a copy of jQuery In Action from your local library as well as a good JavaScript book (do a search in SO to find a couple).

Zian Choy
My local library is actually going down so I may go by and pick up a jQuery book from there. Thanks for reminding me about the power of literature!
NessDan
+2  A: 

I would first make my forms have all the data so that if the user doesn't have javascript the page still will work:

<form action="profile.php" id="comment_form">
    <input type="hidden" name="username" value="<?php echo $user; ?>" />
    <textarea id="comment_box" name="comment"></textarea>
    <input type="submit" id="comment_submit" value="Submit" />
</form>

<form action="app.php" id="comment_form">
    <input type="hidden" name="id" value="<?php echo $id; ?>" />
    <textarea id="comment_box" name="comment"></textarea>
    <input type="submit" id="comment_submit" value="Submit" />
</form>

Then your javascript can be:

$('#comment_form').submit(function(e){
    e.preventDefault();
    var form = $(this),
        submit = $("#comment_submit").attr("disabled", "disabled");
    $("#comment_box").attr("disabled", "disabled");
    $.ajax({
        type: "POST",
        url: form.attr('action'),
        data: form.serialize(),
        success: function(comment) {
            submit.val("Comment Submitted!");
            $("<div class=\"comment new\"></div>").prependTo("#comments")
                .prepend(comment)
                .hide()
                .fadeIn(1000);
        }
    });
});

I would have my ajax request that submits the comment return the html formated comment rather then build it in javascript so that I don't have to update the template in two places. I am also using the submit event on the form rather then the click event on a button since it caches forms getting submitted by other ways then clicking a button.

PetersenDidIt
Thank you so much, this function makes things so much easier!(Hi-Five)
NessDan