Advice on my jQuery Ajax Function - ajax

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("<?php echo $_SESSION['username']; ?><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("<?php echo $_SESSION['username']; ?><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("" + username + "<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!

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.

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).

Related

Admin ajax in wordpress is not working

I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.

data not pass using ajax after onclick

I'm trying to remove an element from the database.
I don't know why, but the data is not getting to the url i inserted.
this is the code (the obj is indeed faded - only in the client side):
$(document).on("click", "#deleteAdmin", function(e) {
$.ajax({
url: "admin/adminProccess.php",
type: "get",
data: $('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin',
success: function(data) {
$('#idPriv:checked').each(function(){
$(this).parent().parent().remove();
});
var item = $(deleteAdmin);
item.fadeOut();
}
});
});
is there something wrong in my code?
when i'm trying to access manually to the url i can see some results - but with my code its not sending the data.
any ideas?
edit: this is my idPriv:
<input type = "checkbox" name="idPriv[]" id="idPriv" onclick="evaluateIT(this)" data-related-item="adminPanelShow" value ="<?php echo $value["id"].':'. $count; ?>" />
Try to change:
$('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin'
to:
$('#idPriv:checked').val() + '&str=' + 'deleteAdmin'

Ajax form not submitting

I followed the Submit Ajax Form tutorial on tutsplus.com ,
but cannot figure out for the life of me why my data won't have addreply.php applied to it. When I look in my mysql table, the data does not get inserted. Any help would be greatly appreciated. I searched the web and have troubleshooted for many hours.
$(document).ready(function() {
$(".replyLink").one("click", function(){
$(this).parent().after("<div id='contact_form'></div>");
$("#contact_form").append("<form id='replyForm'></form>");
$("#replyForm").append("<input class='enterName' id='enterName' type='text'
name='name' placeholder='name' rows='1' cols='20' />");
$("#replyForm").append("<textarea class='enterReply' id='enterReply' name='comment'
placeholder='reply'></textarea>");
$("#replyForm").append("<input type='hidden' name='id' value=''>");
commentID= $(this).parent().attr('id');
$("#replyForm").append("<input class='replyButton' id='replyButton' type='submit' `value='reply'/>");`
$(".enterReply").slideDown();
$(".replyButton").slideDown();
});
$(".replyButton").click(function() {
var name = $("input#enterName").val();
var reply = $("textarea#enterReply").val();
var dataString = 'name='+ name.val() + '&comment=' + reply.val();
$.ajax({
type: "POST",
url: "addreply.php",
data: dataString,
success: function() {
}
});
return false;
});
**addreply.php**
<?php
session_start();
$replyID= $_POST['id'];
$name= $_POST['name'];
$comment= $_POST['comment'];
$type= $_POST['type'];
$song= $_POST['song'];
if($song == ''){
$song= 'not';
}
include 'connection.php';
if($_SESSION['signed_in'] == 'yes') {
$query1= "INSERT INTO ApprovedComments(name, comment, Authorized, type, reply_ID, song, date)
VALUES('$name', '$comment', 'YES', '$type', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query1);
// echo "hi";
}
if( !isset($_SESSION['signed_in']) ) {
$query2= "INSERT INTO PreApprovedComments(name, comment, reply_ID, song, date)
VALUES('$name', '$comment', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query2);
}
mysql_close();
?>
Try
$.ajax({
type: "POST",
url: "addreply.php",
data: $("#replyForm").serialize()+'name='+ encodeURIComponent(name) +
'&comment=' + encodeURIComponent(reply),
success: function() {
}
});
this will post all the fields in the #replyForm form and the name and comment fields.

Jquery and ajax

I am quite new to JS and JQ so I am ask this basic question. I have code like this:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('1500', function() {$(this).remove();
$('#messages').fadeOut('1000');
});
}
});
return false;
});
For now it is working like it should. But I want to add something more. Div with id #messages contains all messages, and I wish that upon deleting message it fadeout(it is working) and then load new data and present all messages again without the deleted one.
Also, there is a counter that counts unread messages, and I created separate page for ajax purpose, but I don't know how to go on from fadeOut.
This is the code from the seperate page:
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
I edited code a bit, but still nothing.
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>").show().fadeIn('1000');
});
});
}
});
return false;
});
When I look page source I can see that the content has been changed, but it is not displayed.
I didn't quite understand what you are trying to do but if this is what you mean by saying but I don't know how to go on from fadeOut you can put a callback function to fadeOut
$('#messages').fadeOut('1000', function () {
// Do something here
);

Ajax request returns every html element of the page

i am a new bie to Ajax and currently making a form submission using php and ajax(for a wordpress plugin). My js code is
$("#submit").click(function(){
var form_data = $('.myform').serialize();
$.ajax({
type: "POST",
url: "main_form.php",
data: form_data,
success: function(html){
$('div#ajax_output').html(html);
}
});
return false;
});
and my entire page structure looks like
<div class="header"> ....</div>
<div class="navigation"> ....</div>
< ?php
if($_post) {
//form validation codes
if(condition true) echo "Success message";
else echo "Error";
}
?>
<div id="ajax_output"></div>
<form class="myform">
//form elements
</form>
//And the above javascript here(that click fn)
Now my problem is, as i am submitting the form data to the same page(it is unavoidable and cannot make it separate), the ajax returns inside <div id="ajax_output"></div> all the page contents header, navigation, etc including echo "Success message".
Can any one tell me how to output only php validation result?
output buffering may help you
<?php // insert that at the beginning of the page
ob_start();
?>
<div class="header"> ....</div>
<div class="navigation"> ....</div>
<?php
if($_post) {
//form validation codes
if(condition true) echo "Success message";
else echo "Error";
ob_end_clean();
exit(1);
} else {
echo ob_get_clean();
}
?>
<div id="ajax_output"></div>
<form class="myform">
//form elements
</form>
//And the above javascript here(that click fn)
You'd better restructure code, though. I.e. move processing of post data to the beginning of the page and then just exit if it should be processed.
Usually, such problems are solved on server side, not in javascript.
I mean, server should return correct html part w/o heading, navigation, etc., client should not parse all that stuff to get what it needs.
You may return after checking the form data, or do the form validation in another action.
The code example is not complete, but you can get the gist of it hopefully!
Add a variable to post data.
Javascript:
$("#submit").click(function(){
var form_data = $('.myform').serialize();
form_data.isAjax = true;
$.ajax({
type: "POST",
url: "main_form.php",
data: form_data,
success: function(html){
$('div#ajax_output').html(html);
}
});
return false;
});
PHP:
<?php
if(array_key_exists("isAjax", $_POST) {
if($_post) {
//form validation codes
if(condition true) {
echo "Success message";
}
else {
echo "Error";
}
}
}
else {
$mainPage = '<div class="header"/>>';
$mainPage += '<div class="navigation"/>';
$mainPage += '<div id="ajax_output"/>';
$mainPage += '<form class="myform"/>';
$mainPage += '<javascript />';
echo $mainPage;
}

Resources