This topic contains a post which is marked as Best Answer. Press here if you would like to see it.
*

mwindey

  • *****
  • 484 posts
Use keyword when placing a new listing
« on: April 02, 2024, 05:21:56 PM »
I am currently working on a possibility to search by keyword when placing a listing and, based on that keyword, to propose a category that is most suitable for the item in question. Using radio buttons, the user can then select a category. select to place the listing or can still use the select boxes as originally offered by osclass. Until then everything works perfectly....
{
    "categories": [
        {
            "pk_i_id": "24",
            "fk_i_parent_id": null,
            "s_name": "Juwelry & Watches",
            "s_name_parent": null
        },
        {
            "pk_i_id": "332",
            "fk_i_parent_id": "97",
            "s_name": "Watches",
            "s_name_parent": "Woman"
        },
        {
            "pk_i_id": "339",
            "fk_i_parent_id": "98",
            "s_name": "Watches",
            "s_name_parent": "Men"
        }
    ]
} I search for a keyword, receive 3 suggested categories. When entering the category watches I receive this data Keyword: watches
new:528 Selected category ID: 332
new:529 Selected category Parent ID: 97
new:535 Category Name: Watches
new:536 Category Parent Name: Women
However, when posting, something goes wrong and I get flashmessage wrong category.... Perhaps more information needs to be provided with the ajax request.

At the moment this is what's posted to DB
// Add the metadata to formData
         var formData = $('#itemForm').serializeArray();
         formData.push({name: 'catId', value: selectedCategoryId});
         formData.push({name: 'categoryName', value: categoryName});
         formData.push({name: 'categoryParentName', value: categoryParentName});
What exactly does osclass need to post an item? pk_i_id, catId?? Anyway this is the scipt:

Code: [Select]
<script>
$(document).ready(function(){
    // AJAX-request voor het verzenden van het formulier
    $('#itemForm').submit(function(event) {
        event.preventDefault(); // Voorkom standaardgedrag van het formulier
        var formData = $(this).serializeArray();
        console.log('Form Data:', formData); // Log de formuliergegevens naar de console

        // Voer het formulier uit met AJAX of andere logica
        // Voeg hier je AJAX-verzoek toe om het formulier te verzenden
        $.ajax({
            url: '<?php echo osc_ajax_hook_url('submit_form_ajax'); ?>',
            type: 'POST',
            data: formData, // Stuur de formuliergegevens door, inclusief het CSRF-token
            dataType: 'json',
            success: function(response) {
                // Verwerk de AJAX-reactie indien nodig
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error: ' + error);
                console.error('Status: ' + status);
                console.error('Response: ' + xhr.responseText);
            }
        });
    });

    // AJAX-request voor het zoeken naar categorieën
    $('#searchCategories').click(function(event) {
        event.preventDefault(); // Voorkom standaardgedrag van de knop
        var keyword = $('#sKeyword').val().trim();
        console.log('Keyword: ' + keyword); // Log keyword in de console
        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) {
                            categoryHTML += '<label><input type="radio" name="foundCategory" data-parentid="' + category.fk_i_parent_id + '" value="' + category.pk_i_id + '" data-s_name="' + category.s_name + '" data-s_name_parent="' + category.s_name_parent + '">' + category.s_name + '</label><br>';
                        });
                        $('#foundCategories').html(categoryHTML);
                        $('#categoryResults').show();
                    } else {
                        $('#foundCategories').html('<p>No categories found.</p>').show();
                    }
                },
                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"); ?>');
        }
    });

    // Debug statement om het ID van de geselecteerde categorie in de console weer te geven
    $(document).on('change', 'input[name="foundCategory"]', function() {
        var selectedCategoryId = $(this).val();
        var selectedCategoryParentId = $(this).data('parentid'); // Extra attribuut voor parent ID

        console.log('Selected category ID:', selectedCategoryId);
        console.log('Selected category Parent ID:', selectedCategoryParentId);

        // Ophalen van de metadata direct van de geselecteerde radioknop
        var categoryName = $(this).attr('data-s_name'); // Haal de naam van de categorie op
        var categoryParentName = $(this).attr('data-s_name_parent'); // Haal de naam van de bovenliggende categorie op

        console.log('Category Name:', categoryName);
        console.log('Category Parent Name:', categoryParentName);

        // Log de metadata naar de console voor debuggen
        console.log('Metadata:', {
            s_name: categoryName,
            s_name_parent: categoryParentName
        });

        // Voeg de metadata toe aan formData
        var formData = $('#itemForm').serializeArray();
        formData.push({name: 'catId', value: selectedCategoryId});
        formData.push({name: 'categoryName', value: categoryName});
        formData.push({name: 'categoryParentName', value: categoryParentName});

        // Voer het formulier uit met AJAX of andere logica
        // Voeg hier je AJAX-verzoek toe om het formulier te verzenden
        $.ajax({
            url: '<?php echo osc_ajax_hook_url('submit_form_ajax'); ?>',
            type: 'POST',
            data: formData, // Stuur de formuliergegevens door, inclusief het CSRF-token en de metadata
            dataType: 'json',
            success: function(response) {
                // Verwerk de AJAX-reactie indien nodig
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error: ' + error);
                console.error('Status: ' + status);
                console.error('Response: ' + xhr.responseText);
            }
        });
    });

});
</script>

*

MB Themes

Re: Use keyword when placing a new listing
« Reply #1 on: April 02, 2024, 06:10:01 PM »
You must set category ID to inout with name catId

Sometimes it can be select box, but usually it is hidden input
  To get fast support, we need following details: Detail description, URL to reproduce problem, Screenshots

*

mwindey

  • *****
  • 484 posts
Re: Use keyword when placing a new listing
« Reply #2 on: April 04, 2024, 06:05:55 PM »
@MB Themes,
Tried but i guess hook is not correct?
Code: [Select]
<script>
$(document).ready(function(){
    $('#itemForm').submit(function(event) {
        event.preventDefault();
        var formData = $(this).serializeArray();
        console.log('Form Data:', formData); // Log form data to console

        $.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 AJAX response if needed
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error: ' + error);
                console.error('Status: ' + status);
                console.error('Response: ' + xhr.responseText);
            }
        });
    });

    // AJAX request for searching categories
    $('#searchCategories').click(function(event) {
        event.preventDefault(); // Prevent default button behavior
        var keyword = $('#sKeyword').val().trim();
        console.log('Keyword: ' + keyword); // Log keyword to console
        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) {
                            categoryHTML += '<label><input type="radio" name="foundCategory" data-parentid="' + category.fk_i_parent_id + '" value="' + category.pk_i_id + '" data-s_name="' + category.s_name + '" data-s_name_parent="' + category.s_name_parent + '">' + category.s_name + '</label><br>';
                        });
                        $('#foundCategories').html(categoryHTML);
                        $('#categoryResults').show();
                    } else {
                        $('#foundCategories').html('<p>No categories found.</p>').show();
                    }
                },
                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"); ?>');
        }
    });

    // Debug statement
    $(document).on('change', 'input[name="foundCategory"]', function() {
        var selectedCategoryId = $(this).val();
        var selectedCategoryParentId = $(this).data('parentid'); // Extra attribute for parent ID

        console.log('Selected category ID:', selectedCategoryId);
        console.log('Selected category Parent ID:', selectedCategoryParentId);

        // Retrieve metadata directly from the selected radio button
        var categoryName = $(this).attr('data-s_name'); // Get category name
        var categoryParentName = $(this).attr('data-s_name_parent'); // Get parent category name

        console.log('Category Name:', categoryName);
        console.log('Category Parent Name:', categoryParentName);

        // Log metadata to console for debugging
        console.log('Metadata:', {
            s_name: categoryName,
            s_name_parent: categoryParentName
        });

        // Set the catId value to the selected category ID
        $('#selectedCategoryId').val(catId);

        var formData = $('#itemForm').serializeArray();
        formData = formData.filter(function(item) {
            return item.name !== 'catId';
        });
        formData.push({name: 'catId', value: catId});

        // Perform form submission with AJAX or other logic
        $.ajax({
            url: '<?php echo osc_ajax_hook_url('submit_form_ajax'); ?>',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                // Process AJAX response if needed
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error: ' + error);
                console.error('Status: ' + status);
                console.error('Response: ' + xhr.responseText);
            }
        });
    });
});
</script>
« Last Edit: April 25, 2024, 09:37:39 AM by mwindey »

Marked as best answer by mwindey on April 05, 2024, 09:42:48 PM
*

MB Themes

Re: Use keyword when placing a new listing
« Reply #3 on: April 05, 2024, 03:15:56 PM »
@mwindey
First you must have hidden input with name="catId" in your form.

Then, below this line:
Code: [Select]
        $('#selectedCategoryId').val(catId);

you may add:
Code: [Select]
        $('input[name="catId"]').val(catId).change();

It will fill category ID for Osclass and trigger change, so category-related hooks are executed.
  To get fast support, we need following details: Detail description, URL to reproduce problem, Screenshots

*

mwindey

  • *****
  • 484 posts
Re: Use keyword when placing a new listing
« Reply #4 on: April 05, 2024, 07:41:51 PM »
it works after 6 days of work!!! Thank you MB Themes :-)  :P :P :P ....For epsilon theme use;
In functions.php
Code: [Select]
// Function to retrieve categories and return them 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); // Retrieve main categories only
   
     $output = array();
     $output['categories'] = $categories; // Return 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 the form and send it to the database
function submit_form_ajax() {
     ob_clean(); // Clear any previous output

     // Receive the 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 the header for the JSON content type
     header('Content-Type: application/json');

     // Execute the logic here to send the 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 the JSON response to the client
     echo json_encode($response);

     // Stop script execution
     exit;
}

// Add the AJAX hook to call the 'submit_form_ajax' function when the form is submitted via AJAX
osc_add_hook('ajax_submit_form_ajax', 'submit_form_ajax');


// HELP FUNCTION TO GET CATEGORIES
function eps_category_loop($parent_id = NULL, $parent_color = NULL) {
   $parent_color = isset($parent_color) ? $parent_color : NULL;

   if(Params::getParam('sCategory') <> '') {
     $id = Params::getParam('sCategory');
   } else if(eps_get_session('sCategory') <> '' && (osc_is_publish_page() || osc_is_edit_page())) {
     $id = eps_get_session('sCategory');
   } else if(osc_item_category_id() <> '') {
     $id = osc_item_category_id();
   } else {
     $catId = '';
   }


   if($parent_id <> '' && $parent_id > 0) {
     $categories = Category::newInstance()->findSubcategoriesEnabled($parent_id);
   } else {
     $parent_id = 0;
     $categories = Category::newInstance()->findRootCategoriesEnabled();
   }

   $html = '<div class="flat-wrap' . ($parent_id == 0 ? 'root' : '') . '" data-parent-id="' . $parent_id . '">';
   $html .= '<div class="single info">' . __('Select category', 'epsilon') . ' ' . ($parent_id <> 0 ? '<span class="back tr1 round2"><i class="fa fa-angle-left"></i> ' . __('Back', 'epsilon') . '< /span>' : '') . '</div>';

   foreach($categories as $c) {
     if($parent_id == 0) {
       $parent_color = eps_get_cat_color($c['pk_i_id'], $c);
       $icon = '<div class="parent-icon" style="background:' . eps_get_cat_color($c['pk_i_id'], $c) . ';">' . eps_get_cat_icon($c['pk_i_id'], $c) . '</div>';
     } else {
       $icon = '<div class="parent-icon children" style="background: ' . $parent_color . '">' . eps_get_cat_icon($c['pk_i_id'], $c) . '</div>';
     }
   
     $html .= '<div class="single tr1' . ($c['pk_i_id'] == $id ? ' selected' : '') . '" data-id="' . $c['pk_i_id' ] . '"><span>' . $icon . $c['s_name'] . '</span></div>';

     $subcategories = Category::newInstance()->findSubcategoriesEnabled($c['pk_i_id']);
     if(isset($subcategories[0])) {
       $html .= eps_category_loop($c['pk_i_id'], $parent_color);
     }
   }
 
   $html .= '</div>';
   return $html;
}


item-post.php:
Code: [Select]
<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">
            <label for="sKeyword"><?php _e('Keyword''epsilon'); ?> <span class="req">*</span></label>
            <input type="text" name="sKeyword" id="sKeyword" placeholder="<?php echo osc_esc_html(__('Start typing category...''epsilon')); ?>" />
        </div>

        <!-- Or choose category yourself radio button -->
        <div class="row" id="chooseCategoryRadio">
            <label><?php _e('Or choose a category yourself''epsilon'); ?></label>
            <input type="radio" name="foundCategory" value="other"> <?php _e("Or choose a category yourself""epsilon"); ?>
        </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 == || $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 ?>

        <!-- Add a separate div for the button -->
        <div class="row rowitempost">
            <button id="searchCategories" class="btn" type="button"><?php _e('Search Categories''epsilon'); ?></button>
        </div>
    </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
        $('#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 message and option for 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>
« Last Edit: April 07, 2024, 04:10:09 PM by mwindey »

*

MB Themes

Re: Use keyword when placing a new listing
« Reply #5 on: April 08, 2024, 01:16:20 PM »
Nice ;)
  To get fast support, we need following details: Detail description, URL to reproduce problem, Screenshots

*

mwindey

  • *****
  • 484 posts
Re: Use keyword when placing a new listing
« Reply #6 on: April 09, 2024, 11:23:08 AM »

In item-post:
Code: [Select]
<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 == || $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:
Code: [Select]
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:

Code: [Select]
// 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:
Code: [Select]
/* DIV for item-post */
.rowitempost { margin-top: 10px; margin-bottom: 10px; }
.category-link { color: #000; text-decoration: underline; }
« Last Edit: April 25, 2024, 09:38:03 AM by mwindey »