I am not able to pass a variable from Codeigniter's view to controller and then model that shoots the query that is required to fetch the data from database.
here's my Controller(snippet):
public function read() {
echo json_encode( $this->random_model->getAll() );
}
Model:
public function getAll() {
$id = $this->input->post('id');
$id = intval( $id );
// print_r($sg_id);
// var_dump($sg_id);
$query = $this->db->where('id',$id)->limit( 100 )->get( 'table_name' );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
I'm sending the "$id" from another function :
function test1()
{
$blaa['id'] = $this->input->post('id');
if ($query = $this->model_name->getAll($blaa))
{
$blaa['records'] = $query;
}
//$this->model_name->getAll($blaa);
$this->load->view('view_name', $blaa);
}
this is the test1 view:
<?php $attributes = array("class" => "", "id" => "", "name" => "");
echo form_open("test/test1/", $attributes);?>
<input type="text" id="id" name="id" >
<?php echo form_submit('submit', 'Submit')?>
<?php echo form_close(); ?>
this is the view_name that shows all the data, I'm using dataTables.:
All.js that is rendered in the view_name (read data snippet):
var readUrl = 'index.php/controller_name/read'
function readUsers() {
//display ajax loader animation
$( '#ajaxLoadAni' ).fadeIn( 'slow' );
$.ajax({
url: readUrl,
dataType: 'json',
success: function( response ) {
for( var i in response ) {
response[ i ].updateLink = updateUrl + '/' + response[ i ].id;
response[ i ].deleteLink = delUrl + '/' + response[ i ].id;
}
//clear old rows
$( '#records > tbody' ).html( '' );
//append new rows
$( '#readTemplate' ).render( response ).appendTo( "#records > tbody" );
//apply dataTable to #records table and save its object in dataTable variable
if( typeof dataTable == 'undefined' )
dataTable = $( '#records' ).dataTable({"bJQueryUI": true});
//hide ajax loader animation here...
$( '#ajaxLoadAni' ).fadeOut( 'slow' );
}
});
The results that I get are only of the data having the id "0" , no matter which value I send through the test controller.
Change your model code to this :
public function getAll($id = null) {
if ($id == null)
$id = $this->input->post('id');
$id = intval( $id );
// print_r($sg_id);
// var_dump($sg_id);
$query = $this->db->where('id',$id)->limit( 100 )->get( 'table_name' );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
Try this
function getAll(id)
{
var id = id;
$.ajax({
url:"<?php echo site_url('controllerName/getAll');?>/"+id,
success:function(data)
{
alert(data);
}
});
}
Get All
In your controller try to fetch id like this
public function getAll($id)
{
echo $id;
}
for more try this : http://w3code.in/2015/10/how-to-edit-delete-and-update-data-without-refreshing-page-in-codeigniter/
add the id you want to post in ajax like this, Then you can use $this->input->post("id"); in model or controller.
$.ajax({
url: readUrl,
data:{id: id which you want to pass.}
dataType: 'json',// change this to post
success: function( response ) {
}
});
Related
Good afternoon devs, I developed a favorite system using Wordpress and php, it works as follows, clicking on the add favorites icon I send an ajax request to php with the favorite id and the user id logged in. php processes this by saving in user_meta the information with number of favorite users and in the logged user an array with the ids of the favorites. Anyway, the question is, the system is working, but whenever I develop something I keep wondering if there is a way to improve the code, if there is a way to do it in a better way, I will leave my code here.
All this for learning ok?
HTML
<div class="stats -favorites">
<a class="icon -click <?php echo is_favorite(get_current_user_id(), $user_ID) ? 'fa' : 'far' ?> fa-heart" data-js="favorite" data-favorite="<?php echo $user_ID; ?>" data-user="<?php echo get_current_user_id(); ?>"></a>
<span class="label" data-js="favorite_label">
<?php echo get_favorites_num( $user_ID ); ?>
</span>
<span class="value">favoritos</span>
</div>
JS
function setFavorite(userid, favoriteid) {
var favorite_field = $('[data-js="favorite"]');
var favorite_label = $('[data-js="favorite_label"]');
$.ajax({
url : appmeninas_ajax_params.ajaxurl,
data : {
'action' : 'setfavorite',
'userid' : userid,
'favoriteid' : favoriteid,
},
dataType : 'json',
type : 'POST',
cache : false,
beforeSend : function( xhr ) {
favorite_field.removeClass('far fa fa-heart').addClass('fas fa-circle-notch fa-spin');
},
success : function( data ) {
var icon = (data.is_favorite) ? 'fa fa-heart' : 'far fa-heart';
favorite_field.removeClass('fas fa-circle-notch fa-spin');
favorite_field.addClass(icon);
favorite_label.html('');
favorite_label.append(data.favorites_num);
}
});
};
$('[data-js=favorite]').click(function() {
var favoriteid = $(this).data('favorite');
var userid = $(this).data('user');
setFavorite(userid, favoriteid);
});
PHP
function setfavorite() {
$userid = $_POST['userid'];
$favoriteid = $_POST['favoriteid'];
// user require favorite
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
$favorites_num = get_field( 'favorites', 'user_' .$favoriteid );
if ( !$favorites_list ) {
$favorites_list = [];
}
// profile favorite
if ( in_array( $favoriteid, $favorites_list ) ) {
$favorites_num--;
$tmp = array_search( $userid, $favorites_list );
array_splice( $favorites_list, $tmp, 1 );
$is_favorite = false;
} else {
$favorites_num++;
$favorites_list[] = $favoriteid;
$is_favorite = true;
}
// set favorite counter
update_user_meta( $favoriteid, 'favorites', $favorites_num );
// set favorite list
update_user_meta( $userid, 'favorites_list', $favorites_list );
echo json_encode( array(
'favorites_num' => $favorites_num,
'favorites_list' => $favorites_list,
'is_favorite' => $is_favorite,
) );
die();
}
function is_favorite($userid, $favoriteid) {
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
return in_array( $favoriteid, $favorites_list );
}
function get_favorites_num( $userid ) {
if ( get_field( 'favorites', 'user_' .$userid ) ) {
return get_field( 'favorites', 'user_' .$userid );
} else {
return '0';
}
}
add_action('wp_ajax_setfavorite', 'setfavorite');
add_action('wp_ajax_nopriv_setfavorite', 'setfavorite');
i maybe will implement a same function in the next 2 months. i allready started researching plugins but as your question states, it does not seems to be very hard.
I try to come back then but first i need a frontend profile page where i can list the favorites.
The first impression looks good so far but first i would give attention to the $_POST array and sanitize and maybe validate the values because sometimes not only your ajax will call.
if ( isset($_POST['userid']) && isset($_POST['favoriteid']) ) { // Both $_POST values exist
$userid = filter_var($_POST['userid'], FILTER_SANITIZE_NUMBER_INT);
$favoriteid = filter_var($_POST['favoriteid'], FILTER_SANITIZE_NUMBER_INT);
if ( filter_var($userid, FILTER_VALIDATE_INT) && filter_var($favoriteid, FILTER_VALIDATE_INT) ) {
// $_POST was save, both values are Integers
}
}
The second one is related to get_field which is a function provided by the ACF Plugin. therefor when deactivating it or it gets replaced with JCF, it may cause errors.
You can avoid this by using if ( function_exists('get_field') ) {. Then your code only stops working when ACF gets deactivated.
Otherwise it seems not neccessary to use the ACF function and you can use the WP native function get_user_meta instead:
function is_favorite($userid, $favoriteid){
$favorites_list = get_user_meta($userid, 'favorites_list', true);
// check the new output instead of get_field
return in_array( $favoriteid, $favorites_list );
}
and also all calls to get_field('favorites', 'user_' .$favoriteid) seem to be wrong then. The ACF Docs say the the second parameter of get_field ist a post ID so i don't know what 'user_' means then. I would call:
function get_favorites_num($favoriteid){
return get_user_meta($favoriteid, 'favorites', true) || 0;
}
i now have my own favorite system ready where users can favorite posts from a specific post_type
HTML
<?php while ( have_posts() ) : the_post() ?>
<?php
$customPostsMeta = get_post_custom();
$favorite_class = 'favorite-me disabled';
$fav_count = isset($customPostsMeta['_favorites']) ? intval($customPostsMeta['_favorites'][0]) : 0;
$fav_count_text = $fav_count > 0 ? '(' . $fav_count . ')' : '';
$fav_count = ' <span class="fav-count clearfix">' . $fav_count_text . '</span>';
$favorite_title = '';
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
$fav_key = array_search($post_id, $favorites);
$is_favorite = ( $fav_key !== false );
if ( $is_favorite ) {
$favorite_class .= ' is-favorite';
$favorite_title = ' title="' . get_the_title() . ' ' . __('favorisieren', 'myTheme') . '"';
} else {
$favorite_title = ' title="' . get_the_title() . ' ' . __('nicht mehr favorisieren', 'myTheme') . '"';
}
}
?>
<a class="<?php echo $favorite_class; ?>" href="#post-<?php the_ID() ?>"<?php echo $favorite_title; ?>><?php echo __('Favorit', 'myTheme')?><?php echo $fav_count; ?></a>
<?php endwhile; ?>
JS
// i use a small self written JS module frame where this is included as module
// favorite.setup() is fired imediatly, favorite.ready() fires on document ready
// you can see a full version here: https://dev.alphabetisierung.at/wp-content/themes/sandbox_2017/js/actions.js
// line 732
/**
* Favorites ajax system
* =====================
* https://stackoverflow.com/questions/60468237
*/
favorite: {
options: {
selectors: {
link: '.favorite-me',
fav_count: '.fav-count'
},
classNames: {
disabled: 'disabled',
is_favorite: 'is-favorite',
}
},
events: function(){
var options = this.options,
selectors = options.selectors,
classNames = options.classNames,
info = this.info;
this.$favorites.on('click', function(event){
var post_id = this.hash.replace('#post-', ''),
$favorite_link = $(this).addClass(classNames.disabled),
$fav_count = $favorite_link.children(selectors.fav_count),
$favorite = $.ajax({
url: myTheme.page.urls.ajax,
type: 'post',
data: {
action: info.name, // derived from the module name "favorite"
verify: myTheme.page.verify, // https://developer.wordpress.org/reference/functions/check_ajax_referer/
post_id: post_id
// user_id of user who takes the action is not necessary
}
});
$favorite.done(function(data){
var fav_count = data.hasOwnProperty('fav_count') ? parseInt(data.fav_count) : 0,
fav_count_text = '',
is_favorite = data.hasOwnProperty('is_favorite') ? data.is_favorite : false;
if ( fav_count > 0 ) {
fav_count_text = '(' + fav_count + ')';
}
$fav_count.html(fav_count_text);
if ( is_favorite && !$favorite_link.is('.' + classNames.is_favorite) ) {
$favorite_link.addClass(classNames.is_favorite);
} else {
$favorite_link.removeClass(classNames.is_favorite);
}
$favorite_link.removeClass(classNames.disabled);
});
event.preventDefault();
});
},
ready: function ready(){
var selectors = this.options.selectors,
classNames = this.options.classNames;
this.$favorites = $(selectors.link).removeClass(classNames.disabled);
this.events();
},
setup: function setup(){
var setup = myTheme.info.is_user_logged_in && myTheme.info.post_type === 'my_custom_post_type';
return setup; // only for my post_type
}
PHP
add_action('wp_enqueue_scripts', 'myTheme_enqueue_scripts');
add_action('wp_ajax_favorite', 'myTheme_set_favorite');
// wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
function myTheme_enqueue_scripts(){
$data = array(
'id' => get_the_ID(),
'urls' => array(
'ajax' => admin_url('admin-ajax.php'),
'template' => get_stylesheet_directory_uri(),
),
'verify' => wp_create_nonce('myThemeOrAction_ajax_call'), // used for check_ajax_referer()
// ...
'info' => array(
// ...
'is_user_logged_in' => is_user_logged_in(),
'post_type' => get_post_type(),
),
);
// ...
wp_localize_script('actions', 'myTheme_data', $data );
}
function myTheme_set_favorite(){
check_ajax_referer('myThemeOrAction_ajax_call', 'verify');
if ( isset($_POST['post_id']) ) {
$user = wp_get_current_user(); // here we get the user ID of the current user
$post_id = filter_var($_POST['post_id'], FILTER_SANITIZE_NUMBER_INT);
$post = get_post($post_id);
// $fav_id = filter_var($_POST['fav_id'], FILTER_SANITIZE_NUMBER_INT);
// $fav_user = get_userdata($fav_id); // WP_User
$is_favorite = false;
if ( $post instanceof WP_Post ) { // post ID is valid
// for user favorites it would be
// if ( $fav_user instanceof WP_User ) {
$fav_count = intval(get_post_meta($post->ID, '_favorites', true));
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
if ( !filter_var($fav_count, FILTER_VALIDATE_INT) ) {
$fav_count = 0;
}
if ( !is_array($favorites) || empty($favorites) ) {
$favorites = array();
}
$fav_key = array_search($post->ID, $favorites);
if ( $fav_key !== false ) { // is favorite, remove it
$fav_count--;
unset($favorites[$fav_key]);
} else { // is no favorite, add it
$fav_count++;
$favorites[] = $post->ID;
$is_favorite = true;
}
// set favorite counter
update_post_meta($post->ID, '_favorites', $fav_count);
// set favorite list
update_user_meta($user->ID, '_favorite_posts', $favorites);
// Output
$json = array(
'fav_count' => $fav_count,
'favorites' => $favorites,
'error' => false,
'is_favorite' => $is_favorite,
);
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'Invalid Post ID');
}
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'No post_id Post ID sent');
}
// wp_send_json sets the http header and ends the request
wp_send_json($json);
}
this are the things i noticed on the way:
verify referer with wp_create_nonce() and check_ajax_referer()
check JSON result data keys for existance with data.hasOwnProperty('key') to avoid possible JS errors
check valid WP_User or WP_Post object
current users ID with is not necessary to send with POST
wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
use wp_send_json() for ending the response
kind regards
tom
I am inserting data successfully by selecting multiple row table data but at the same time I want to print data on print page.
In above image I select only 3 record and insert in data base at the time of insert that selected data I want show on my print page.
Create page:
<form>
<table id="pending_collection_table"> </table>
<input type="button" id="allocate" value="allocate" name="allocate">
</form>
<script>
$('#allocate').click(function (event) {
event.preventDefault();
var allVals = [];
$('input[name=selectedBilties]:checked').each(function() {
allVals.push($(this).val());
});
var formData = new FormData();
var agent = $('#agent').val();
var rec_type = $('#rec_type').val();
formData.append("agent",agent);
formData.append("rec_type",rec_type);
for (var i = 0; i < allVals.length; i++) {
formData.append('due_ids[]', allVals[i]);
}
alertify.confirm('Payment Recovery Allocation', 'Do you want to Allocate ?', function(){
$.ajax({
url :"<?php echo base_url();?>crossing/payment_rec_allocation/PaymentRecAllocationController/createPaymentAllocation",
type:"POST",
dataType: "json",
data:formData,
contentType:false,
cache:false,
processData:false,
success: function(data){
if(data.PaymentRecAllocation.form_status=='false'){
}
else if(data.PaymentRecAllocation.form_status=='true'){
alertify.confirm('Payment Recovery Allocation', 'Do you want to print ? ', function(){
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
setTimeout(location.reload.bind(location), 2000);
},
function(){
location.href="<?php echo base_url(); ?>", 'refresh';
});
}
}
});
}, function(){
});
});
</script>
Contoller:
public function createPaymentAllocation()
{
$bilty_ids = $this->input->post('due_ids');
$biltyCount = count($bilty_ids);
$agent = $this->input->post('agent');
$due_to = $this->input->post('due_to');
for($i = 0; $i < $biltyCount; $i++) {
$data = array(
'agent_id' =>$agent,
'pay_dueto' =>$due_to,
'mr_no' =>$bilty_ids[$i],
);
$modelResult = $this->PayRecAllModel->inserPaymentAllocation($data);
}
if($modelResult){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate'
);
}else{
$data['PaymentRecAllocation'] = array(
'form_status' => 'false',
'form_message' => 'Something went wrong.'
);
}
echo json_encode($data);
}
Model:
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
return true;
}else {
return false;
}
}
And now my print function on controller
public function printCollectionRecPage(){
$this->load->view('template/header');
$data= array();
$data['collnR'] = $this->PayRecAllModel->printCollectionRecPage();
$this->load->view('crossing/payment_rec_allocation/printCollectionRecovery',$data);
$this->load->view('template/footer');
}
model of print page:
public function printCollectionRecPage(){
$this->db->select('*');
$this->db->from('payment_rec_allocn');
$this->db->join('crossing_cash_memo', 'payment_rec_allocn.mr_no = crossing_cash_memo.mr_no');
$this->db->where('total !=','0');
$query = $this->db->get();
return $query->result();
}
How I can pass ids in print page.
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage";
How can I pass that selected ids on print page.
And my print page I have table to show data of selected data on inset time.
You can use insert_id() function
public function inserPaymentAllocation($data){
if($this->db->insert('payment_rec_allocn', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}else {
return false;
}
}
store returned ids into array
$modelResult[] = $this->PayRecAllModel->inserPaymentAllocation($data);
if(!empty($modelResult)){
$data['PaymentRecAllocation'] = array(
'form_status' => 'true',
'form_message' => 'Payment Recovery has been successfully Allocate',
'form_ids' => $modelResult
);
}
Pass the ids to your controller for print
var ids = data.PaymentRecAllocation.form_ids.join(',');
window.location.href =" <?php echo base_url(); ?>crossing/payment_rec_allocation/PaymentRecAllocationController/printCollectionRecPage?ids="+ids;
But in case of multiple inserts you should ideally use
$this->db->trans_start();
//all your insertion code here
//if anything breaks the db will be rollback
$this->db->trans_complete();
JQuery Code:
jQuery("#dmhsc-form").on("submit", function () {
var form = this;
if (jQuery("input[name='url']", form).val() == "") {
jQuery("div[id='results']", form).html('<div class="not-available">Please, Enter site address.</div>');
return false;
}
var url = jQuery("input[name='url']", form).val();
jQuery("div[id='results']", form).css('display', 'none');
jQuery("div[id='results']", form).html('');
jQuery("div[id='loading']", form).css('display', 'inline');
var data = {
'action': 'dmhsc_show',
'url': url,
'security': badnc_ajax.dmhsc_nonce
};
jQuery.post(badnc_ajax.ajaxurl, data, function (response) {
var x = JSON.parse(response);
if (x.status >= 0) {
display = x.text;
} else {
display = "Error occured." + x;
}
jQuery("div[id='results']", form).css('display', 'block');
jQuery("div[id='loading']", form).css('display', 'none');
jQuery("div[id='results']", form).html(unescape(display));
});
return false;
});
Plugin File
function badnc_load_styles() {
wp_enqueue_script( 'badnc-script', plugins_url( 'script.js', __FILE__ ), array('jquery')); // script.js contains jquery code
wp_localize_script( 'badnc-script', 'badnc_ajax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'dmhsc_nonce' => wp_create_nonce( 'dmhsc_nonce' ))
);
}
add_action( 'wp_loaded', 'badnc_load_styles' );
add_action( 'admin_enqueue_scripts', 'badnc_load_styles' );
function dmhsc_show() {
check_ajax_referer( 'dmhsc_nonce', 'security' );
if(isset($_POST['url']))
{
$url = sanitize_text_field($_POST['url']);
if(!$url || !is_string($url) || ! preg_match('/^(https?:\/\/)?(www\.)?\w+\.[a-z]{2,6}(\/)?$/i', $url)) {
$result = array('status'=>0,'url'=>$url, 'text'=> '<div class="not-available">Please, Enter valid domain name.</div>');
echo json_encode($result);
} else {
/*$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$url.'</div>');
echo json_encode($result);*/ //It display the message without calling to fucntion
check_https($url); //function call
}
}
die();
}
add_action('wp_ajax_dmhsc_show','dmhsc_show');
add_action('wp_ajax_nopriv_dmhsc_show','dmhsc_show');
function check_https($host) {
$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$host.'</div>');
echo json_encode($result);
}
Problem
I want to show "Domain: domain name" when I submit the form. Form contains url field and submit button.
but I don't know it is not displaying the message written in check_https() function.
I am also getting error in console:
Uncaught SyntaxError: Unexpected token { in JSON at position 74
at JSON.parse (<anonymous>)
If I display the message without calling to function check_https(), it works.
What should be the problem.
I have a problem with my code. I am studying jquery ajax. And I have a difficulty in it. I am creating an 'add to cart' function in my simple e-commerce site. And I am doing this with database interaction. Here's what I did so far.
Here's my PHP part
$product_id = $_GET['product'];
....
<input type="hidden" name="cart_product_id" id="cart_product_id" value="<?php echo $product_id; ?>" />
<input type="hidden" name="cart_user_id" id="cart_user_id" value="<?php echo $_SESSION['member']; ?>" />
Here's my javascript part
function notification_message(type) {
var confirmation = '';
if(type == 'cart') {
confirmation = '#cart_confirm';
} else {
confirmation = '#wishlist_confirm';
}
$(confirmation).dialog({
resizable: false,
height: 220,
modal: true,
draggable: false,
buttons: {
"Yes": function() {
if(type == 'cart'){
add_cart();
} else {
add_wishlist();
}
},
"No": function() {
$( this ).dialog( "close" );
}
}
});
}
//this is the main function I need to process
function add_cart(){
var cart_product_id = $("#cart_product_id").val();
var cart_user_id = $("#cart_user_id").val();
var url_add_cart = '<?php echo $_SERVER['DOCUMENT_ROOT'].'ahm/secure/aroma/aroma_shop.php'; ?>';
console.log(url_add_cart);
$.ajax({
type: 'POST',
url: url_add_cart,
data: { user_id: cart_user_id, product_id: cart_product_id },
dataType: 'json',
success: function(d) {
console.log(d);
}
});
}
function add_wishlist(){
alert('wishlist');
}
$('#register_user').click(function(){
$('#failed').dialog('close');
});
function failed() {
$("#failed").dialog({
resizable: false,
height: 220,
modal: true,
draggable: false,
});
}
$(document).ready(function(){
$("#mycart").click(function(){
var product_id = $('#mycart').data('cart-id');
var member_id = '<?php echo $_SESSION[member]; ?>';
var type = 'cart';
notification_message(type);
});
$("#mywishlist").click(function(){
var product_id = $('#mywishlist').data('wishlist-id');
var member_id = '<?php echo $_SESSION[member]; ?>';
var type = 'wishlist';
if (member_id == '') {
failed();
} else {
notification_message(type);
}
});
});
Now here's my separate PHP file that contains the sql query it contains.
function get_cart($user_id) {
$query = mysql_query("SELECT * FROM product_cart WHERE user_id = ".$user_id."");
$row = mysql_fetch_array($query);
return $row;
}
function count_cart($user_id) {
$query = mysql_query("SELECT COUNT(*) AS cart_total FROM product_cart WHERE user_id = ".$user_id."");
$row = mysql_fetch_array($query);
return $row['cart_total'];
}
//now, how can I access here the variable I set in the PHP?
function insert_cart(){
//this should be the query part but I dont know how to access the variable
}
In ajax call, you can pass some variable with the url, say url_add_cart+"type=insert_cart"
Then at start of PHP, check-
if(isset($_GET['type'] == "insert_cart"))
echo insert_cart();
Now, in that function just get your variables as- $_POST['user_id'] and $_POST['product_id']; do the processing and return whatever you want to return.
Note, return your array after json encoding it- echo json_encode($result_array) - also, use echo not return; since ajax call just get the contents of the url (just like curl)
P.S. This question is long as there's lot of code. Thank you for your patience and time. I appreciate it.
I am using ultimate wp query search filter plugin on my wordpress site. I would like to use chosen plugin instead of default select boxes. The select boxes already on the page are working perfectly with this code.
(function($){
$(".first-ddwn, .second-ddwn, .third-ddwn, .main-ddwn, .posts_ajax select").chosen({
no_results_text: "Oops, nothing found!",
width: "50%"
});
})(jQuery);
I have changed the result html for AJAX search as mentioned by the plugin author so that I get a dropdown of result posts.
add_filter('uwpqsf_result_tempt', 'customize_output', '', 4);
function customize_output($results , $arg, $id, $getdata ){
// The Query
global $post;
$apiclass = new uwpqsfprocess();
$query = new WP_Query( $arg );
ob_start(); $result = '';?>
<form action="<? bloginfo('url'); ?>" method="get"><?php
echo '<select name="page_id" id="page_id">';
echo '<option value="">Select</option>';
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<option value="<? echo $post->ID; ?>"><?php echo the_title(); ?></option>
<?php }
echo '</select>';
echo '<input type="submit" name="submit" value="view" />';
echo '</form>';
} else {
echo 'no post found';
}
/* Restore original Post Data */
wp_reset_postdata();
$results = ob_get_clean();
return $results;
}
However, chosen doesn't get applied to this result dropdown. I have tried the option of using settimeout after the AJAX call as mentioned http://davidwalsh.name/jquery-chosen#comment-29299 but it didn't work. maybe I did it wrong. Also when I run it after ajax call like below, chosen does get applied to the select but is all broken.
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
$(".content select").chosen();
}
});
This is what I get
This is plugin's uwpqsfscript.js file
jQuery(document).ready(function($) {
$('body').on('click','.usearchbtn', function(e) {
process_data($(this));
return false;
});
$('body').on('click','.upagievent', function(e) {
var pagenumber = $(this).attr('id');
var formid = $('#curuform').val();
upagi_ajax(pagenumber, formid);
return false;
});
$('body').on('keypress','.uwpqsftext',function(e) {
if(e.keyCode == 13){
e.preventDefault();
process_data($(this));
}
});
window.process_data = function ($obj) {
var ajxdiv = $obj.closest("form").find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $obj.closest("form").serialize();
var pagenum = '1';
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
}
});
}
window.upagi_ajax = function (pagenum, formid) {
var ajxdiv = $(''+formid+'').find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $(''+formid+'').serialize();
jQuery.ajax({
type: 'POST',
url: ajax.url,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty(); res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
//res.container.find(res.loader).remove();
}
});
}
$('body').on('click', '.chktaxoall,.chkcmfall',function () {
$(this).closest('.togglecheck').find('input:checkbox').prop('checked', this.checked);
});
});//end of script
And some relevant code (maybe?) from uwpqsf-process-class.php
//front ajax
add_action( 'wp_ajax_nopriv_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'wp_ajax_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'pre_get_posts', array($this ,'uwpqsf_search_query'),1000);
}
function uwpqsf_ajax(){
$postdata =parse_str($_POST['getdata'], $getdata);
$taxo = (isset($getdata['taxo']) && !empty($getdata['taxo'])) ? $getdata['taxo'] : null;
$cmf = (isset($getdata['cmf']) && !empty($getdata['cmf'])) ? $getdata['cmf'] : null;
$formid = $getdata['uformid'];
$nonce = $getdata['unonce'];
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
if(isset($formid) && wp_verify_nonce($nonce, 'uwpsfsearch')){
$id = absint($formid);
$options = get_post_meta($id, 'uwpqsf-option', true);
$cpts = get_post_meta($id, 'uwpqsf-cpt', true);
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
$default_number = get_option('posts_per_page');
$cpt = !empty($cpts) ? $cpts : 'any';
$ordermeta = !empty($options[0]['smetekey']) ? $options[0]['smetekey'] : null;
$ordertype = (!empty($options[0]['otype']) ) ? $options[0]['otype'] : null;
$order = !empty($options[0]['sorder']) ? $options[0]['sorder'] : null;
$number = !empty($options[0]['resultc']) ? $options[0]['resultc'] : $default_number;
$keyword = !empty($getdata['skeyword']) ? sanitize_text_field($getdata['skeyword']) : null;
$get_tax = $this->get_uwqsf_taxo($id, $taxo);
$get_meta = $this->get_uwqsf_cmf($id, $cmf);
if($options[0]['snf'] != '1' && !empty($keyword)){
$get_tax = $get_meta = null;
}
$ordermeta = apply_filters('uwpqsf_ometa_query',$ordermeta,$getdata,$id);
$ordervalue = apply_filters('uwpqsf_ometa_type',$ordertype,$getdata,$id);
$order = apply_filters('uwpqsf_order_query',$order,$getdata,$id);
$number = apply_filters('uwpqsf_pnum_query',$number,$getdata,$id);
$args = array(
'post_type' => $cpt,
'post_status' => 'publish',
'meta_key'=> $ordermeta,
'orderby' => $ordertype,
'order' => $order,
'paged'=> $pagenumber,
'posts_per_page' => $number,
'meta_query' => $get_meta,
'tax_query' => $get_tax,
's' => esc_html($keyword),
);
$arg = apply_filters( 'uwpqsf_query_args', $args, $id,$getdata);
$results = $this->uajax_result($arg, $id,$pagenumber,$getdata);
$result = apply_filters( 'uwpqsf_result_tempt',$results , $arg, $id, $getdata );
echo $result;
}else{ echo 'There is error here';}
die;
}//end ajax
function uajax_result($arg, $id,$pagenumber,$getdata){
$query = new WP_Query( $arg );
$html = '';
//print_r($query); // The Loop
if ( $query->have_posts() ) {
$html .= '<h1>'.__('Search Results :', 'UWPQSF' ).'</h1>';
while ( $query->have_posts() ) {
$query->the_post();global $post;
$html .= '<article><header class="entry-header">'.get_the_post_thumbnail().'';
$html .= '<h1 class="entry-title">'.get_the_title().'</h1>';
$html .= '</header>';
$html .= '<div class="entry-summary">'.get_the_excerpt().'</div></article>';
}
$html .= $this->ajax_pagination($pagenumber,$query->max_num_pages, 4, $id,$getdata);
} else {
$html .= __( 'Nothing Found', 'UWPQSF' );
}
/* Restore original Post Data */
wp_reset_postdata();
return $html;
}//end result
I have been searching for days and have tried many things to make this work. I have no knowledge of jquery,so maybe someone will help me out.
Many Thanks