How to implement AJAX commenting in WordPress - javascript

I'm trying to 'ajaxify' commenting in WordPress using this tutorial Ajaxify WordPress Comments
Here is my PHP handler:
function ajaxify_comments( $comment_ID, $comment_status ){
if( ! empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) {
//If AJAX Request Then
switch( $comment_status ) {
case '0':
//notify moderator of unapproved comment
wp_notify_moderator( $comment_ID );
case '1': //Approved comment
echo "success";
$commentdata = &get_comment( $comment_ID, ARRAY_A );
$post = &get_post( $commentdata['comment_post_ID'] );
wp_notify_postauthor( $comment_ID, $commentdata['comment_type'] );
break;
default:
echo "error";
}
exit;
}
}
add_action( 'comment_post', 'ajaxify_comments', 20, 2 );
And here is my script:
jQuery('document').ready(function($){
var commentform=$('#commentform'); // find the comment form
commentform.prepend('<div id="comment-status" ></div>'); // add info panel before the form to provide feedback or errors
var statusdiv=$('#comment-status'); // define the infopanel
commentform.submit(function(){
//serialize and store form data in a variable
var formdata=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown){
statusdiv.html('<p class="ajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success: function(data, textStatus){
if(data=="success")
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
else
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
});
return false;
});
});
Every time I post a comment, I get: "Please wait a while before posting your next comment". Hoping somebody can tell me what I'm doing wrong?

Try this:
jQuery('document').ready(function($){
var commentform=$('#commentform'); // find the comment form
commentform.prepend('<div id="comment-status" ></div>'); // add info panel before the form to provide feedback or errors
var statusdiv=$('#comment-status'); // define the infopanel
commentform.submit(function(){
//serialize and store form data in a variable
var formdata=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown)
{
statusdiv.html('<p class="ajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success: function(data, textStatus){
if(data == "success" || textStatus == "success"){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
}else{
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
}
});
return false;
});
});

Related

How do I get a message in a div box instead of the alert box with ajax success?

I'm trying to create error validation handling for my custom form. What I want to do is get the error messages in a div instead of the browser alert box but I'm new to all of this and have no idea how to do it. I tried to do some research but found nothing useful for my case.
Basically my form works and shows error or success messages correctly, but I don't want to display them in the alert box, but in a dedicated div. Thanks for any answers, I appreciate any help.
So here's what I have:
My section which contains all the various messages error
<div class="error-message-wrapper">
<!-- Here are all my error messages that are printed with the wc_print_notices(); function -->
</div>
My Script
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
alert( response );
}
});
});
});
My function
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$msg = wc_print_notices();
$response = $msg;
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}
If u wanna show in exist class then choose element by document.querySelector(".className").innerHtml = response.textFromResponse or u can do like below
Query(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
alert( response );
const uiDivElement = document.createElement("DIV");
uiDivElement.innerHTML = response.textFromResponse
document.appendChild(uiDivElement)
}
});
});
});

AJAX POST group of form variables to PHP

I am trying to send a group of form parameters over to a PHP script for processing.
I've previously done something like this using $.post, but now I'm trying to get it done strictly by using $.ajax.
Here is the jQuery click event that is supposed to send all of the variables to the PHP script:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
Here is the PHP script, called railmbs.php:
<?php
if(isset($_POST['searchCriteria']))
{
$value = $_POST['searchCriteria'];
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($value['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($value['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($value['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Not sure what I am doing wrong. If I echo hello before the IF above, the console will output accordingly. But I cannot seem to get anything to echo from inside the IF.
Does anyone see my error?
You are not setting the "searchCriteria" variable.
Change this:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
to:
$('.searchSubmit').on('click', function()
{
var data = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: data, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
First of all. Why not to use $("form").serialize()? It would be much cleaner.
Secondary, you transfer data in root object, so to get you values, check $_POST array.
Instead of $value = $_POST['searchCriteria'] use $value = $_POST;.
This PHP code should work:
<?php
if(isset($_POST))
{
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($_POST['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($_POST['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($_POST['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Or modify your js to send data in searchCriteria object, like this:
var searchCriteria = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}};
You should check if you actually send post data using your browser developer tools or typing var_dump($_POST); at the beginning of your PHP script.
As far as i can see, you never actually set searchCriteria as post variable.
Currently your $_POST variable should contain the field import_bill, import_ramp and so on. Either change your if statement or your JavaScript object to {searchCriteria: {/*Your data here*/}.

rails xhr.send( ( options.hasContent && options.data ) || null ); error

I trying to make like button for each recipe
but if i click like button browser said
xhr.send( ( options.hasContent && options.data ) || null );
return this errors
I don't know why this error occurred
this is my code in rails
application.js
function like(id){
$.ajax({
url:"/like/" + id,
type:"POST",
dataType:"json",
success: function(data){
if(data.result){
$("#countlike").html("likes " + data.count);
// $("#count").removeAttr('onclick');
// $("#count").attr('disabled', 'disabled');
}
}
});
}
route.rb
post '/like/:id'=>'recipes#like'
views/recipes/show.html.erb
<p>
<a id = "countlike" onclick="like(<%=#recipe.id%>)">Like it</a>
</p>
recipes_controller.rb
def like
likes = Recipe.find(params[:id]).likes
result = likes.create
render json:{result: result, count: likes.count}
end
It was work correctly in other project same code
Looks like you are missing your data attribute in you post ajax request that might be throwing the error.
function like(id){
$.ajax({
url:"/like/" + id,
type:"POST",
dataType:"json",
data: my_data, // <--- HERE
success: function(data){
if(data.result){
$("#countlike").html("likes " + data.count);
// $("#count").removeAttr('onclick');
// $("#count").attr('disabled', 'disabled');
}
}
});
}
Hope it helps. Cheers!

AJAX in WordPress only returns 0

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.
The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:
JS/jQuery built into PHP function ajax-action()
$ = jQuery;
$('#platform').change(function(e) {
var data = {
action: 'action_cb',
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
PHP functions and add-actions
add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };
My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.
As per the wordpress documentation:
https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")
A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)
Things to check:
Where are you defining your add_action('wp_ajax_action_cb','action_cb');?
Specifically, what portion of your plugin code?
Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)
Additionally, you didn't share the function this is tied to:
add_action('admin_footer','ajax_action');
And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...
So your code would look like so:
function action_cb() { $platform = 'test'; echo $platform; p_die(); };
...and your AJAX could be:
<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
if (data != '0' && data != '-1') {
{YOUR SUCCESS CODE}
} else {
{ANY ERROR HANDLING}
}
},
dataType: 'html'
});
</script>
Try This:
<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
</script>
Probably you need to add
add_action('wp_ajax_nopriv_action_cb', 'action_cb');
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
just make small change in your AJAX. I am assuming you're logged in as admin.
replace action in data object with data:"action=action_cb",
var data = {
data:"action=action_cb",
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl,data,function(data){
$('#user_id').val(data);
});
To prevent WP adding zero into response i always using die(); insted of wp_die();
and registering function:
add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );
function action_cb_init() {
}
When calling to function with AJAX use action: 'action_cb'
Hope this helps. I have already explained standard way of using ajax in wp.
Wordpress: Passing data to a page using Ajax
Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.
$j = jQuery.noConflict();
$j('#platform').change(function(e) {
$j.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'action_cb',
}
}).done(function( data ) {
// When ajax-request is done.
if(data) {
$j('#user_id').val(data);
} else {
// If 0
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
// If ajax failed
console.log(errorThrown);
});
e.preventDefault();
});
I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.
For those by the "Load More" problem.
Normally "0" is used instead of false.
I found such a solution.
So that 0 does not come. Try this code with false.
PHP
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
JS
if( posts[i] == false )
$(".load_more_button").fadeOut();

Message error its not showing using ajax via jQuery

Im trying to update data in a form via ajax with jQuery.
Im doing the update with sucess, but when I have empty fields Im not getting my error message saying: myModal('config_datas_errempty','alert','Fill al fields please');
And also if I write a wrong format for email I dont have any message too.
Do you see where might be the error? Because for me everyting seems fine and I already review the code many times!
My php:
switch ($action)
{
case 'data_update':
$d['adress'] = $_POST['adress'];
$d['phone'] = $_POST['phone'];
$d['fax'] = $_POST['fax'];
$d['email']= $_POST['email'];
if(in_array('',$d))
{
echo 'errempty';
}
else if(!valMail($d['email']))
{
echo 'erremail';
}
else
{
$updateData= $pdo->prepare("UPDATE config_data set adress=?, phone =?, fax=?, email=? WHERE id = ?");
$updateData->bindValue(1, $d['adress']);
$updateData->bindValue(2, $d['phone']);
$updateData->bindValue(3, $d['fax']);
$updateData->bindValue(4, $d['email']);
$updateData->bindValue(5, '1');
$updateData->execute();
}
break;
default: echo 'Error';
}
My jQuery:
$('form[name="config_data"]').submit(function(){
var forma = $(this);
var data = $(this).serialize() + '&action=data_update';
$.ajax({
url: url,
data: data,
type: 'POST',
beforeSend: function(){
forma.find('.load').fadeIn("fast");
},
success: function( datas ){
if(datas == 'errempty'){
myModal('config_datas_errempty','alert','Fill al fields please');
}else if((datas == 'erremail')){
myModal('config_datas_accept','accept','Sucess update');
}
},
complete: function(){
forma.find('.load').fadeOut("fast");
}
});
return false;
});

Categories