WordPress users in a datatables is not working - ajax

I am making a plugin to display all user info in a DataTables but i am failed. I have about 20k user so i can't use normal table method that's why i use ajax method. Please help me.
I get ajax response like {"draw":0,"recordsTotal":0,"recordsFiltered":0,"data":[]}
This is my table structure
<table id="user_table" class="display table table-striped table-bordered dataTable" style="width:100%">
<thead class="user-table">
<tr>
<th>Email</th>
<th>Name </th>
<th>Url</th>
<th>nickname</th>
<th>description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My script
jQuery(document).ready(function($){
var ajaxurl = USERAjax.wpajaxusersearch;
var dataTable = $('#user_table').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url: ajaxurl,
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
});
also added localize script like
wp_localize_script( 'jquery', 'USERAjax', array('wpajaxusersearch' => admin_url( 'admin-ajax.php?action=wpajaxusersearch' )) );
and my data fetching function with ajax response
<?php
function wpajaxusersearch(){
$request=$_REQUEST;
global $wpdb;
$sort= "user_registered";
//Build the custom database query to fetch all user IDs
$all_users_id = $wpdb->get_results("SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY %s ASC ", $sort );
$totalData=mysqli_num_rows($all_users_id);
$data=array();
foreach ( $all_users_id as $i_users_id ) {
$user = get_userdata( $i_users_id );
$email = $user->user_email;
$user_fullname =$user->first_name . ' ' . $user->last_name;
$user_url =$user->user_url;
$user_nickname =$user->nickname;
$user_profile =$user->description;
$sub_array = array();
$sub_array[] = $email;
$sub_array[] = $user_fullname;
$sub_array[] = $user_url;
$sub_array[] = $user_nickname;
$sub_array[] = $user_profile;
$data[] = $sub_array;
}
$json_data=array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalData),
"data" => $data
);
echo json_encode($json_data);
wp_die(); //to remove that 0 response
}
add_action( 'wp_ajax_wpajaxusersearch', 'wpajaxusersearch' );
add_action( 'wp_ajax_nopriv_wpajaxusersearch', 'wpajaxusersearch' );

Try this code
Your query is wrong
<?php
function wpajaxusersearch(){
$request=$_REQUEST;
global $wpdb;
$sort= "user_registered";
//Build the custom database query to fetch all user IDs
$all_users_id = $wpdb->get_results("SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY $sort ASC " );
$totalData=$wpdb->num_rows;
$data=array();
foreach ( $all_users_id as $i_users_id ) {
$user = get_userdata( $i_users_id->ID);
$email = $user->user_email;
$user_fullname =$user->first_name . ' ' . $user->last_name;
$user_url =$user->user_url;
$user_nickname =$user->nickname;
$user_profile =$user->description;
$sub_array = array();
$sub_array[] = $email;
$sub_array[] = $user_fullname;
$sub_array[] = $user_url;
$sub_array[] = $user_nickname;
$sub_array[] = $user_profile;
$data[] = $sub_array;
}
$json_data=array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalData),
"data" => $data
);
echo json_encode($json_data);
wp_die(); //to remove that 0 response
}
add_action( 'wp_ajax_wpajaxusersearch', 'wpajaxusersearch' );
add_action( 'wp_ajax_nopriv_wpajaxusersearch', 'wpajaxusersearch' );

Related

Error updating data of 1 column by id in Codeigniter 3 database

I am posting the hosting order and I want to increase the "number of sales" column in my "hostings" table, but the data of all packages in my hostings table is increasing.
Here is my relevant code, I can say that there is no method I haven't tried.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
//FULL CODE
public function buy_hosting_post()
{
if ($this->input->post('package_id') && $this->session->userdata('id')) {
$hosting = $this->db->from('hostings')->where('id', $this->input->post('package_id'))->get()->row_array();
if ($hosting) {
$data = array(
'user_id' => $this->session->userdata('id'),
'domain' => $this->input->post('domain'),
'price' => $this->input->post('price'),
// 'end_date' => date('Y-m-d h:i:s',$end_date),
'package_id' => $hosting['id'],
'package_title' => $hosting['name'],
'payment_status' => 0,
);
$this->db->insert('hosting_orders', $data);
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
$hosting_order_successful = array(
'hosting_order_successful' => 'success',
);
$this->session->set_userdata('hosting_order_successful', $hosting_order_successful);
redirect(("hosting-siparisi-olusturuldu"));
} else {
redirect(base_url());
}
} else {
redirect(base_url());
}
}
I solved the problem in the following way, but it makes the system heavy.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->where('id', $this->input->post('package_id')); // added here.
$this->db->update('hostings', $data);

Get Product ID on AJAX call

I am trying to get the current product ID (if is a product page) in this AJAX call. I have attempted to use global $product but couldn't make it work. Is there any way to access the current product (post) in an AJAX call?
add_action('wp_ajax_get_product_list', 'get_product_list');
add_action('wp_ajax_nopriv_get_product_list', 'get_product_list');
function get_product_list()
{
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'ASC'
);
$loop = new WP_Query($args);
$allProducts = '';
//if the product page get the current product ID
// Do something here with the current product ID
foreach ($loop->posts as $product) {
$allProducts = $allProducts . '<option value="' . $product->ID . '">' . $product->post_title . '</option>';
}
wp_reset_query();
echo $allProducts;
wp_die();
}
AJAX call
jQuery(document).ready(function($) {
var data = {
'action': 'get_product_list',
};
jQuery.post("/wp-admin/admin-ajax.php", data, function(response) {
console.log(response);
});
});

Create category on the front-end with Ajax in WordPress

I'm having difficulty getting this to create a category on the front-end with Ajax. It's 99% working.
Here is my form:
<form id="new_idea" name="new_idea" method="POST">
<ul>
<li>
<label>Idea name</label>
<input type="text" name="idea_name" required />
</li>
<li class="full">
<label>Description</label>
<input type="text" name="idea_description" />
</li>
</ul>
</form>
Here is my function (in functions.php):
add_action( 'wp_ajax_add_new_idea', 'add_new_idea' );
add_action( 'wp_ajax_nopriv_add_new_idea', 'add_new_idea' );
function ajax_scripts() {
$parameters = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('inputs')
);
wp_enqueue_script('my-ajax', get_template_directory_uri().'/js/ajax.js', array('jquery'), null, true);
wp_localize_script('my-ajax', 'inputs', $parameters );
}
add_action('wp_enqueue_scripts', 'ajax_scripts');
function ajaxStatus($status, $message, $data = NULL) {
$response = array (
'status' => $status,
'message' => $message,
'data' => $data
);
$output = json_encode($response);
exit($output);
}
// New Idea
function add_new_idea() {
if(isset($_POST["new_idea_form"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $_POST['idea_name'];
$idea_description = $_POST['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
...and this is my ajax.js:
$('#new_idea').on('submit', function(e) {
e.preventDefault();
$.post( inputs.ajaxurl, {
action : 'add_new_idea',
nonce : inputs.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
ResponseSuccess(response);
});
return false;
});
As for troubleshooting, if I hardcode values into the $idea array like this and submit the form...
$idea = array(
'cat_name' => 'cool idea',
'category_parent' => '',
'category_nicename' => 'cool-dea',
'category_description' => 'a description of my cool idea',
'taxonomy' => 'ideas'
);
...it actually works and my category gets created.
So from what I can tell, the real problem is that it is not getting the $_POST[] values that were submitted, although I can't see why.
Any help would be awesome.
Try this code.
function add_new_idea() {
$params = array();
parse_str($_POST["post"], $params);
if(isset($_POST["post"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $params['idea_name'];
$idea_description = $params['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
Read This
you need to use parse_str for serlize object.
Retrieving serialize data in a PHP file called using AJAX

Drupal 7 ajax form submit not working

I have a node page where I need to create a reply form via ajax for commenting. Commenting in my system is also a kind of node.
When my page first loads it's presented with all comments done and also only one textbox & submit button which is used to add a new comment node. When I click submit button that comment is added via ajax.
Below each comments there is reply option. When I click on this reply, an ajax call is made to bring a new text area & reply button which are coming using same node form that is presented in form above. When this new form is presented I fill it up and submit at that time it's not submitted via ajax instead it redirects to destination URL.
Following is my menu & form alter code.
function mymodule_menu() {
$items['user_reply_comments/%/%'] = array(
'title' => t('Reply to User Comment'),
'page callback' => 'mymodule_user_reply_comment',
'page arguments' => array(1, 2, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
'delivery callback' => 'ajax_deliver',
'file' => 'includes/mymodule.pages.inc',
);
return $items;
}
function mymodule_form_comment_node_statement_form_alter(&$form, &$form_state, $form_id) {
drupal_add_library('system', 'drupal.form');
drupal_add_library('system', 'drupal.ajax');
drupal_add_js($base_url. '/' .path_to_theme().'/js/script.js', 'file');
$form['#action'] = url('user_reply_comments/'.$id.'/'.arg(2) .'/ajax');
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_comment_node_statement_form_callback',
'wrapper' => 'comment-replies-' . arg(2),
'method' => 'replace',
'effect' => 'fade',
'event' => 'click',
'progress' => array('type'=> 'throbber',
'message' => "<div></div>",
),
'js' => array(
$base_url. '/' .path_to_theme().'/js/script.js',
),
);
}
/**
* Ajax callback for comment_node_statement_form.
*/
function mymodule_comment_node_statement_form_callback($form, &$form_state) {
/*echo '<pre>';
print_r($form);
exit;*/
//echo ' 1 :' . arg(1) . ' 2:' .arg(2); exit; // sub reply dows not came here
$message_empty = drupal_get_messages();
if(!empty($message_empty) && isset($message_empty ['error'])){
global $base_url;
$command_add = array();
if(user_is_anonymous()){
$command_add = ajax_command_invoke(NULL, "redirect_user", array($base_url));
}
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_before('#content', '<div id="inline-messages" class="messages error">'.$message_empty ['error'] [0].'</div>'),
ajax_command_invoke(NULL, "greyout_reply"),
$command_add
)
);
}
else{
$current_path = TRUE;
$statement_page_reply_form = "";
$pos = strpos($_SERVER['HTTP_REFERER'], "statements");
if($pos !== FALSE){
$current_path = FALSE;
}
// print_r($_SERVER['HTTP_REFERER']);
// print "$$$".$current_path."###"; exit;
// Clear the messages (drupal_set_message() doens't work for some reason).
$_SESSION['messages'] = '';
if($current_path){
$html = "<div class='arrow'>arrow</div>";
}
else{
$html = "";
}
$id = $form['#node']->nid;
if (!empty($form['build_info_args_' . $id]['#value'])) {
$form_state = array(
'build_info' => array('args' => $form['build_info_args_' . $id]['#value']),
'values' => array(),
) + form_state_defaults();
}
$form_state['rebuild'] = TRUE;
//$comment_form = drupal_rebuild_form('comment_node_statement_form', $form_state, $form);
$comment_form = drupal_rebuild_form('comment_node_statement_form', $form_state, $form);
$node_comments = views_embed_view('statement_replies', 'block', $id);
if($form['current_url']['#value'] == "dashboard"){
$comment_form['current_url'] = array('#type' => 'hidden', '#value' => "dashboard", '#name' => 'current_url');
$html .= '<div class="dashboard-statements-comments">';
}
if($current_path){
$html .= '<div class="statement-comment-reply-box">'.drupal_render($comment_form).'</div>';
}
else{
$statement_page_reply_form = '<div class="arrow">arrow</div><div class="statement-comment-reply-box">'. drupal_render($comment_form).'</div>';
$num_comments = db_query("SELECT COUNT(cid) AS count FROM {comment} WHERE nid =:nid and status = :status",array (":nid"=>$id, ":status" => '1'))->fetchField();
$statement_page_reply_form .= '<span class="statement_total_replies">'.$num_comments. ' Replies</span>';
$statement_page_reply_form .= '<span class="collapse_reply">COLLAPSE</span>';
}
$html .= '<div class="statement-comment-reply-feed">'.$node_comments.'</div>';
if($form['current_url']['#value'] == "dashboard"){
$html .= '</div>';
}
if($current_path){
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#statement-replies-' . $id, $html),
ajax_command_remove('#inline-messages'),
ajax_command_before('#content', '<div id="inline-messages" class="messages status"><h2 class="element-invisible">Status message</h2>Reply posted.</div>'),
)
);
}
else{
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#statement-replies-' . $id, $html),
ajax_command_html('.statement_upper_part .reply_form_statement', $statement_page_reply_form),
ajax_command_remove('#inline-messages'),
ajax_command_before('#content', '<div id="inline-messages" class="messages status"><h2 class="element-invisible">Status message</h2>Reply posted.</div>'),
ajax_command_invoke(NULL, "alter_elements"),
)
);
}
}
}
/**
* This is function in mymodule.pages.inc
* Callback function for 'user_reply_comment/%/%' path.
*
* Returns the popup modal form consists of reply form
*
* #param $entity_id
* Integer representing node ID
* #param $current_cid
* Integer representing comment ID
*/
function mymodule_user_reply_comment($entity_id, $current_cid, $js = FALSE) {
$logged_in = user_is_logged_in();
$node = node_load($entity_id);
if($node) {
if ($node->type == 'statement' || $node->type == "user_comment") {
$replies = "<div class='arrow'>arrow</div>";
$ajax_css = "";
if ($logged_in) {
$edit = array('nid' => $node->nid);
$form = drupal_get_form("comment_node_{$node->type}_form", (object) $edit);
$replies .= "<div class='statement-comment-reply-box'>";
$replies .= drupal_render($form);
$replies .= "</div>";
}
else{
$ajax_css = ajax_command_invoke(NULL, "views_row_hide_border");
}
$replies .= "<div class='statement-comment-reply-feed'>";
$replies .= "</div>";
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#comment-replies-' . $current_cid, $replies),
ajax_command_invoke(NULL, "show_statement_replies", array('#comment-replies-' . $current_cid)),
ajax_command_invoke(NULL, "toggle_reply_links" , array($current_cid)),
ajax_command_invoke(NULL, "mymodule_user_reply_comment_reply" , array($current_cid, $edit)),
$ajax_css
));
}
}
}
/*
Following is there in script.js file
*/
(function($) {
$.fn.mymodule_user_reply_comment_reply = function(cid, nid) {
var form_class = '.comment-form-' + nid + '--' + cid;
var button = form_class + ' input.form-submit';
console.log('reply thread click.' + cid);
$(button).bind('click', 'upload_reply_image');
/*{
console.log($(this).attr('id'));
return false;
e.preventDefault();
e.stopPropogation();
//Drupal.attachBehaviors($(form_class));
return false;
});//*/
console.log('reply thread out.' + cid);
};
})(jQuery);
/* To toggle between Reply expand/collapse mode in statement/Comment box and their reply box - Start */
(function($) {
$.fn.toggle_reply_links = function(cid) {
jQuery('#close-sub-comments-' + cid).parent().find('a').toggle();
};
})(jQuery);
(function($) {
$.fn.show_statement_replies = function(id) {
jQuery(id).slideDown();
};
})(jQuery);
Thanks in advance.
I think you have wrong path in your code. You need to change this in hook_menu:
$items['user_reply_comments/%/%'] = array(
With this:
$items['user_reply_comments/%/%/ajax'] = array(
At least there's something that doesn't match in my opinion.
Clear your menu cache to see the changes.
Hope that helps.

CodeIgniter - Search function (products->category_id database relationship)

I have this code:
function search($terms){
$query = $this->db->get_where('products',"name LIKE '%$terms%' OR description LIKE '%$terms%'");
$product = $query->result_array();
foreach($product as $p):
$query2 = $this->db->get_where('categories', array('cat_id' => $p['prod_category']));
$category = $query2->row_array();
$product['category'] = $category['cat_link'];
endforeach;
return $product;
}
in my search function. It will return something like:
Array(
[0] => Array(
[prod_id] => 5
[prod_name] => Product
[prod_category] => 1
)
But what I'm after is:
Array(
[0] => Array(
[prod_id] => 5
[prod_name] => Product
[prod_category] => Category1
)
from the name of my category with the id 1. This is in my 'categories' table. The foreach loop is not the right way to accomplish this, but what is?
You could simplify your search logic by letting your database handle the joining of your tables.
function search($terms){
$this->db->select('prod_id, prod_name, cat_name');
$this->db->from('products');
$this->db->join('categories', 'cat_id = prod_category', 'inner');
$this->db->like('name', $terms);
$this->db->or_like('description', $terms);
$query = $this->db->get();
return $query->result_array();
}
This is assuming your category name column is named cat_name. The results would be as follow :
Array(
[0] => Array(
[prod_id] => 5
[prod_name] => Product
[cat_name] => Category1
)
Hope this helps!
You can use below method:
I'm assuming that you've already loaded your libraries
CONTROLLER
function search()
{
$data['query'] = $this->Books_model->get_search();
$this->load->view(‘books’, $data);
}
MODEL
function get_search()
{
$match = $this->input->post(‘search’);
$this->db->like(‘bookname’,$match);
$this->db->or_like(‘author’,$match);
$this->db->or_like(‘characters’,$match);
$this->db->or_like(‘synopsis’,$match);
$query = $this->db->get(‘books’);
return $query->result();
}
VIEWS
<?=form_open(‘books/search’);?>
<?php $search = array(‘name’=>’search’,'id’=>’search’,'value’=>”,);?>
<?=form_input($search);?><input type=submit value=’Search’ /></p>
<?=form_close();?>
The result can be displayed using a HTML table
<table>
<tr><th>ID</th><th>Book</th><th>Author</th><th>Published</th><th>Price</th></tr>
<?php foreach($query as $item):?>
<tr>
<td><?= $item->id ?></td>
<td><?= $item->bookname ?></td>
<td><?= $item->author ?></td>
<td><?= $item->datepublished ?></td>
<td><?= $item->price ?></td>
</tr>
<?php endforeach;?>
</table>
This is what I'm using and I hope it'll help you to make search function on Code Igniter.

Resources