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
Related
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') );
I want to make custom search page where I can filter results as shown in the screenshot below:
Currently my problem is that all the items of the list are coming in a single category while I want a grouped view according to different categories e.g. "Device Features", "Mobile Phone Operating System", etc. So far I've written below piece of PHP code:
<?php
$listCategories = get_categories();
if(isset($listCategories) && !empty($listCategories)){
?>
<div class="list-section">
<h3 class="list-heading">Topics</h3>
<ul id="post-grid">
<?php
foreach($listCategories as $categories){
$total_post = get_posts(array('post_type'=>'post', 'category'=>$categories->term_id, 'posts_per_page'=>'-1'));
$total_post = count($total_post);
?>
<li>
<div class="checkbox">
<input type="checkbox" id="cat<?php echo $categories->term_id; ?>" data-tax="category" data-name="<?php echo $categories->name; ?>" class="category_check" value="<?php echo $categories->term_id; ?>">
<label class="css-label" for="cat<?php echo $categories->term_id; ?>">
<span class="filter-name"><?php echo $categories->name; ?></span>
<span class="filter-count"><?php echo $total_post; ?></span>
<i class="icon fa fa-check"></i>
</label>
</div>
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
I've created my own custom plugin for searching and filtering the search result.
1. Plugin file (index.php)
<?php
/*
Plugin Name: Search and Filter
Plugin URI: http://wordpress.org
Description: Search and Filter
Author: Naveen
Version: 1.0
*/
class SearchAndFilter{
public function __construct()
{
add_action('wp_enqueue_scripts', array($this, 'AddScript'));
add_action('wp_ajax_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_noprev_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_action('wp_ajax_noprev_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_shortcode('Search', array($this, 'CreateShortcode'));
}
public function AddScript()
{
wp_enqueue_script('saf-app', plugin_dir_url(__FILE__) . '/js/app.js', array('jquery'));
wp_localize_script('saf-app', 'my_ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}
function CreateShortcode($atts)
{
ob_start();
$keyword = $_REQUEST['s'];
?>
<form action="<?php echo home_url('/'); ?>" method="get">
<input type="text" name="s" id="search_keyword" value="<?php echo $keyword; ?>" class="form-control search-input" placeholder="Search..." />
</form>
<div class="search-suggestion"></div>
<?php
$output = ob_get_clean();
return $output;
}
// search autocomplete
function AffordanceSearchData()
{
$args = array('post_type'=>array('post'),'status'=>'publish');
$output = '';
$output = '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">'.get_the_title().'</li>';
endwhile;
endif;
$output .= '<li>See All Result of '.$_POST['keyword'].' </li>';
$output .= '</ul>';
wp_reset_query();
echo $output; die;
}
// filters search data
function AffordanceSearchPageData()
{
$args = array('post_type'=>'post','status'=>'publish');
$output = '';
$output .= '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
if(isset($_POST['page_number']) && !empty($_POST['page_number']) && $_POST['page_number'] != 1){
$args['paged'] = $_POST['page_number'];
}
if(isset($_POST['categories']) && !empty($_POST['categories'])){
$args['cat'] = $_POST['categories'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">
<h3 class="resources-content-heading">'.get_the_title().'</h3>
<p class="resources-content-description">'.get_the_excerpt().'</p>
<div class="resources-action-area">
Read More <i class="fa fa-angle-right" aria-hidden="true"></i>
</div>
</li>';
endwhile;
else :
$output .= "No records";
endif;
wp_reset_query();
$output .= the_posts_pagination();
$output .= '</main>';
echo $output; die;
}
}
new SearchAndFilter();
2. Js File (app.js)
jQuery(document).ready(function ($) {
// on searching keyword
$('#search_keyword').keyup(function () {
var inputvalue = $(this).val();
if (inputvalue != '') {
GetSuggestion(inputvalue);
}
});
// on pagination click
$('.ajaxclick').on('click', "a", function () {
var page_number = $(this).attr('data-page-num');
//console.log(page_number);
var current_page = $('.ajaxclick .current').attr('data-page-num');
var keyword = $('#search_keyword').val();
GetSearchData(keyword, page_number);
});
// on category select
$('.category_check').on('click', function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var blogWrapper = $('.blogWrapper');
var catTagHTML = '<ul>';
blogWrapper.find('input.category_check:checked').each(function () {
catTagHTML += '<li><a class="exclude_cat" href="javascript:void(0)" data-cat-id="' + $(this).attr('value') + '">' + $(this).attr('data-name') + '</a></li>';
});
$('#selected-category-tags').html(catTagHTML);
GetSearchData(keyword, page_number);
});
// on tag click
$('#selected-category-tags').on('click', "a.exclude_cat", function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var catID = $(this).attr('data-cat-id');
$('#cat' + catID).attr('checked', false);
$(this).closest('li').remove();
GetSearchData(keyword, page_number);
});
function GetSuggestion(keyword) {
var formData = {
'action': 'affordance_search_data',
'keyword': keyword
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.search-suggestion').html(data);
}, 1000);
}
});
}
function GetSearchData(keyword, page_number) {
if (page_number == '') {
page_number = 1;
}
var blogWrapper = $('.blogWrapper');
var categories = [];
blogWrapper.find('input.category_check:checked').each(function () {
categories.push($(this).attr('value'));
});
var formData = {
'action': 'affordance_search_page_data',
'page_number': page_number,
'keyword': keyword,
'categories': categories,
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.site-main').html(data);
}, 1000);
}
});
}
});
Here I'm using ajax to achieve this functionality.
I have a problem with ajax search in my codeigniter project.
The search no show data, and after click SEARCH button page freez 1-2 sec. I think the problem is anywhere in getting the information from the database but, also the model is correct.
There is the code:
Model:
var $table = 'users';
function search($options = array(), $status = true, $limit = null, $offset = 0) {
$this->db->select('users.username,types.t_title,media.photo');
$str = '';
if ($options['username'] != '') {
$str .= ' AND users.username =' . $this->db->escape($options['username']);
}
if (!$status) {
$str .= ' AND users.active = 1';
}
$this->db->where('users.username', 'LIKE', '%' . $options['username'] . '%' . $str);
$this->db->group_by('users.id');
$this->db->limit($limit, $offset);
$search = $this->db->get($this->table);
return $search->result();
}
Controller:
public function search($offset = 0) {
$options = $this->Users->array_from_post(array('username'));
if ($this->form_validation->run('search')) {
$count = $this->Property->search($options, $status = FALSE);
$perpage = 10;
if (count($count) > $perpage) {
$config['base_url'] = site_url('welcome/search');
$config['total_rows'] = count($count);
$config['per_page'] = $perpage;
$config['uri_segment'] = 4;
$q = $this->pagination->initialize($config);
$offset = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
} else {
$this->data['pagination'] = '';
$offset = 0;
}
$status = 1;
$this->data['search'] = $this->Users->search($options, $status = FALSE, $perpage, $offset);
$this->load_search('search');
}
}
And View with ajax:
<script type="text/javascript">
$(document).ready(function() {
$("form[name='search']").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: "<?php echo site_url('welcome/welcome/search'); ?>",
type: "POST",
dataType: "text",
data: formData,
async: false,
success: function (msg) {
$(".search_area").html(msg);
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
});
</script>
<form class="form-horizontal" method="post" name="search">
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
<div class="form-group">
<div class="col-md-12">
<input type="text" class="input-text" id="username" name="username" placeholder="Username">
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
<div class="form-group">
<input type="submit" class="search-button" name="search" value="Search">
</div>
</div>
</div>
</form>
<div class="search_area">
</div>
All is connected and load the template, but the only message with No Record Found
And here is search view:
<div class="main-title">
<h1>Search Results</h1>
<div class="border">
<div class="border-inner"></div>
</div>
</div>
<?php if ($search) : ?>
<?php foreach ($search as $sr): ?>
<p>Tralalala <?php echo $sr['title']; ?></p>
<?php endforeach; ?>
<?php else:?>
<div class="notification-box">
<h3><?php echo $this->lang->line('no_record'); ?></h3>
</div>
<?php endif; ?>
I have created one custom form in admin post editor, to send email templates to authors. I'm facing problem during ajax call that isn't redirecting to the page which I need and getting message post updated when selected template and click on send option
<div id="custom-meta-files" class="row">
<div class="col-md-12">
<form>
<div class="form-group">
<label style="" for="reject_email_template">Template Name</label>
<?php
// The Query
$the_query = new WP_Query( array(
'post_type' => 'email-templates',
'posts_per_page' => -1,
));
if ( $the_query->have_posts() ) { ?>
<select style="display: block;width: 100%;margin: 10px 0;" name="_reject_email" class="form-control" id="reject_email_template">
<?php
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<option value="'.get_the_ID().'">' . get_the_title() . '</option>';
} ?>
</select>
<?php
wp_reset_postdata();
} else {
// no posts found
}
?>
</div>
<button type="submit" class="reject-email-btn btn btn-primary" style="border:none; padding: 6px 1rem;color: #fff; background: #0085ba;text-decoration: none;">Send</button>
</form>
<div id="fromPartsTable"></div>
</div>
save posts in custom fields database
add_action('admin_init','event_meta_init');
function event_meta_init(){
foreach (array('post') as $type){
add_meta_box('my_all_meta', 'Reject Email', 'my_meta_setup', $type, 'normal', 'high');
}
add_action('save_post','my_meta_save');}
function my_meta_setup(){
global $post;
// using an underscore, prevents the meta variable
// from showing up in the custom fields section
$meta = get_post_meta($post->ID,'_post',TRUE);
// instead of writing HTML here, lets do an include
include(MY_THEME_FOLDER . '/metafields/events-fields.php');
// create a custom nonce for submit verification later
echo '<input type="hidden" name="my_meta_noncename" value="' . wp_create_nonce(__FILE__) . '" />';
}
function my_meta_save($post_id){
// authentication checks
// make sure data came from our meta box
if (!wp_verify_nonce($_POST['my_meta_noncename'],__FILE__)) return $post_id;
// check user permissions
if ($_POST['post_type'] == 'page'){
if (!current_user_can('edit_page', $post_id)) return $post_id;
}else{
if (!current_user_can('edit_post', $post_id)) return $post_id;
}
$current_data = get_post_meta($post_id, '_post', TRUE);
$new_data = $_POST['_post'];
my_meta_clean($new_data);
if ($current_data){
if (is_null($new_data)) delete_post_meta($post_id,'_post');
else update_post_meta($post_id,'_post',$new_data);
}elseif (!is_null($new_data)){
add_post_meta($post_id,'_post',$new_data,TRUE);
}
return $post_id;
}
function my_meta_clean(&$arr){
if (is_array($arr)) {
foreach ($arr as $i => $v){
if (is_array($arr[$i])){
my_meta_clean($arr[$i]);
if (!count($arr[$i])){
unset($arr[$i]);
}
}else{
if (trim($arr[$i]) == ''){
unset($arr[$i]);
}
}
}
if (!count($arr)){
$arr = NULL;
}
}
}
My ajax script is
jQuery.noConflict();
(function( $ ) {
function rejection_email(){
$.ajax({
url: "/rejection-email/",
data : {eid:$('#reject_email_template').val()},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
},
error: function() {
alert('Error occured');
}
});
}
$('.reject-email-btn').click(function(e) {
rejection_email();
});
})(jQuery);
Hi everyone I tried to serialize a form by his ID using jquery method serialize().
Html code:
<form name="structure_form" id="structure_form" method="post">
<div id="add_sections" class="postbox add_section_box">
<button type="button" class="handlediv button-link" aria-expanded="true"><span class="screen-reader-text">Commuta il pannello: Add section</span><span class="toggle-indicator" aria-hidden="true"></span></button>
<h3 class="handle ui-sortable-handle structure_title"><span>Add Section</span></h3>
<div class="inside">
#CONTENT#
<input type="button" class="button button-primary button-large saveSections" id="save" value="Save">
</div>
</div>
</form>
Js code:
$('.saveSections').on('click', function () {
var serializedForm = $('#structure_form').serialize();
$.post(ajaxurl, {action: 'saveConfiguration', serializedForm: serializedForm}, function (data) {
alert(data);
});
console.log("configuration saved");
});
Php code:
function saveConfiguration() {
print_r($_POST['serializedForm']);
exit;
}
function add_section_meta_box() {
global $post;
if ($post->post_type == "minisites") {
$addSection = file_get_contents(dirname(__FILE__) . '/templates/components/add_section_box.html');
$addSection = str_replace('#CONTENT#', Utils::createSelect(), $addSection);
}
echo Utils::includeScripts();
echo $addSection;
}
This is Utils::createSelect
public static function createSelect() {
$sections = get_posts(array(
'post_type' => 'sections',
'posts_per_page' => 10)
);
$html = '<select id="sections" name="item">';
foreach ($sections as $section) {
$html .= '<option value="' . $section->ID . '">' . $section->post_title . '</option>';
}
$html .= '</select><br><br>';
$html .= '<input type="button" class="button button-primary button-large addSection" id="add" value="Add">';
return $html;
}
the output is empty or undefined.
I think that the problem is the ID's form because if I change $('#structure_form') with $('form') it works fine.
Thanks in advance.
Edit(Update):
I add code in order that it works
Create custom_post_type, box, ecc (Plugin)
<?php
//error_reporting(E_ALL);
//ini_set("display_errors", 'on');
/*
Plugin Name: deaSiteBuilder
Version: 1.0
Description:
Author: Giuseppe Giubaldo
Author URI:
*/
require_once 'utils.php';
require_once __DIR__ . '/../../../vendor/autoload.php';
use Symfony\Component\Yaml\Parser;
add_action('init', 'create_post_type');
function create_post_type() {
register_post_type('minisites', array(
'labels' => array(
'name' => __('Minisites'),
'singular_name' => __('Minisite'),
),
'public' => true,
'has_archive' => true,
)
);
register_post_type('sections', array(
'labels' => array(
'name' => __('Sections'),
'singular_name' => __('Section'),
),
'public' => true,
'has_archive' => true,
));
}
//Add default meta box
add_action('edit_form_after_editor', 'add_section_meta_box');
function add_section_meta_box() {
global $post;
if ($post->post_type == "minisites") {
$addSection = file_get_contents(dirname(__FILE__) . '/templates/components/add_section_box.html');
$addSection = str_replace('#CONTENT#', Utils::createSelect(), $addSection);
}
echo Utils::includeScripts();
echo $addSection;
}
//Our custom meta box will be loaded on ajax
function add_structure_meta_box($post_name) {
$sectionStructureBox = file_get_contents(dirname(__FILE__) . '/templates/components/sectionStructureBox.html');
$sectionStructureBox = str_replace('#ELEMENT#', strtoupper($post_name), $sectionStructureBox);
$sectionStructureBox = str_replace('#CONTENT#', $post_name, $sectionStructureBox);
echo $sectionStructureBox;
}
//Call ajax
add_action('wp_ajax_addStructureBox', 'addStructureBox');
function addStructureBox() {
add_structure_meta_box($_POST['section']);
exit;
}
add_action('wp_ajax_saveConfiguration', 'saveConfiguration');
function saveConfiguration() {
echo $_POST['serializedForm'];
exit;
}
Html pages:
sections_box
<form name="structure_form" id="structure_form" method="post">
<div id="add_sections" class="postbox add_section_box">
<button type="button" class="handlediv button-link" aria-expanded="true"><span class="screen-reader-text">Commuta il pannello: Add section</span><span class="toggle-indicator" aria-hidden="true"></span></button>
<h3 class="handle ui-sortable-handle structure_title"><span>Add Section</span></h3>
<div class="inside">
#CONTENT#
<input type="button" class="button button-primary button-large saveSections" id="save" value="Save">
</div>
</div>
</form>
structure_box
<div id="section_structure_box" class="postbox section_box">
<button type="button" class="handlediv button-link" aria-expanded="true"><span class="screen-reader-text">Commuta il pannello: Section Structure</span><span class="toggle-indicator" aria-hidden="true"></span></button>
<!-- <div class="handlediv" title="Click to toggle"><br>
</div>-->
<h3 class="handle ui-sortable-handle structure_title"><span>Section Structure - #ELEMENT#</span></h3>
<div class="inside">
#CONTENT#
</div>
<!--<input type="button" class="button button-primary button-large remove_box" id="remove" value="Remove">-->
Class Utils:
<?php
class Utils {
public static function createSelect() {
$sections = get_posts(array(
'post_type' => 'sections',
'posts_per_page' => 10)
);
$html = '<select id="sections" name="item">';
foreach ($sections as $section) {
$html .= '<option value="' . $section->ID . '">' . $section->post_title . '</option>';
}
$html .= '</select><br><br>';
$html .= '<input type="button" class="button button-primary button-large addSection" id="add" value="Add">';
return $html;
}
public static function includeScripts() {
$html = '<link rel="stylesheet" type="text/css" href="' . plugins_url('deaSiteBuilder/assets/css/style.css', dirname(__FILE__)) . '">';
$html .= '<script src="' . plugins_url('deaSiteBuilder/assets/js/jquery.min.js', dirname(__FILE__)) . '"></script>';
$html .= '<script src="' . plugins_url('deaSiteBuilder/assets/js/jquery-ui.js', dirname(__FILE__)) . '"></script>';
$html .= '<script src="' . plugins_url('deaSiteBuilder/assets/js/plugin.js', dirname(__FILE__)) . '"></script>';
return $html;
}
}
And js code:
$(document).ready(function () {
$('.addSection').on('click', function () {
var selectedSection = $('#sections option:selected').text();
$.post(ajaxurl, {action: 'addStructureBox', section: selectedSection}, function (data) {
$('#add_sections').parent().append(data);
console.log("section added");
});
});
$('.saveSections').on('click', function () {
var serializedForm = $('body form#structure_form').serialize();
alert(serializedForm);
$.post(ajaxurl, {action: 'saveConfiguration', serializedForm: serializedForm}, function (data) {
});
console.log("configuration saved");
});
});
try this one,
$('.saveSections').on('click', function () {
var serializedForm = $('#structure_form').serialize();
serializedForm.push({name: 'action', value: 'saveConfiguration'});
$.post(ajaxurl, serializedForm, function (data) {
alert(data);
});
console.log("configuration saved");
});