I have a Wordpress website hosted on 20i. I'm almost certain that everything worked fine until I pointed the a records to get the website off its test domain and onto the actual one, this might be unrelated but I figured I'd mention it incase. Anyway for some reason my Ajax function works fine on desktop but not on mobile. When I look at it on mobile none of the posts are visible and if I select a filter nothing happens. Does anyone know what this could be? I've looked around for answers but I can't seem to find the solution.
Here's my code;
jQuery
// submit form function
jQuery('#form').on('submit', function(e){
e.preventDefault();
var $ = jQuery;
var filter = $('#form');
var form_data = $('#form').serializeArray();
$('#load_more').data('page', 1);
$.ajax({
url: ajax_url,
type: 'post',
data: form_data,
dataType: 'json',
error : function(response){
console.log(response);
},
success : function(response){
$('#loop').empty();
for( var i = 0; i < response.post_cont.length; i++ ){
var html =''+
'<div class="col-12 col-md-4 column">'+
'<a href="'+ response.post_cont[i].permalink +'">'+
'<div class="card" style="width: 100%;">'+
'<div class="post_image" style="background-image: url('+ response.post_cont[i].image +');"></div>'+
'<div class="card-body">'+
'<h5 class="card-title">'+ response.post_cont[i].title +'</h5>'+
'</div>'+
'</div>'+
'</a>'+
'</div>';
$('#loop').append(html);
}
}
});
});
php AJAX function
<?php
add_action('wp_ajax_nopriv_filter', 'filter');
add_action('wp_ajax_filter', 'filter');
// this function runs after it is called inside our_work_ajax.js
function filter(){
if( $_POST['type'] && !empty($_POST['type']) ){
$category = $_POST['type'];
}else{
$category = array( 'Assisted Needs/Residential', 'Commercial/Educational', 'Private Housing', 'Social-Housing' );
}
$args = array(
'post_type' => 'our_work',
'posts_per_page' => 9,
'orderby' => 'date',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $category
)
)
);
$query = new WP_Query( $args );
$no_of_posts = $query->found_posts;
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
$main_field = get_field('Images');
$first_row = $main_field[0];
$img = $first_row['Image'];
$imgsize = $img['sizes']['large'];
// creating an array of content needed from array
$post_cont[] = array(
"permalink" => get_the_permalink(),
"image" => $imgsize,
"title" => get_the_title(),
);
endwhile;
endif;
// array getting the total number of posts
$max_posts[] = array(
"no_of_posts" => $no_of_posts
);
// converting arrays into json and submitting it to the ajax_url for the .js file
echo json_encode(array( "post_cont" => $post_cont, "max_posts" => $max_posts));
wp_reset_postdata();
die();
}
?>
HTML
<form action="" method="POST" id="form">
<div id="filters">
<div class="option">
<p>Assisted Needs/Residential</p>
<input type="checkbox" name="type[]" value="Assisted Needs/Residential">
</div>
<div class="option">
<p>Commercial/Educational</p>
<input type="checkbox" name="type[]" value="Commercial/Educational">
</div>
<div class="option">
<p>Private Housing</p>
<input type="checkbox" name="type[]" value="Private Housing">
</div>
<div class="option">
<p>Social Housing</p>
<input type="checkbox" name="type[]" value="Social Housing">
</div>
</div>
<input type="hidden" name="action" value="filter">
</form>
<div id="loop" class="row">
</div>
<script>
jQuery(document).ready(function($){
var inputs = $('#form .option input');
inputs.each(function(){
if( $(this).is(':checked') ){
$(this).parent().addClass('active');
}
});
$('#form').submit();
});
</script>
AJAX url inside functions.php
wp_localize_script( 'all_js', 'ajax_url', admin_url('admin-ajax.php') );
Related
I am trying to build a component that looks like a WooCommerce product page, it should have a filter(category), a search box, and pagination, and a dropdown that users can select how many posts they want to display on the page. Currently, I am using ajax and a jQuery plugin called twbs-pagination to build this function, the code looks awful, and is not organized. I am wondering if timber has a native way to do it.
JS FILE
jQuery(document).ready(function ($) {
function ftGetPost(page = 1) {
$.ajax({
type: 'GET',
url: ajaxurl,
dataType: 'JSON',
data: {
'action': 'flatsome_get_posts',
'paged': page,
'category': $('#ft-category').val(),
'keyword': $('input[name=ft-keyword]').val(),
},
success: function (data) {
console.log(data);
$('#ft-block__posts-holder').empty().html(data.data.posts);
$('#ft-block__pager').twbsPagination({
totalPages: data.data.pages,
visiblePages: 7,
onPageClick: function (event, page) {
ftGetPost(page);
},
});
},
});
}
ftGetPost();
$('#ft-category').change(function () {
ftGetPost();
});
$('#ft-do-search').click(function () {
ftGetPost();
});
});
PHP FILE
//fetch books from wp
add_action('wp_head', function () {
?>
<script type="text/javascript">
//<![CDATA[
ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
//]]>
</script>
<?php
}, 1);
add_action('wp_ajax_flatsome_get_posts', 'flatsome_get_posts');
add_action('wp_ajax_nopriv_flatsome_get_posts', 'flatsome_get_posts');
function flatsome_get_posts()
{
$paged = $_GET['paged'] ?? 1;
$posts_per_page = 4;
$args = [
'post_type' => 'books',
'paged' => $paged,
'posts_per_page' => $posts_per_page,
];
$ft_query = new WP_Query($args);
$html = '';
if ($ft_query->have_posts()) {
foreach ($ft_query->get_posts() as $post) {
$html .= '<div class="ft_post">';
$html .= '<div class="ft-post__image">';
if (has_post_thumbnail()) {
$html .= get_the_post_thumbnail($post->ID, 'full');
}
$html .= '</div>';
$html .= '<h3 class="ft-post__title" style="white-space:normal;">';
$html .= $post->post_title;
dump($post->post_title);
die();
$html .= '</h3>';
$html .= "<p>";
$html .= trim($post->post_content);
$html .= "</p>";
$html .= '</div>';
}
}
$posts = ob_get_clean();
wp_send_json_success([
'posts' => $html,
'pages' => $ft_query->max_num_pages,
]);
exit;
}
<div class="ft-block">
<div class="ft-block__header">
<label for="ft-category">Filter By</label>
<select name="category" id="ft-category">
<option value="" disabled selected>CATEGORIES</option>
<option value="BOOKS">BOOKS</option>
<option value="PODCAST">PODCAST</option>
</select>
<label>
<input type="search" name="ft-keyword">
<button id="ft-do-search">Search</button>
</label>
</div>
<div id="ft-block__posts-holder">
</div>
<div class="ft-block__footer">
<div id="ft-block__pager"></div>
</div>
</div>
TWIG Template
With this I add a custom field to a category:
add_action ( 'edit_category_form_fields', function( $tag ){
$cat_title = get_term_meta( $tag->term_id, '_pagetitle', true ); ?>
<tr class='form-field'>
<th scope='row'><label for='cat_page_title'><?php _e('Category Page Title'); ?></label></th>
<td>
<input type='text' name='cat_title' id='cat_title' value='<?php echo $cat_title ?>'>
<p class='description'><?php _e('Title for the Category '); ?></p>
</td>
</tr> <?php
});
add_action ( 'edited_category', function() {
if ( isset( $_POST['cat_title'] ) )
update_term_meta( $_POST['tag_ID'], '_pagetitle', $_POST['cat_title'] );
});
Then I try to add my own text with ajax:
function data_person(){
$catname = $_POST['catName'];
$surnameCat = $_POST["surnameCat"];
$cityCat = $_POST["cityCat"];
$catDob = $_POST["dobCat"];
$catBio = $_POST["catBio"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_sur = $surnameCat;
$cat_city = $cityCat;
$cat_dob = $catDob;
$cat_bio = $catBio;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_bio,
'cat_title' => $cat_sur,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo json_encode("Category added successfully");
} else {
echo json_encode("That category already exists");
}
} else {
echo json_encode("That category already exists");
}
exit;
}
but I am not sure how to add the text to the new created custom field, this isn't working: 'cat_title' => $cat_sur, as it isn't saving the value I am sending from the input field once I click. Basically what should I put instead of 'cat_title' => ?
UPDATE
This is the full code, so in function.php we have:
add_action ( 'edit_category_form_fields', function( $tag ){
$cat_title = get_term_meta( $tag->term_id, '_pagetitle', true ); ?>
<tr class='form-field'>
<th scope='row'><label for='cat_page_title'><?php _e('Category Page Title'); ?></label></th>
<td>
<input type='text' name='cat_title' id='cat_title' value='<?php echo $cat_title ?>'>
<p class='description'><?php _e('Title for the Category '); ?></p>
</td>
</tr> <?php
});
add_action ( 'edited_category', function() {
if ( isset( $_POST['cat_title'] ) )
update_term_meta( $_POST['tag_ID'], '_pagetitle', $_POST['cat_title'] );
});
add_action( 'wp_footer', 'ajax_Person' );
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#saveperson").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#nameCat').val(), catSurnam: jQuery('#surnameCat').val(), catCity: jQuery('#cityCat').val(), catDob: jQuery('#dobCat').val(), catBio: jQuery('#bioCat').val() },
success: function(data) {
jQuery(".modal-body .help-text").html(data);
}
});
}
</script>
<?php }
add_action('wp_ajax_data_person' , 'data_person');
add_action('wp_ajax_nopriv_data_person','data_person');
function data_person(){
$catname = $_POST['catName'];
$surnameCat = $_POST["surnameCat"];
$cityCat = $_POST["cityCat"];
$catDob = $_POST["dobCat"];
$catBio = $_POST["catBio"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_bio,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
$cat_id = wp_insert_category( $my_cat );
if( ! is_wp_error( $cat_id ) && (int)$cat_id ) {
// NOW, add the metadata...
add_term_meta( $cat_id, '_pagetitle', $surnameCat );
echo json_encode("Category added successfully");
} else {
echo json_encode("That category already exists");
}
}
exit;
}
And the html:
<div class="col-xs-12">
<div class="add-pearson-form memory-form">
<div class="m-form-wrap">
<i class="fa fa-times-circle"></i>
<div class="team_person">
<div class="form-group">
<div class="col-xs-12 col-sm-8 col-sm-offset-2">
<h4 class="text-center text-uppercase">aggiungi una persona</h4>
<input type="text" class="form-control" placeholder="NOME">
<input type="text" class="form-control" placeholder="COGNOME">
<input type="text" class="form-control" placeholder="CITTA">
<input type="text" class="form-control pickdate" placeholder="DATA DI NASCITA">
<textarea class="form-control" id="froala-editor" placeholder=" type ricordo"></textarea>
<div class="text-center">
inserisci persona
</div>
</div>
</div>
</div>
</div>
</div>
</div>
The answer to your question is to use the add_term_meta function.
Don't insert cat_title into the category - the wp_insert_category function doesn't accept / use that argument.
Instead, get the category ID back from wp_insert_category, then use that ID to add the meta value.
See your modified / simplified code below, with comments explaining changes:
// no need to assign variables here, commented out and using originals below
// $cat_name = $catname;
// $cat_sur = $surnameCat;
// $cat_city = $cityCat;
// $cat_dob = $catDob;
// $cat_bio = $catBio;
// $cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $catname,
'category_description' => $catBio,
// this is a _custom meta field_, so doesn't get inserted here...
// 'cat_title' => $cat_sur,
'category_nicename' => sanitize_title_with_dashes($catname),
'category_parent' => 0
);
// get the category ID from the insert
$cat_id = wp_insert_category( $my_cat );
if( ! is_wp_error( $cat_id ) && (int)$cat_id ) {
// NOW, add the metadata...
add_term_meta( $cat_id, '_pagetitle', $surnameCat );
echo json_encode("Category added successfully");
} else {
echo json_encode("That category already exists");
}
I am not able to call the search term in functions.php file from search.php file. I am trying to achieve this through the use of script.
$search_term should be called but it is not being called. If I replace it with certain keywords, posts shows perfectly. I want to call search term input by user using the search form.
search.php
<?php $search_query = get_search_query(); ?>
<div align="center">
<h2>Search Results For "<?php echo $search_query ?>"</h2>
</div>
<div class="entry-content" style="margin:2% 0 0 0;">
<?php if (have_posts()) : ?>
<div class="col-lg-12 col-md-12 col-sm-12 my-posts" style="padding:0 1% 1% 1%;">
<?php while (have_posts()) : the_post(); ?>
<?php
echo "<div>";
This Part Shows Content
echo "</div>";
?>
<?php endwhile ?>
</div>
<?php endif ?>
</div>
<div class="loadmore" style="text-align:center;font-size:1.4em;color:#4a235a;padding:1% 0 1% 0;font-weight:900;">
<button type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts</button>
</div>
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {
var data = {
'action': 'load_posts_by_ajax_search',
'page': page,
'searchTerm': $('#s').val(),
'security': '<?php echo wp_create_nonce("load_more_posts_search"); ?>'
};
$.post(ajaxurl, data, function(response) {
$('.my-posts').append(response);
page++;
});
});
});
</script>
functions.php
add_action('wp_ajax_load_posts_by_ajax_search', 'load_posts_by_ajax_callback_search');
add_action('wp_ajax_nopriv_load_posts_by_ajax_search', 'load_posts_by_ajax_callback_search');
function load_posts_by_ajax_callback_search() {
check_ajax_referer('load_more_posts_search', 'security');
$paged_search = $_POST['page'];
$search_term = esc_attr($_POST['searchTerm']);
$args_search = array(
'posts_per_page' => '20',
's' => $search_term,
'paged' => $paged_search,
);
$my_posts_search = new WP_Query( $args_search );
if ( $my_posts_search->have_posts() ) :
?>
<?php while ( $my_posts_search->have_posts() ) : $my_posts_search->the_post() ?>
<?php
echo "<div>";
This Part Shows Content
echo "</div>";
?>
<?php endwhile ?>
<?php endif; ?>
My searchform.php code
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>" target="_self">
<div>
<input style="text-align:center;width:100%;margin:0 0 12px; 0;border-color:#4a235a;color:#000000;" placeholder='Eg:Location,Skill,Company' class="text" type="text" value="" name="s" id="s" />
</div>
<div>
<input type="submit" style="text-align:center;margin:0 0 0 0;width:100%;border:1.5px solid;border-color:grey;background-color:#4a235a;color:#f4511e;" class="submit button" name="submit" value="<?php _e('Search');?>" />
</div>
</form>
i`m making a search for products on the site. When you load the page the first time, you see all the products.
The product block is wrapped in pjax and pagination is carried out by the widget LinkPager.
A search request to the server is carried out through ajax, and a block of products found returns via renderPartial. If I try to switch to the next page, search results are reset and you see all the products again. It turns out that the widget LinkPager doesn’t work properly after carrying out of renderPartital.
view:
<div class="search-wrap">
<input type="text" class="search-input" id="search" placeholder="Поиск по названию" name="p">
<button type="submit" class="btn filter-search-btn-menu" id="btns">Поиск</button>
<script>
$('#btns').on('click', function(e){
var search = $('#search').val();
$.ajax({
type: 'POST',
url: "/person/notice",
data: { 'search': search },
cache: false,
success: function (data) {
$('#allnotice').html(data);
});
});
</script>
</div>
<div id="allnotice">
<?php yii\widgets\Pjax::begin();?>
<div id="up">
<?php if ($offerings) foreach($offerings as $one): ?>
<div class="preview-notice-wrap">
<div class="preview-notice-inner">
<h4><?php echo $one->title; ?></h4>
<div class="preview-notice">
<div>
<p><?php
$price = $one->start_price;
echo number_format($price) . ' ₽';
?></p>
</div>
<div>
<p><?php
$date = $one->created;
echo Yii::$app->formatter->asDate($date, 'd MMMM y');
?> </p>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<div class="notice-pagination-wrap preview-notice-pagination">
<?= \app\components\MyPager::widget([
'pagination' => $pages,
'maxButtonCount' =>7,
'prevPageLabel' => false,
'nextPageLabel' => false,
'activePageCssClass' => ['class' => 'page-active'],
'options' => ['class' => 'page-test'],
'linkOptions' => ['class' => 'page-link'],
]); ?>
</div>
</div>
<?php yii\widgets\Pjax::end(); ?>
</div>
controller:
public function actionNotice()
{
$user_id = Yii::$app->user->id;
$user = Person::findOne($user_id);
if (Yii::$app->request->isPost && Yii::$app->request->isAjax && Yii::$app->request->post()){
$s = \Yii::$app->request->post('search');
$count = \app\models\Offering::find()->where(['person_id' => $user->id])->andWhere(['like', 'title', $s])->count();
$query = \app\models\Offering::find()->where(['person_id' => $user->id])->andWhere(['like', 'title', $s])->orderBy('id DESC');
$pages = new \yii\data\Pagination(['totalCount' => $query->count(),'pageSize' => 4, 'pageParam' => 'page-top']);
$offerings = $query->offset($pages->offset)->limit($pages->limit)->all();
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $this->renderPartial('_notice, ['count' => $count, 'pages' => $pages, 'offerings' => $offerings]);
}
$count = \app\models\Offering::find()->where(['person_id' => $user->id])->count();
$query = \app\models\Offering::find()->where(['person_id' => $user->id])->orderBy('id DESC');
$pages = new \yii\data\Pagination(['totalCount' => $query->count(),'pageSize' => 4, 'pageParam' => 'page-top']);
$offerings = $query->offset($pages->offset)->limit($pages->limit)->all();
return $this->render('notice', ['count' => $count, 'pages' => $pages, 'offerings' => $offerings]);
}
I have one solution:
url: "/person/notice?search="+search,
put value in url.
$('#btns').on('click', function(e){
var search = $('#search').val();
$.ajax({
type: 'POST',
url: "/person/notice?search="+search,
data: { 'search': search },
cache: false,
success: function (data) {
$('#allnotice').html(data);
});
});
and you can catch it in controller
if(isset($_POST['search']))
$search_word = trim($_POST['search']);
if(isset($_GET['search']))
$search_word = trim($_GET['search']);
I am developing a wordpress plugin to allow users to submit a post from the frontend.
I have added a validation method and it works. How do I implement ajax validation in my code?
<?php
function exclutips_fep($content = null) {
global $post;
ob_start();
?>
<style>
#fep-new-post label{display:inline-block;width:15%;}
#fep-post-title input{width:60%;}
#fep-new-post input[type="submit"]{margin-left:15%;width:30%;padding:7px;}
#fep-new-post textarea{ display:inline-block;width:80%;vertical-align:top;}
</style>
<div id="exclutips-fep-postbox" class="<?php if(is_user_logged_in()) echo 'closed'; else echo 'loggedout'?>">
<?php do_action( 'exclutips-fep-notice' ); ?>
<div class="exclutips-fep-inputarea">
<?php if(is_user_logged_in()) { ?>
<form id="fep-new-post" name="new_post" method="post" action="<?php the_permalink(); ?>">
<p><label>Post Title *</label><input type="text" id ="fep-post-title" name="post-title" /></p>
<p>
<?php
$settings = array(
'textarea_rows' => 14,
'teeny' => true,
'quicktags' => false,
'textarea_name' => 'post-content',
'media_buttons' => true,
'editor_class' => 'front-end-post',
'tinymce' => array(
'theme_advanced_buttons1' => 'formatselect,|,bold,italic,underline,|,' .
'bullist,blockquote,|,justifyleft,justifycenter' .
',justifyright,justifyfull,|,link,unlink,|' .
',spellchecker,wp_fullscreen,wp_adv'
)
);
wp_editor( '', 'content', $settings);
?>
</p>
<p><label>Category</label>
<select name="post-category">
<option value=""><?php echo esc_attr_e( 'Select Category', 'exclutips-fep' ); ?></option>
<?php
$args = array(
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
printf( '<option value="%1$s">%2$s</option>',
esc_attr( '/category/archives/' . $category->category_nicename ),
esc_html( $category->cat_name )
);
}
?>
</select>
</p>
<p><label>Tags</label><input id="fep-tags" name="tags" type="text" tabindex="2" autocomplete="off" value="<?php esc_attr_e( 'Add tags', 'exclutips-fep' ); ?>" onfocus="this.value=(this.value=='<?php echo esc_js( __( 'Add tags', 'exclutips-fep' ) ); ?>') ? '' : this.value;" onblur="this.value=(this.value=='') ? '<?php echo esc_js( __( 'Add tags', 'exclutips-fep' ) ); ?>' : this.value;" /></p>
<input id="submit" type="submit" tabindex="3" value="<?php esc_attr_e( 'Post', 'exclutips-fep' ); ?>" />
<input type="hidden" name="action" value="post" />
<input type="hidden" name="empty-description" id="empty-description" value="1"/>
<?php wp_nonce_field( 'new-post' ); ?>
</form>
<?php } else { ?>
<h4 class="exclutips-fep-error">Please Log-in To Post</h4>
<?php } ?>
</div>
</div> <!-- #exclutips-fep-postbox -->
<?php
// Output the content.
$output = ob_get_contents();
ob_end_clean();
// return only if we're inside a page. This won't list anything on a post or archive page.
if (is_page()) return $output;
}
// Add the shortcode to WordPress. [exclutips-fep]
add_shortcode('exclutips-fep', 'exclutips_fep');
function exclutips_fep_errors(){
?>
<style>
.exclutips-fep-error{border:1px solid #CC0000;border-radius:5px;background-color: #FFEBE8;margin: 0 0 16px 0px;padding: 12px;}
</style>
<?php
global $error_array;
foreach($error_array as $error){
echo '<p class="exclutips-fep-error">' . $error . '</p>';
}
}
function exclutips_fep_notices(){
?>
<style>
.exclutips-fep-notice{ border:1px solid #E6DB55;border-radius:5px;background-color: #FFFBCC;margin: 0 0 16px 0px;padding: 12px;}
</style>
<?php
global $notice_array;
foreach($notice_array as $notice){
echo '<p class="exclutips-fep-notice">' . $notice . '</p>';
}
}
function exclutips_fep_add_post(){
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'post' ){
if ( !is_user_logged_in() )
return;
global $current_user;
$user_id = $current_user->ID;
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_category = $_POST['post-category'];
$tags = $_POST['tags'];
global $error_array;
$error_array = array();
if (empty($post_title)) $error_array[]='Please add a post title.';
if (empty($post_content)) $error_array[]='Please add some content.';
if (empty($post_category)) $error_array[]='Please select category.';
if (count($error_array) == 0){
$post_id = wp_insert_post( array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_type' => 'post',
'post_content' => $post_content,
'post_category' => $post_category,
'tags_input' => $tags,
'post_status' => 'publish'
) );
global $notice_array;
$notice_array = array();
$notice_array[] = "Thank you for posting. Your post is now live. ";
add_action('exclutips-fep-notice', 'exclutips_fep_notices');
} else {
add_action('exclutips-fep-notice', 'exclutips_fep_errors');
}
}
}
add_action('init','exclutips_fep_add_post');
Please try it.. it is works for me.
1) call this on click of your button.. (it is the code of your lending page)
var pathname = window.location.pathname;
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var email = $('#email').val();
var phoneNumber = $('#phoneNumber').val();
var data = new Array (firstName,lastName,email,phoneNumber);
$.get( ajax_request_url,
{
'action' : 'get_myusers',
'data' : data,
'pathname' : pathname
},
function( response )
{
$('.displayUsers').html(response);
$('#myForm')[0].reset();
$('.addForm').hide();
$('.displayAddForm').show();
$('.hideAddForm').hide();
}, "html" );
2) this is functions.php code
/* custom function for display user
* using ajax user add update delete
*/
add_action('wp_footer', 'eps_footer');
function eps_footer() {
echo "<script>var ajax_request_url = '".admin_url( 'admin-ajax.php' )."'</script>";
}
//Get user Ajax
add_action( 'wp_ajax_nopriv_get_myusers', 'get_myusers' );
add_action( 'wp_ajax_get_myusers', 'get_myusers' );
function get_myusers()
{
$userArray = $_REQUEST['data'];
$table = "my_table";
$data = array(firstName=>$userArray[0],lastName=>$userArray[1],email=>$userArray[2],foneNumber=>$userArray[3]);
global $wpdb;
$wpdb->insert( $table, $data );
?>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Action</th>
</tr>
<?php
$users = $wpdb->get_results( "SELECT * FROM my_table" );
foreach($users as $user)
{
?>
<tr id="displayTr<?php echo $user->my_table_id;?>">
<td><?php echo $user->firstName; ?></td>
<td><?php echo $user->lastName; ?></td>
<td><?php echo $user->email; ?></td>
<td><?php echo $user->foneNumber; ?></td>
<td>
Delete
Edit
</td>
</tr>
<tr style="display:none;" class="editTr" id="editTr<?php echo $user->my_table_id;?>">
<td><input type="text" id="firstName<?php echo $user->my_table_id;?>" value="<?php echo $user->firstName; ?>"></td>
<td><input type="text" id="lastName<?php echo $user->my_table_id;?>" value="<?php echo $user->lastName; ?>"></td>
<td><input type="text" id="email<?php echo $user->my_table_id;?>" value="<?php echo $user->email; ?>"></td>
<td><input type="text" id="phoneNumber<?php echo $user->my_table_id;?>" value="<?php echo $user->foneNumber; ?>"></td>
<td>
Update
Cancle
</td>
</tr>
<?php
}
?>
</table>
<?php
}
die();
You can do like some steps below:
Step 1: Localize WP Ajax URL
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() { ?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Step 2: Send your post information by using ajax
$.ajax({
type: 'post',
url: ajaxurl ,
data: {
action: 'validation',
data: [yourdata]
},
beforeSend: function() {},
success: function(resp) {
}
});
Step 3: Receive data on PHP server by using WP Hook
<?php
// this action will run for loged in user
add_action('wp_ajax_validation', 'exclutips_fep_add_post');
// This action will run for visitor
add_action('wp_ajax_wp_ajax_nopriv_validation', 'exclutips_fep_add_post');?>
Hope Those can help you solve your problem.
Your question is a bit open ended. But one important piece of security validation is implementing nonces. This checks the ajax request is coming from your site as intended, which prevents a variety of attacks.
In your php you create a nonce and pass it into the javascript as a variable.
wp_register_script( 'your-script', /*file url here*/ , /*dependencies here*/, false, false);
$params = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce('name-the-nonce'),
);
wp_localize_script( 'your-script', 'jsParameters', $params );
wp_enqueue_script( 'your-script' );
In your javascript you pass the nonce to the php like so:
var ajaxRequest = $.post(
jsParameters.ajaxurl,
{
action: 'your_action',
// send the nonce along with the request
nonce: jsParameters.nonce
},
function (response) {
//some reponse code
}
);
Within the AJAX php function you perform this validation:
$nonce = $_POST['nonce'];
if (!wp_verify_nonce($nonce, 'name-the-nonce'))
die('Busted');
//continue executing ajax php code
Some external material on the matter:
https://codex.wordpress.org/WordPress_Nonces
http://www.barrykooij.com/check-nonces-wordpress-ajax-calls/