Optional parameters in Sammy.js

Utilizing ajax for paging has led me to choose Sammy.js, which works well. However, incorporating checkboxes to filter results poses a challenge. While defining a route for Sammy to intercept is feasible, the issue arises when I wish to avoid displaying certain filters (parameters) in the URL if they are not checked. Unfortunately, Sammy does not offer support for optional parameters.

    var samm = $.sammy(function () {

        this.defaultCheckFormSubmission = this._checkFormSubmission;
        this._checkFormSubmission = function (form) {
            var $form, path, verb;
            $form = $(form);
            path = $form.attr("action");
            verb = this._getFormVerb($form);
            var index = path.indexOf("#");
            if (verb === "get" && path.indexOf("#") == -1) {
                return true;
            }
            else {
                return this.defaultCheckFormSubmission(form);
            }
        };
        this.get('#/Page=:page', function (context) {

            alert("sammy");
        });
    });
    samm.run('#');

I'm looking to prevent my URLs from appearing as www.something.com#/Page=5%Filter1=0?Filter2=0?Filter3=0?Filter4=1...........

Answer №1

To avoid Sammy handling extra filters, such as unchecked checkbox values, simply exclude them from your route. Instead, retrieve parameters from controls using jQuery and make the ajax request accordingly. For example:

this.get('#/Page=:page', function (context) {
        var page = this.params['page'];
        var filter1 = $("#chkFilter1").is(':checked');
        var filter2 = $("#chkFilter2").is(':checked');
        var filter3 = $("#chkFilter3").is(':checked');
        //etc..
        //perform necessary actions here
    });

If you require a different URL structure for deep linking or Google tracking, and are aware of the maximum number of variables needed, plan out your routes accordingly. Arrange the most variables first to prevent incorrect URL matching by Sammy. Here's an example demonstrating how to display only checked values in the URL while still accessing unchecked values via jQuery:

   this.get('#/Page=:page%filter1=:filter1?filter2=:filter2?filter3=:filter3', function (context) {
        var page = this.params['page'];
        var filter1 = this.params['filter1'];
        var filter2 = this.params['filter2'];
        var filter3 = this.params['filter3'];
    });
    this.get('#/Page=:page%filter1=:filter1?filter2=:filter', function (context) {
        var page = this.params['page'];
        var filter1 = this.params['filter1'];
        var filter2 = this.params['filter2'];
        var filter3 = $("#chkFilter1").is(':checked');
    });
    this.get('#/Page=:page%filter1=:filter1', function (context) {
        var page = this.params['page'];
        var filter1 = this.params['filter1'];
        var filter2 = $("#chkFilter1").is(':checked');
        var filter3 = $("#chkFilter2").is(':checked');
    });

Alternatively, consider abandoning querystring variables and opting for a URL structure like www.something.com#/5/0/1/0/1. This would be implemented as follows:

   this.get('#/:page/:filter1/:filter2/:filter3/:filter4', function (context) {
        var page = this.params['page'];
        var filter1 = this.params['filter1'];
        var filter2 = this.params['filter2'];
        var filter3 = this.params['filter3'];
        var filter4 = this.params['filter4'];
    });   

If dealing with unknown potential variables, a more dynamic approach is required, as detailed in this sammyjs optional parameters explanation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The bidirectional data binding feature is malfunctioning following an XMLHttpRequest request

When watching a property from Vuex, I use the following approach: computed: { ticket() { return this.$store.getters['order/reservation'].offer_id } }, watch: { ticket(newTicketId) { console.log('Caught change of ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Sending data from TextBox as json format

JavaScript Code: var latitude = document.getElementById("<%=txt_Lat.ClientID %>").value; var longitude = document.getElementById("<%=txt_Long.ClientID %>").value; var jsonData = {latitude: latitude, longitude: longitude}; var jsonString = JSO ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

A step-by-step guide to implementing lodash once in Vuejs

I am faced with the following input scenario. <input type="text" maxlength="50" v-on:input="query = $event.target.value" v-on:keyup.enter="once(search)" /> Additionally, there are ...

Drupal 7 FlexSlider - alignment issue with image placement

I am encountering an issue with the Flexslider module on my Drupal 7 website. I have created a simple slider that displays 3 photos. I enabled touch screen functionality for the slider, and everything seems to be working fine except for one problem - all t ...

Ways to display a div when a drop-down box is clicked

How can I make a dropdown box that displays 'Yes' and 'No' options? When 'Yes' is selected, how do I show another div on the page? ...

JavaScript can be used to arrange a table in both ascending and descending order by simply clicking on the header

window.addEventListener('DOMContentLoaded', () => { let dir = "dsc"; th = document.getElementsByTagName('th'); for(let c=0; c < th.length; c++){ th[c].addEventListener('click',item(c)); } ...

How to mute a particular warning in development mode with Next.js

Currently in the process of transitioning a CRA app to Next.js in order to enhance SEO. During development, I encountered the following warning: Warning: 'NaN' is an invalid value for the 'left' css style property. I am aware of the s ...

Top method for efficiently inserting multiple rows into a database from an HTML table using AJAX

I need to store data from HTML table rows in a database. Each row contains 20 values, and there are about 200 rows that need to be inserted. I have two possible solutions: A. I can send the data for each row (20 values) through AJAX, repeating this proces ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

Jquery and CSS3 come together in the immersive 3D exhibit chamber

Recently, I stumbled upon an amazing 3D image gallery example created using jQuery and CSS3. http://tympanus.net/codrops/2013/01/15/3d-image-gallery-room/ Excited by the concept, I attempted to incorporate a zoom effect (triggered every time a user clic ...

Safari on iOS 11.4 ignoring the 'touch-action: manipulation' property

I ran into an issue while developing a React web app that I want to work seamlessly across different platforms. My goal was to allow users to interact with a div element by double-clicking on desktop and double-tapping on mobile devices. However, when tes ...

How to disable the onChange event in PrimeNG p-dropdown?

I'm currently utilizing PrimeNG's dropdown component. Each option in the list includes an icon that, when clicked, should trigger a specific method. Additionally, I need to execute another method when the onChange event of the dropdown is trigger ...

JavaScript, XML, and PHP all support the use of HTML entities within their code

Having some trouble as a newbie again))) Can you please help me out, guys? I'm having an XML file with the following data: <Page> <Content>&lt;p&gt;Article content&lt;/p&gt;&#13; &#13; &lt;h1 style="font-style ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

What is the process of matching a server response with the appropriate pending AJAX query?

Imagine a scenario where my web app utilizes AJAX to send out query #1, and then quickly follows up with query #2 before receiving a response from the server. At this point, there are two active event handlers eagerly waiting for replies. Now, let's ...

Encountering issues with the transmission and retrieval of ajax data in Struts 2 framework

Currently, I am attempting to transmit data through ajax and then retrieve the same using ajax. Below is the snippet of my ajax code: $.ajax({ url:"getSampleData", type:'GET', data : {'var':cellValue}, ...

Efficiently sending a cookie with an Axios POST Request

My request is not receiving a cookie even after trying various solutions like withCredentials. I have pasted the most recent code here, can anyone spot what might be missing? var cookie_for_data = "token=test"; var host = "http://localh ...

Angular JS Profile Grid: Discover the power of Angular JS

I came across an interesting example that caught my attention: http://www.bootply.com/fzLrwL73pd This particular example utilizes the randomUser API to generate random user data and images. I would like to create something similar, but with manually ente ...