In item-post:
<section class="s1">
<h2><?php _e('Category', 'epsilon'); ?> <i class="show-tip fas fa-question-circle"></i></h2>
<div class="in">
<!-- Keyword input field -->
<div class="row" id="keywordRow">
<label for="sKeyword"><?php _e('Find category or select from field', 'epsilon'); ?> <span class="req">*</span></label>
<input type="text" name="sKeyword" id="sKeyword" placeholder="<?php echo osc_esc_html(__('what do you offer?', 'epsilon')); ?>" />
</div>
<!-- Add a separate div for the button -->
<div class="row rowitempost" id="searchButtonRow">
<button id="searchCategories" class="btn" type="button"><?php _e('Search Categories', 'epsilon'); ?></button>
</div>
<!-- Or choose category yourself radio button -->
<div class="row" id="chooseCategoryRadio">
<label><a href="#" id="chooseYourselfLink" class="category-link"><?php _e('Or select a category yourself', 'epsilon'); ?></a></label>
<input type="radio" name="foundCategory" value="other" style="display: none;"> <!-- Hide the radio button -->
</div>
<!-- Display the found categories below as radio buttons -->
<div id="categoryResults" class="row categories" style="display: none;">
<div class="lead"><?php _e('Found Categories', 'epsilon'); ?></div>
<div id="foundCategories"></div>
</div>
<?php if ($category_type == 1) { ?>
<!-- Category input field -->
<div class="row rowitempost">
<label for="sCategoryTerm" class="auto-width"><?php _e('Category', 'epsilon'); ?></label>
<div class="input-box picker category only-search">
<input name="sCategoryTerm" type="text" class="category-pick" id="sCategoryTerm" placeholder="<?php echo osc_esc_html(__('Start typing category...', 'epsilon')); ?>" value="<?php echo osc_esc_html(osc_item_category()); ?>" autocomplete="off" />
<i class="clean fas fa-times-circle"></i>
<div class="results"></div>
</div>
</div>
<?php } else if ($category_type == 2 || $category_type == '') { ?>
<!-- Multi-select category dropdown -->
<div class="row category multi">
<label for="catId"><?php _e('Select category for your listing', 'epsilon'); ?> <span class="req">*</span></label>
<?php ItemForm::category_multiple_selects(null, $prepare, __('Select a category', 'epsilon')); ?>
</div>
<?php } else if ($category_type == 3) { ?>
<!-- Single-select category dropdown -->
<div class="row category simple">
<label for="catId"><?php _e('Select category for your listing', 'epsilon'); ?> <span class="req">*</span></label>
<?php ItemForm::category_select(null, $prepare, __('Select a category', 'epsilon')); ?>
</div>
<?php } ?>
</div>
<!-- Add a hidden field to store the selected category ID -->
<input type="hidden" name="selectedCategoryId" id="selectedCategoryId" value="">
<div class="tip">
<i class="fas fa-times close-tip"></i>
<p><strong><?php _e('Category selection is important!', 'epsilon'); ?></strong></p>
<p><?php _e('Selecting the correct category for your item is an essential part of the selling process.', 'epsilon'); ?></p>
<p><?php _e('If you select an improper category, potential buyers will not be able to find your item, and it will take much more time to sell it.', 'epsilon'); ?></p>
</div>
<?php echo osc_csrf_token_form(); ?>
<?php osc_run_hook('item_publish_category'); ?>
</section>
<script>
$(document).ready(function(){
// Function to display no category found message and manual category selection
function showNoCategoryFound() {
$('.row.category').show(); // Show the category selection row
$('#categoryResults').html('<div class="lead"><?php _e("No categories found", "epsilon"); ?></div>'); // Display the message for no categories found
$('#categorySelection').html('<p><?php _e("Please select a category", "epsilon"); ?></p>' +
'<select id="manualCategorySelect" name="manualCategorySelect">' +
'<option value="">Select a category</option>' +
'<option value="1">Category 1</option>' +
'<option value="2">Category 2</option>' +
'<option value="3">Category 3</option>' +
'</select>'); // Display the option for manual category selection
}
// Event handler for clicking on the "Or select a category yourself" link
$('#chooseYourselfLink').click(function(event) {
event.preventDefault(); // Prevent default link behavior
showNoCategoryFound(); // Display the manual category selection
});
// AJAX request for submitting the form
$('#itemForm').submit(function(event) {
event.preventDefault(); // Prevent default form behavior
var formData = $(this).serialize(); // Gather form data
// Check if "Choose a category yourself" is selected
var selectedCategoryId = $('input[name="foundCategory"]:checked').val();
if (selectedCategoryId === 'other') {
// Manually selected category, handle it here or ignore
selectedCategoryId = $('#manualCategorySelect').val(); // Get the manually selected category ID
}
// Update the hidden field "catId" with the selected category ID for Osclass
$('input[name="catId"]').val(selectedCategoryId);
// Execute the form submission with AJAX or other logic
$.ajax({
url: '<?php echo osc_ajax_hook_url('submit_form_ajax'); ?>',
type: 'POST',
data: formData, // Send form data, including CSRF token
dataType: 'json',
success: function(response) {
// Process the response as needed
console.log('Form submitted successfully:', response);
},
error: function(xhr, status, error) {
console.error('AJAX Error: ' + error);
console.error('Status: ' + status);
console.error('Response: ' + xhr.responseText);
}
});
});
// Event handler for searching categories
$('#searchCategories').click(function(event) {
event.preventDefault(); // Prevent default button behavior
var keyword = $('#sKeyword').val().trim();
// Check if a keyword is entered
if (keyword !== '') {
$.ajax({
url: '<?php echo osc_ajax_hook_url('suggest_category_ajax'); ?>',
type: 'POST',
data: {
keyword: keyword
},
dataType: 'json',
success: function(response) {
if (response && response.categories && response.categories.length > 0) {
var categoryHTML = '';
$.each(response.categories, function(index, category) {
var categoryName = category.s_name;
if (category.s_name_parent !== null) {
categoryName += ' (' + category.s_name_parent + ')';
}
categoryHTML += '<label><input type="radio" name="foundCategory" value="' + category.pk_i_id + '">' + categoryName + '</label><br>';
});
categoryHTML += '<label><input type="radio" name="foundCategory" value="other"> <?php _e("Or choose a category yourself", "epsilon"); ?></label><br>'; // Add the fourth radio button
$('#foundCategories').html(categoryHTML);
$('#categoryResults').show();
$('#chooseCategoryRadio').hide(); // Hide the "Or choose a category yourself" radio button
} else {
showNoCategoryFound(); // Display no category found message and manual category selection
}
},
error: function(xhr, status, error) {
console.error('AJAX Error: ' + error);
console.error('Status: ' + status);
console.error('Response: ' + xhr.responseText);
}
});
} else {
// Handle empty keyword
alert('<?php _e("Please enter a keyword to search categories.", "epsilon"); ?>');
}
});
// Event handler for the change of radio button
$(document).on('change', 'input[name="foundCategory"]', function() {
var selectedCategoryId = $(this).val();
console.log('Selected category ID:', selectedCategoryId);
// Save the selected category ID in the hidden field
$('#selectedCategoryId').val(selectedCategoryId);
// Update the hidden field "catId" with the selected category ID for Osclass
$('input[name="catId"]').val(selectedCategoryId);
// Check if "Other" is selected and display the selection field accordingly
if (selectedCategoryId === 'other') {
$('.row.category').show();
$('#catId').hide(); // Hide the original category selection element
$('#selectedCategoryId').hide(); // Hide the original selected category ID element
} else {
$('.row.category').hide();
$('#catId').show(); // Show the original category selection element
$('#selectedCategoryId').show(); // Show the original selected category ID element
}
});
// Initially hide the selection field
$('.row.category').hide();
// Prevent form submission on Enter key press
$('#sKeyword').keypress(function(event) {
if (event.keyCode === 13) {
event.preventDefault();
$('#searchCategories').click(); // Simulate click on the search button
}
});
});
</script>
In modelEPS add extra:
public function suggest_category_ajax() {
try {
$keyword = Params::getParam('keyword');
$this->dao->select('c.pk_i_id, c.fk_i_parent_id, cd.s_name, cd.s_description, p.s_name as s_name_parent');
$this->dao->from($this->getTable_category() . ' as c');
$this->dao->join($this->getTable_category_description() . ' as cd', 'c.pk_i_id = cd.fk_i_category_id', 'INNER');
$this->dao->join($this->getTable_item() . ' as i', 'c.pk_i_id = i.fk_i_category_id', 'INNER');
$this->dao->join($this->getTable_item_description() . ' as id', 'i.pk_i_id = id.fk_i_item_id', 'INNER');
$this->dao->join($this->getTable_category_description() . ' as p', 'c.fk_i_parent_id = p.fk_i_category_id', 'LEFT OUTER');
$this->dao->where('c.b_enabled', 1);
$this->dao->where('c.fk_i_parent_id', 0); // Only top-level categories
// Check for keyword in category description
if($keyword != '') {
$this->dao->where(sprintf('cd.s_description like "%%%s%%"', mysqli_real_escape_string($this->dao->connId, $keyword)));
}
// Add search based on item title and description to the query
if($keyword != '') {
$this->dao->orWhere('id.s_description like "%%%s%%" OR id.fk_i_category_id = c.pk_i_id', mysqli_real_escape_string($this->dao->connId, $keyword));
}
$result = $this->dao->get();
if($result) {
$categories = $result->result();
$output = array();
$output['categories'] = $categories;
header('Content-Type: application/json');
echo json_encode($output);
exit;
} else {
// No results found
echo json_encode(array('error' => 'No categories found.'));
exit;
}
} catch(Exception $e) {
// Error handling
echo json_encode(array('error' => $e->getMessage()));
exit;
}
}
functions.php:
// Function to fetch categories and return as JSON
function suggest_category_ajax() {
ob_clean(); // Clear any previous output
$keyword = Params::getParam('keyword');
$limit = 3;
$modelEPS = new ModelEPS();
$categories = $modelEPS->findCategories($keyword, $limit, true); // Fetch only top-level categories
$output = array();
$output['categories'] = $categories; // Send back the found categories
header('Content-Type: application/json');
echo json_encode($output);
exit;
}
osc_add_hook('ajax_suggest_category_ajax', 'suggest_category_ajax');
// Function to process and submit the form to the database
function submit_form_ajax() {
ob_clean(); // Clear any previous output
// Receive data sent via AJAX
$formData = array(
'catId' => Params::getParam('selectedCategoryId'), // Get the selected category ID and send it as catId
// Add other form data as needed
);
// Set header for JSON content type
header('Content-Type: application/json');
// Perform logic here to send data to the database
// Send a response back to the client (e.g., success or error message)
$response = array(
'success' => true, // For example: a successful response
'error' => ''
);
// Send JSON response back to the client
echo json_encode($response);
// Stop script execution
exit;
}
// Add AJAX hook to invoke the 'submit_form_ajax' function when the form is submitted via AJAX
osc_add_hook('ajax_submit_form_ajax', 'submit_form_ajax');
And last one is add to style.css:
/* DIV for item-post */
.rowitempost { margin-top: 10px; margin-bottom: 10px; }
.category-link { color: #000; text-decoration: underline; }