What I am trying to do is create a "save", "edit", and "hide: button for my website which applies to specific posts and comments, exactly like these buttons on Reddit. For now I am trying to self teach jQuery AJAX and attempting to figure out how to submit data to the database without having to reload the whole page. What I am attempting to do here is save a string by submitting it to a table called "Saved" when I click on "save", and edit, and hide the specific comment. However, the div id is static. I want to be able to make it dynamic when run through the loop so I can call the id selector in jQuery to complete the ajax functions for the specific comment. However, I cannot put php code into jQuery so calling the specific php $id variable is out of the question.
HTML and PHP5
<div id="main">
<?php
$comments = array("Message 1 is the first!", "Message 2 comes in second!", "This is the third message!");
for($i = 1; $i <= 3; $i++) {
$id = $i;
$comment = $comments[$i - 1];
displayMsg($id, $comment);
}
?>
<form action="ajaxexample.php" method="post" style="display: none" id="1234">
<input type="hidden" name="message" id="message" value="<?php echo $comment; ?>">
</form>
</div>
</form>
PHP function
// Replace message1 with $id
function displayMsg($id, $comment){
echo "<div id=\"message\" . $id ." style=\"border: solid 1px; width: 20%;\">";
echo "<div id=\"pmessage\"><p>$comment</p></div>";
echo "<a href=\"#\" class=\"Save\" style=\"color: blue;\">Save</a>";
echo "<a href=\"#\" class=\"Edit\" style=\"color: blue;\">Edit</a>";
echo "<a href=\"#\" class=\"Hide\" style=\"color: blue;\">Hide</a>";
echo "</div>";
}
jQuery
$(document).ready(function () {
$('a.Save').click(function () {
});
$('a.Hide').click(function () {
$("#message" + $id).hide();
$("#message" + $id).fadeIn(2000);
});
$('a.Edit').click(function () {
if ($(this).text() == "Edit") {
$("#pmessage").css("color", "red");
$("a.Edit").text("Unedit");
} else {
$("#pmessage").css("color", "black");
$("a.Edit").text("Edit");
}
});
$('a.Save').click(function (e) {
e.preventDefault();
$("#1234").submit();
});
$("#1234").submit(function(e) {
$("a.Save").text("Saving...");
e.preventDefault();
$.ajax({
type: "POST",
url: 'ajaxexample.php',
data: $("#1234").serialize(),
success: function(data)
{
$("a.Save").text("Unsave");
}
});
});
});