Adrian Adrian - 2 months ago 4
Javascript Question

How to replace an empty variable of searchPhrase?

I have a problem. I have features to sort, filter and search and when textarea of searchPhrase is null I have a problem:

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


And I can't use sort and filter when searchPhrase is null.
How I can fix it?

This is my code:

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 write in searchPhrase somethink e.g "hello" I have such an outcome:

"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

You could check if searchPhrase is not null by adding a ternary

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

and only add the / (and searchPhrase) if it holds a value:

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