What is the best method for substituting a null searchPhrase variable?

I'm facing an issue with my code. I have implemented features to sort, filter, and search data. However, when the search textarea is left empty (null), I encounter the following error:

Error: error https://localhost/cases/caselistsorted/no-filter/search_customer//casetype/desc

Furthermore, I am unable to use the sorting and filtering functionalities when the search field is empty. Any suggestions on how to address this?

Here's a snippet of my code for reference:


function sendParam(element) {
    var filterSelect = $("#filterSelect").val();
    var searchOption = $("#searchOption").val();
    var searchPhrase = $("#searchPhrase").val();
    var params1 = $(element).attr("sort");
    var params2 = $(element).attr("order");
    var url = "{{restUrl}}cases/caselistsorted/" + filterSelect 
              + "/" + searchOption + "/"+searchPhrase + "/" 
              + params1 + "/" + params2;
    $.ajax({
        type: 'GET',
        url: url,
        data: null,
        dataType: 'json',
        success: function (data) {
            if (data != null) {
                console.log(url);
                $(".case-list").html(data["code"]);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Error: " + textStatus + " " + url);
        }
    });
}

$(document).on('ready', function(){
    $('.button-sort').on('click', function() {
        sendParam(this);
    });
    $('#filterSelect').change(function () {
        sendParam(this);
    });
});

function customerSearch() {
sendParam(this);
}

function customerSearchTextInput(event) {
if (event.which == 13 || event.keyCode == 13) {
    customerSearch();
    return false;
} else if (event.which == 27 || event.keyCode == 27) {
    customerSearchClear();
    return false;
}
return true;
}

function customerSearchClear() {
var searchPhrase = $("#searchPhrase").val("");
console.log("FieldClear!");
}

When I input "hello" into the search field, I get the following URL:

"https://localhost/cases/caselistsorted/no-filter/search_customer/hello/createDate/asc"

PHP Code :

if ($filter && $searchOption && $searchPhrase && $sortField == "createDate" && $order == "asc") {
            usort($caseList, function ($a, $b) {
                /* @var $a CMCase */
                /* @var $b CMCase */
                $time1 = strtotime($a->createDate);
                $time2 = strtotime($b->createDate);
                return $time1 > $time2;
            });

Answer №1

To ensure that searchPhrase is not null, you can use a ternary operator:

(searchPhrase ? "/" + searchPhrase : "")

Add the / and searchPhrase only if it has a value:

var url = "{{restUrl}}cases/caselistsorted/" + filterSelect 
           + "/" + searchOption + (searchPhrase ? "/" + searchPhrase : "") 
           + "/" + params1 + "/" + params2;

Answer №2

One way to approach this is by utilizing arrays in your code.

It is advisable to have a data structure such as an object or array. Using an object may not maintain order, so you can opt for mapping or utilizing ES6's set feature

var data = [];
/*data.push($("#filterSelect").val());
data.push($("#searchOption").val());
data.push($("#searchPhrase").val());
data.push($(element).attr("sort"));
data.push($(element).attr("order"));*/

data.push("test");
data.push("");
data.push("Hello");
data.push("World");
data.push("");

function isNotEmpty(val){
  return !(
    val === undefined ||
    val === null ||
    val.toString().trim().length === 0
  )
}

var qsString = data.filter(isNotEmpty).join("/");
console.log(qsString)

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

Tips for detecting a change in a Django Autocomplete Light widget with jQuery

Currently, I am incorporating Django Autocomplete Light (DAL) within my application. To perform additional processing in the background upon user selection, I am attempting to detect the .on('change') event (specifically when the DAL select fiel ...

Converting foreign key IDs to corresponding values in Django can be achieved by utilizing the related objects feature

In my Django project, I have defined the following Models in my models.py file: class HadoopDistributor(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Cluster(models.Model): size = mode ...

Encountering a constructor problem while Jest is mocking a class from an NPM module

I'm currently attempting to create a mock for the Discord.JS module. Within this module, there is a Client class that I am extending in my own "Bot" class. My goal is to mock the module in order to simulate certain methods on other classes such as "Me ...

Rendering in React by cycling through an array and displaying the content

I have been working on displaying two arrays. Whenever the button is clicked, a new user is generated and added to the array. My goal is to render the entire array instead of just the newest entries. I've attempted various methods but haven't had ...

Can you identify the date stored in this JSON object?

I need to analyze some JSON data This is the specific snippet required for my query. "UpdatedDate":"\/Date(1311377875937)\/" I'm unsure about that number, but the updated date indicates when the item was last modified Moreover, how can I ...

The Angular routing functionality appears to be malfunctioning

I am currently implementing routing in my project using basic angular route with Angular 1.3.0. Here is the content of my app.js file: 'use strict'; var routerApp = angular.module('mcw', [ 'ngRoute', 'mcw.controll ...

Unable to establish a connection with the TCP server on CloudFoundry, although the localhost node.js is functioning properly

I am experiencing difficulty connecting to my TCP server example that is running on CloudFoundry. Interestingly, when I run my app.js file on a local node.js installation, everything works perfectly. Upon using vmc push to deploy on CloudFoundry, the servi ...

Should we be concerned about the ethics of running javascript that is fetched through an AJAX request?

Currently, I am working on updating an existing web application that allows for user administration and login capabilities. One of the features involves modifying a user's details through a dialog box, where the updated data is then sent to the server ...

There seems to be an issue with the file upload process

I'm attempting to upload an image using the following code: $sourcePath = $_FILES['file']['tmp_name']; $targetPath = "upload/".$_FILES['file']['name']; move_uploaded_file($sourcePath, $targetPath); However, I ...

What is the best way to retrieve recently inserted data using Sequelize in PostgreSql?

Is there a way to retrieve updated table values after adding a user to the "WOD" table without making an additional query? Currently, when I add a third user to my WOD table, I can only return the first two users because I am unable to access the updated ...

PHP Multiple Uploads is a feature that allows users to

I'm currently attempting to utilize the dropzone JS plugin in combination with PHP for the purpose of uploading multiple files and then displaying each file's URL. Here is my progress so far: $upload_dir = 'files'; for($i=0; $i&l ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

Generating rows within Angular while implementing ng-repeat

In my code, I am facing an issue where posts from the API are being repeated and displayed in rows of 9. My objective is to create a grid layout with 3 rows, each containing 3 posts. Unfortunately, the solution I attempted did not work as expected. I also ...

Updating a nested object element inside an array in Vuex state with Vue.js does not reflect the changes in the component's DOM

Vuex/store : import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { todos: [ {id: 1, text: 'Wash dishes', done: false}, {id: 2, text: ' ...

What is the best approach to managing a Symfony form that contains TWO CollectionType child forms?

I have been referring to the Symfony guide here which explains how to generate and save a collection of associated entities within a form. Following the example provided in the guide, I have successfully implemented the functionality for adding and removi ...

Retrieve live data from a Python script using jQuery and PHP for immediate usage

How can I show the current temperature on a webpage? My setup involves using a Raspberry Pi 3 with the Jessie OS and Chromium as the browser. To achieve this, I have placed a Python script inside a loop for a countdown timer. The script is triggered ever ...

Is Immutable state considered a key functional aspect in the ReactJs framework?

One key aspect of an imperative program is the emphasis on state and its modifications. When it comes to ReactJs, there is a push for more functional programming styles, such as using purity and higher-order functions. I'm curious to explore whether ...

The append method is not available for a div element

this is my unique code snippet for (i = 0 ; i< number ; i++){ var iDiv = document.createElement('div'); iDiv.innerHTML = "<label for=\"timeslot\" class=\"p-label-required\">Time Slot</label>" iDiv.i ...

Creating a responsive modal in React.js: A step-by-step guide

Currently, I am working on a straightforward modal in React and am in the process of making it responsive. My goal is to have the modal display with fixed height and width on desktop, with the background unscrollable while the modal itself is scrollable. O ...