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;
});
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;
If you can use arrays, you can try something like this.
Note, its better to have a dataStructure, an object or an array. Object will not have order, so either you will have to use map or if you are on ES6, use set
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)
Related
I have these columns on my table:
CardNumber
DateRegister
TimeRegister
DateExit
TimeExit
I read a value that is in a box, and when I press enter, the
Cardnumber, DateRegister,TimeRegister is add to the SQL Database
So I'll have like
CardNumber|DateRegister|TimeRegister|DateExit|TimeExit
124455|23-10-2022|11:00|null|null|
My Issue is, If I read the same card again, before I need to see if there is already one entrance on database with that card number, that don't have still DateExit and TimeExit.
If dont, I need to update that line, with that information, of if is a new one, will add a new entrance on the database
This is my code:
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
/*es.IdCartao = $("#readONchange").val();*/
/*es.DateRegister = param2;*/
//Le cartao / Le data / Le Hora
es.IdCartao = $("#readONchange").val();
es.DateRegister = param2;
es.TimeRegister = param3;
if (es.IdCartao != null)
{
} else if (es.IdCartao == null) {
empregados.IdCartao = es.IdCartao(id);
(es.IdCartao == $("#readONchange").val && es.DateRegister != null && es.TimeRegister != null)
es.TimeExit = param3;
alert(es.IdCartao == $("#readONchange").val);
} else {
alert("erro")
}
alert("Register ADD!")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Data Insert with Sucess");
},
error: function () {
alert("ERROR! on the regist");
}
});
});
});
</script>
I've a script using navigator's local storage valuesand i've developped a web service that sends me the values, the only issue here is that i dont need it to send me Null results, this is the Function:
function SendNeedHelpLinkTrace() {
var pLinkVirement = sessionStorage.getItem("pClickVirement");
var pLinkCarteBancaire = sessionStorage.getItem("pLinkCarteBancaire");
var pLinkRechargePaiementFactureTelecom = sessionStorage.getItem("pLinkRechargePaiementFactureTelecom");
var pPaiementVignetteImpotTaxe = sessionStorage.getItem("PaiementVignetteImpotTaxe");
var pLinkPaiementFactureEauElectricite = sessionStorage.getItem("pPaiementFactureEauElectricite");
var pLinkServiceFatourati = sessionStorage.getItem("pCatchLinkServiceFatourati");
var pLinkCihExpress = sessionStorage.getItem("pCatchLinkCihExpress");
var pLinkEdocuments = sessionStorage.getItem("pCatchLinkEdocuments");
var lChannelId = "01";
var lServiceId = "900120";
var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;
alert(lClientId);
var lData;
var lCollect;
console.log(lClientId);
lData = pLinkVirement + " | " + pLinkCarteBancaire + " | " + pLinkRechargePaiementFactureTelecom + " | " + pPaiementVignetteImpotTaxe + " | " + pLinkPaiementFactureEauElectricite + " | " + pLinkServiceFatourati + " | " + pLinkCihExpress + " | " + pLinkEdocuments;
console.log(lData);
alert(lData);
lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;
console.log(lDataCollected);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:9097/CatchEvent.asmx/CollectData",
data: JSON.stringify({ "pData": lDataCollected }),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
alert('success');
}
},
error: function (exception) {
alert('Exeption : ' + exception);
}
});
sessionStorage.clear();
}
the results are like this :
Null || 300123 || 900452 || Null || Null || 26332
what should i do to not show the Null results ?
Given that lDataCollected is an string you can convert it to an array using split() and easily make a filter() excluding the 'Null' values from the array and finally join() to make an string again:
var lDataCollected = 'Null || 300123 || 900452 || Null || Null || 26332';
var result = lDataCollected
.split(' || ')
.filter(function(item) {
return item !== 'Null';
})
.join(' || ');
console.log(result);
Than, the final solution:
function SendNeedHelpLinkTrace() {
var pLinkVirement = sessionStorage.getItem('pClickVirement'),
pLinkCarteBancaire = sessionStorage.getItem('pLinkCarteBancaire'),
pLinkRechargePaiementFactureTelecom = sessionStorage.getItem('pLinkRechargePaiementFactureTelecom'),
pPaiementVignetteImpotTaxe = sessionStorage.getItem('PaiementVignetteImpotTaxe'),
pLinkPaiementFactureEauElectricite = sessionStorage.getItem('pPaiementFactureEauElectricite'),
pLinkServiceFatourati = sessionStorage.getItem('pCatchLinkServiceFatourati'),
pLinkCihExpress = sessionStorage.getItem('pCatchLinkCihExpress'),
pLinkEdocuments = sessionStorage.getItem('pCatchLinkEdocuments'),
lChannelId = '01',
lServiceId = '900120',
lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value,
lData = pLinkVirement + ' | ' + pLinkCarteBancaire + ' | ' + pLinkRechargePaiementFactureTelecom + ' | ' + pPaiementVignetteImpotTaxe + ' | ' + pLinkPaiementFactureEauElectricite + ' | ' + pLinkServiceFatourati + ' | ' + pLinkCihExpress + ' | ' + pLinkEdocuments,
lDataCollectedString = lClientId + ';' + lChannelId + ';' + lServiceId + ';' + lData,
getLDataCollected = function(str) {
var str
.split(' || ')
.filter(function(item) {
return item !== 'Null';
})
.join(' || ');
};
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://localhost:9097/CatchEvent.asmx/CollectData',
data: JSON.stringify({
'pData': getLDataCollected(lDataCollectedString)
}),
dataType: 'json',
async: true,
success: function(data, textStatus) {
if (textStatus === 'success') {
alert('success');
}
},
error: function(exception) {
alert('Exeption:' + exception);
}
});
sessionStorage.clear();
}
As commented by #hindmost, you should create an array of keys that you need to send and loop through them.
But my personal recommendation, send object instead. This way you will know what is empty and what is not.
Sample Code
// map of keys to fetch
var keysToSend = [
'pClickVirement'
'pLinkCarteBancaire'
'pLinkRechargePaiementFactureTelecom'
'PaiementVignetteImpotTaxe'
'pPaiementFactureEauElectricite'
'pCatchLinkServiceFatourati'
'pCatchLinkCihExpress'
'pCatchLinkEdocuments'
]
// Loop to concatinate
var data = keysToSend.reduce(function(p,c){
var _t = sessionStorage.getItem(c);
return isEmpty(_t) ? p : p + ' | ' + _t;
}, '')
// Check validity
function isEmpty(val){
return val === undefined || val === null;
}
Do an OR check
Assuming lData = pLinkVirement + " | " + pLinkCarteBancaire + " | " + pLinkRechargePaiementFactureTelecom produces Null || 300123 || 900452
Since you're getting the data from sessionStorage, the data will be stored as String, hence do a JSON.parse and do the following
NOTE:(incase the string is Null , then do String.toLowerCase() before JSON.parse())
lData = (pLinkVirement || '') + " | " + (pLinkCarteBancaire || '') + " | " + (pLinkRechargePaiementFactureTelecom || '')
Say you got the data pLinkVirement from sessionStorage as Null, do the following
pLinkVirement = pLinkVirement.toLowerCase()
pLinkVirement = JSON.parse(pLinkVirement)
pLinkVirement = (pLinkVirement || '')
I have this code in a js file which I am including in Default page to Create cookies at the clients' browser and using it in the Thankyou page to invoke my web service to track payment transactions.
// Read a page's GET URL variables and return them as an associative array.
$(document).ready(function () {
$.extend({
getUrlVars: function () {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function (name) {
return $.getUrlVars()[name];
},
getCookie: function (name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else {
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return unescape(dc.substring(begin + prefix.length, end));
}
});
{
var cookieStart, cookieEnd, cookieValue, UserGuid, productId, AffiliationURL, PricePerUnit, commissionAmount;
// Get object of URL parameters
if ($.getUrlVars() != null) {
var allVars = $.getUrlVars();
}
// Getting URL var by its name
//Now check if the user is from Seek Site??
//If this is not null that means the user is Refered from Seek Site
if ($.getUrlVar('clientId') != null) {
UserGuid = $.getUrlVar('clientId');
if ($.getUrlVar('productId') != null) {
productId = $.getUrlVar('productId');
}
if ($.getUrlVar('AffiliationURL') != null) {
AffiliationURL = $.getUrlVar('AffiliationURL');
}
if ($.getUrlVar('PricePerUnit') != null) {
PricePerUnit = $.getUrlVar('PricePerUnit');
}
if ($.getUrlVar('commissionAmount') != null) {
commissionAmount = $.getUrlVar('commissionAmount');
}
//Now Create the cookie for the user
var myCookie = $.getCookie("ReferedCookie");
alert(myCookie);
if (myCookie != null) {
// cookie exists
cookieStart = myCookie.indexOf("clientId=");
//alert(cookieStart = cookieStart + "ReferedCookie=".length);
cookieEnd = myCookie.indexOf(";", cookieStart);
//if there is no occurence of the semicolon character
//cookieEnd takes the length of the document.cookie property
if (cookieEnd == -1) cookieEnd = myCookie.length;
cookieValue = myCookie.substring(cookieStart, cookieEnd);
// check the Product Id
if (cookieValue.indexOf(productId + "&", "productId=") != -1) {
// that means the User clicked on the same Product again and there is already a cookie Exists for that product
alert("User clicked on the same Product again");
}
else {
// The Product Id is different ,We are going to add that product value as string to the cookie
}
}
else {
// Create Cookie
var expiryDate = new Date();
expiryDate.setTime(expiryDate.setDate(expiryDate.getDate() + 365)); // 365 days
document.cookie = "ReferedCookie=" + "clientId=" + UserGuid + "&productId=" + productId + "&AffiliationURL=" + AffiliationURL + "&PricePerUnit=" + PricePerUnit + "&commissionAmount=" + commissionAmount + ";" + "expires=" + expiryDate.toGMTString() + ";";
}
}
}});
And Here the Code which I want to run at Thankyou page but it runs in IE9 (at time I dnt know why???)
{
var cookieStart, cookieEnd, cookieValue, UserGuid, productId, AffiliationURL, PricePerUnit, commissionAmount;
$(window).load(function (e) {
e.preventDefault();
$.extend({
readCookie: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
});
var x = new Array(3);
cookieValue = $.readCookie("ReferedCookie");
var s = 0;
var pos = cookieValue.indexOf("&");
while (pos > -1) {
x[s] = pos;
pos = cookieValue.indexOf("&", pos + 1);
// alert(x[s]);
s++;
}
var c1 = cookieValue.indexOf("clientId=");
alert(UserGuid = cookieValue.substring(c1 + 9, x[0]));
var p1 = cookieValue.indexOf("productId=");
alert(productId = cookieValue.substring(p1 + 10, x[1]));
var A1 = cookieValue.indexOf("AffiliationURL=");
alert(AffiliationURL = cookieValue.substring(A1 + 15, x[2]));
var pp1 = cookieValue.indexOf("PricePerUnit=");
alert(PricePerUnit = cookieValue.substring(pp1 + 13, x[3]));
var com1 = cookieValue.indexOf("commissionAmount=");
alert(commissionAmount = cookieValue.substring(com1 + 17));
var ServiceURL = 'http://localhost:12445/Service/TrackPayment.asmx/InsertCommissionRecord';
// var d = '{"ProductID": "' + productId + '" , "AffiliationURL": "' + AffiliationURL + '" , "Quantitiy": "' + 15 + '" , "PricePerUnit": "' + PricePerUnit + '" , "commissionAmount": "' + commissionAmount + '"}';
var d = '{"ProductID":"1","AffiliationURL":"1","Quantitiy":"1","PricePerUnit":"1","commissionAmount":"1"}';
alert(d);
$.ajax({
type: 'POST',
data: d,
url: ServiceURL,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
alert(data);
alert(textStatus);
alert(XMLHttpRequest);
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
});}
In firebug console it show data.d is null
Kindly help me out and please point out where I am going wrong.
Thanks
JS:
$.ajax({
type: 'POST',
data: {'d': d},
url: ServiceURL,
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
alert(data.ProductID); // returns '1'
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
test.php:
$data = json_decode($_POST['d']);
echo json_encode($data);
I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define the search type that they want and when a search is made, a URL is created which is something like #type/query/.
Currently, the search box is selected on page load with the $('#query').focus(); function however I want it to be deselected when the page is reloaded and there is text in #query. How can I go about doing this? I hope you can understand my question.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#query').focus();
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0, full.indexOf("/"));
$('#type_' + queryType).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
});
Remove $('#query').focus(); from where it is now, and add it in with an else like this:
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}else {
$('#query').focus();
}
I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. I need to somehow define the query terms in my window.location.hash.replace so I am just left with the search type from the URL. How can I go about changing the QUERYGOESHERE in my example below to the query the user has made? I hope people can understand my question.
My jQuery Script is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
if (window.location.hash != "") {
url = window.location.hash.replace('#', '').replace('/QUERYGOESHERE/', '');
$('#type_' + url).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
This should do it.
var full = window.location.hash.replace('#', '')
var queryType = full.substring(0,full.indexOf("/"))
var query = full.replace(queryType, '');
EDIT: Updated code
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0,full.indexOf("/"));
console.log('#type_' + queryType);
$('#type_' + queryType).click();
}