I am using wordpress and have a function like this, how to redirect to the corresponding url only happens onclick, for now the "en" language page is automatically redirecting after the page load, but the "zh-hant" redirecting after click, anyone can help me to check the code?
Thanks.
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
if(ICL_LANGUAGE_CODE=='en'){
?>
<script>
window.beforeConfirmedBooking = function() {
window.location.href = "https://aaa.com";
};
</script>
<?php
}
if(ICL_LANGUAGE_CODE=='zh-hant'){
?>
<script>
window.beforeConfirmedBooking = function() {
window.location.href = "https://aaa.com/zh-hant";
};
</script>
<?php
}
}
}
You should be doing all of it in one function itself
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
$url_endpoint = '';
if(ICL_LANGUAGE_CODE=='en'){
} else if (ICL_LANGUAGE_CODE=='zh-hans') {
$url_endpoint = '/zh-hans';
}else if (ICL_LANGUAGE_CODE=='zh-hant') {
$url_endpoint = '/zh-hant';
}
?>
<script>
window.beforeConfirmedBooking = function() {
window.location.href = "https://aaa.com<?php echo $url_endpoint; ?>";
};
const btn = document.querySelector('.el-button .el-button--primary .redirect-link');
btn.addEventListener('click', beforeConfirmedBooking);
</script>
<?php
}
}
You can also do it just using php and no js at all
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
$url_endpoint = '';
if(ICL_LANGUAGE_CODE=='en'){
} else if (ICL_LANGUAGE_CODE=='zh-hans') {
$url_endpoint = '/zh-hans';
}else if (ICL_LANGUAGE_CODE=='zh-hant') {
$url_endpoint = '/zh-hant';
}
}
}
// The following will redirect you to where ever you want
header('Location: https://aaa.com' . $url_endpoint);
/* Make sure that code below does not get executed when we redirect. */
One method would be to do the below using a switch statement.
This allows for easy growth and in the event you end up with a LOT of languages easy to just repeat and falls back to the site URL in the event there isn't a match.
add_action( 'wp_head', 'redirect_after_booking' );
function redirect_after_booking() {
if ( in_category('teachers') ) {
switch (CL_LANGUAGE_CODE) {
case 'zh-hant':
wp_redirect( trailingslashit( get_site_url() ) . CL_LANGUAGE_CODE );
exit;
break;
default:
wp_redirect( get_site_url() );
exit;
}
}
}
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
Iam facnigg and issue with ajax, Im working on a contact form and I have an issue with the ajax call,
The call is never succseed, even if the field are all typed correctly.
I tried few things but nothing is working
Somene can give me an advice..?
Many thanks.
$.ajax({
url: "assets/contact_form/process-contact.php",
type: "POST",
dataType: "html",
data: userData,
beforeSend: function () {
$( sb ).html('Sending...');
},
success: function (response) {
if (response == true) {
setTimeout(function () {
window.location = 'index.html';
}, 1000);
} else {
$( sb ).html('Can not send, please try latter'); //IT GOES STRIGHT TO HERE
}
}
});
}
});
here is the php code:
<?php
$userData['name'] = filter_var(trim($_POST['name']),
FILTER_SANITIZE_STRING);
$userData['email'] = filter_var(trim($_POST['email']),
FILTER_VALIDATE_EMAIL);
$userData['phone'] = filter_var(trim($_POST['phone']),
FILTER_SANITIZE_STRING);
$userData['message'] = filter_var(trim($_POST['message']),
FILTER_SANITIZE_STRING);
if( ! in_array( null, $userData ) ){
$my_email = 'roni.itzhaik#gmail.com';
$nameRegx = "/^[' a-zא-ת]+(\s[' a-zא-ת]+)*$/i";
$phoneRegx = "/^(?:0(?!(5|7))(?:2|3|4|8|9))(?:-?\d){7}$|^(0(?=5|7)(?:-?\d)
{9})$/";
if( strlen($userData['name']) > 2 && strlen($userData['name']) < 70 &&
preg_match($nameRegx, $userData['name']) ) {
if( preg_match($phoneRegx, $userData['phone']) ){
if( strlen($userData['message']) > 2 ){
$subject = 'Message from ' . $userData['name'] ;
$message_phone= $userData['message'].'Phone number:
'.$userData['phone'];
$headers = 'From: ' . $userData['email']. "\r\n";
mail($my_email, $subject, $message_phone, $headers);
// send mail
// Save data to db (DON'T FORGET TO CLEAN AGAINST SQL INJECTIONS!!!)
echo true;
}}}}
This may work.
......
if (response) {
setTimeout(function () {
window.location = 'index.html';
.....
It will be better if you could return an object instead :
echo json_encode(['success' => true]);
Then the check in your success callback will looks like :
if (response.success){
//Your logic
}
Hope this helps.
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 ) {
}
});
I am working in WordPress and I run a function to insert a row in database with ajax. Ajax runs but for some reason insert operation is performed twice.
Below is my code
Ajax
jQuery(function ($) {
$(document).on("submit","#myvoteform", function(e) {
//form is intercepted
e.preventDefault();
//serialize the form which contains secretcode
var sentdata = $(this).serializeArray();
//Add the additional param to the data
sentdata.push({
name: 'action',
value: 'votes'
})
//set sentdata as the data to be sent
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
//$("#myresult").append(res.l);
// $("#myresult").html("");
$("#myresult").html(res);
//$.parseJSON(data);
return false;
} //end of function
,
'json'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
}); //vote function ends here
PHP code
Insert function
add_action( 'wp_ajax_votes', 'votes' );
add_action( 'wp_ajax_nopriv_votes', 'votes');
add_shortcode('sketchfamvotes','voteus');
function voteus(){
// register & enqueue a javascript file called globals.js
wp_register_script( 'votess', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) );
wp_enqueue_script( 'votess' );
// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'votess', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function votes ()
{//echo json_encode("pakistan zindabad"); die();
$cat =$_POST['category'];
$comp = $_POST['competition'];
$uid= $_POST['uid'];
global $wpdb;
$userid = $_POST['userid'];
$myvote = 1;
if($wpdb->insert(
'votes',
array(
'votes' => 1,
'competition' => $comp,
'uid' => $uid
)
) == false) {wp_die(json_encode('Database Insertion failed')); die();} else {echo json_encode('your vote was successfully recorded');die();}
}
Below is my form which is the result of another ajax call. I'm not pasting the full ajax php function but just showing how my form looks like.
if( is_array($results) && count($results) > 0 ) {
$form = "";
foreach( $results as $result ) {
$form .= '<form id="myvoteform" action="" method="post">';
$form .= "<input name='category' type='hidden' value='$result->category'>";
$form .= "<img src='$result->path' width='150' height='150' >" . '<br><br>';
$form .= "<input name='uid' type='text' value='$result->uid'>";
$form .= "<input name='competition' type='hidden' value='$result->competition'>";
$form .= "<input name='userid' value'$result->uid' type='text'>".'<br>';
$form .= $result->category.'<br>';
$form .= $result->uid.'<br>';
$form .= $result->votessum.'<br>';
$form .= "<input style='margin-bottom:30px;' id='votebutton' value='vote' name='submit' type='submit'/></form>";
Try with this modified code - jquery .off()
jQuery(function ($) {
$(document).off().on("submit","#myvoteform", function(e) {
//form is intercepted
e.preventDefault();
//serialize the form which contains secretcode
var sentdata = $(this).serializeArray();
//Add the additional param to the data
sentdata.push({
name: 'action',
value: 'votes'
})
//set sentdata as the data to be sent
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
//$("#myresult").append(res.l);
// $("#myresult").html("");
$("#myresult").html(res);
//$.parseJSON(data);
return false;
} //end of function
,
'json'); //set the dataType as json, so you will get the parsed data in the callback
}); // submit end here
}); //vote function ends here