LIKE or CONTAINS in SOQL Query - javascript

I'm trying obtain some data from the following URL, using a JavaScript code:
http://data.cityofnewyork.us/resource/erm2-nwe9.json
That's how I construct my query:
//data URL variables
var start_date = '2013-08-01'; //YYYY-MM-DD
var end_date = '2013-08-08'; //YYYY-MM-DD
var c_type = 'Noise'; // Complaint Type
// Build the data URL
var URL = "http://data.cityofnewyork.us/resource/erm2-nwe9.json"; // API Access Endpoint
URL += "?";
URL += "$where=";
URL += "(latitude IS NOT NULL)";
URL += " AND ";
URL += "(complaint_type='" + c_type + "')";
URL += " AND ";
URL += "(created_date>='" + start_date + "') AND (created_date<='" + end_date + "')";
URL += "&$group=complaint_type,descriptor,latitude,longitude";
URL += "&$select=descriptor,latitude,longitude,complaint_type";
URL = encodeURI(URL);
And how I'm testing it so far:
$.getJSON(URL, function(data)
{
console.log(data)
});
Right now it works fine, but I should consider any complaint type that contains a single world ("Noise"):
URL += "(complaint_type LIKE '%" + c_type + "%')";
Encoded URL (seems OK):
http://data.cityofnewyork.us/resource/erm2-nwe9.json?$where=(latitude%20IS%20NOT%20NULL)%20AND%20(complaint_type%20LIKE%20'%25Noise%25')%20AND%20(created_date%3E='2013-08-01')%20AND%20(created_date%3C='2013-08-08')&$group=complaint_type,descriptor,latitude,longitude&$select=descriptor,latitude,longitude,complaint_type
Error:
{
"code" : "query.compiler.malformed",
"error" : true,
"message" : "Error, could not parse SoQL query \"select descriptor,latitude,longitude,complaint_type from #erm2-nwe9 where (latitude IS NOT NULL) AND (complaint_type LIKE '%Noise%') AND (created_date>='2013-08-01') AND (created_date<='2013-08-08') group by complaint_type,descriptor,latitude,longitude\"",
"data" : {
"query" : "select descriptor,latitude,longitude,complaint_type from #erm2-nwe9 where (latitude IS NOT NULL) AND (complaint_type LIKE '%Noise%') AND (created_date>='2013-08-01') AND (created_date<='2013-08-08') group by complaint_type,descriptor,latitude,longitude"
}
}
The documentation seems that it is possible to use LIKE, but I can't get it to work.
I don't know how to do this.

I have just figured out how it works, it seems that it does not accept just percent symbols '%' in the condition, it should be preceded by backslash(or is it just slash, anyway).
So this is the valid URL for using 'like' statement:
http://data.cityofnewyork.us/resource/erm2-nwe9.json?$where=(latitude%20IS%20NOT%20NULL)%20AND%20(complaint_type%20like%20%27\%Noise\%%27)%20AND%20(created_date%3E=%272013-08-01%27)%20AND%20(created_date%3C=%272013-08-08%27)&$group=complaint_type,descriptor,latitude,longitude&$select=descriptor,latitude,longitude,complaint_type
Or appropriate row in your code:
URL += "(complaint_type LIKE '\\%" + c_type + "\\%')";
Let me know if it works, and sorry for not replying on time, I really have no experience with Salesforce and SOQL. But thanks to you there is another new space for me to explore :)

Related

replace segment of a URL with regex

I have a button that takes a value from a checkbox and inserts it dynamically into a URL parameter. the URL looks like this:
example.com/search?q=searchterm&site=site1&page=1
&site=site1 is what is being updated dynamically by the value of a checkbox. My code for that looked like below at first:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = '&site=' + filterSelection + '&page=1';
console.log(filterUrl + " - " + filterSite);
window.location.replace(filterUrl);
});
The problem with the first approach is when you click the button multiple times, it just adds the new parameters to the URL, so it ends up looking like:
example.com/search?q=searchterm&site=site1&page=1&site=site2&page=1&site=site3&page=1
When I only need to change &site=site3&page=1 - I tried using a regex to select that part of the URL and replace it with the new one. My attempt at that is below:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
console.log(filterUrl + " - " + filterSite);
window.location.replace(url, filterUrl);
});
What this block does is remove the search query and just returns
example.com/site=site1&page=1 which gives a 404.
I need to somehow update a segment of a URL, and not the entire thing. I believe I need to do some sort of regex to target it and change it. What are the next steps? How can I update a certain section of a URL?
EDIT: This is where it stands now:
// apply filter, go to page
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
// console.log(filterUrl + " - " + filterSite);
if (window.location.href.indexOf("&site=") > -1) {
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
window.location.replace(filterSite);
console.log(filterSite);
} else {
window.location.replace(filterUrl);
}
});
but the .replace() method doesn't seem to be working.
Correct me if I got it wrong:
You have something like this: example.com/search?q=searchterm&site=site1&page=1 and you need to update ONLY THIS PART: &site=site1.
One way:
filterSite.replace(/&site=site\d+/,'&site=site' + filterSelection);
This works only if the updatable part of the url is ALWAYS going to be of the form &site=site<number>, ie: filterSelection is always a number
anyhow, let me know
REGARDING YOUR EDIT:
Assuming what you mean by The .replace() method won't change the parameter, is that the URL won't change, you are right: when you do this:
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
what you are modifying is the variable filterSite, the page won't automatically reload to the new url, which I think is what you intend after seeing this other line:
window.location.replace(filterSite);
replace it with:
window.open(filterSite);
to make the page go to the new url
More about window.open and its arguments
One last thing, I noticed you are using /&site=\d+/,'&site=' + filterSelection as args for replace which will not match example.com/search?q=searchterm&site=site1&page=1. So, unless you changed the structure of the url, you might want to look on that too.
let me know
URL Constructor
EXAMPLE: 1
;
var uri = new URL( "http://example.com/search?q=searchterm&site=site1&page=1" );
uri.searchParams.has("q");
>> true
uri.searchParams.set( "site", "site2" );
uri.searchParams.set( "page", "2" );
uri.href;
>> "http://example.com/search?q=searchterm&site=site2&page=2"
;
Browser Suport: ( ? )[ Chrome 49, Firefox 44, Opera 36, IE12 ]
I suggest you to use A POST request method and Jquery has already a method to construct that params to send based in the form
https://api.jquery.com/serialize/

Calculating Oath 1.0a signature in Typescript/Javascript

I am trying to implement the signature generation for oauth in Typescript and I had it working, but then I changed something minor (I hardcoded the URI in my method and changed that for a test) and didn't really paid attention and now it is now it is broken for some reason I don't know. I am sitting here for two hours staring at my code but for the love of god, I can't get it to work again.
calculateSignatur(URI: string, nonce: string, timestamp: number): string{
let rawURL: string = "GET&" + encodeURIComponent(URI) + "&";
let parameterString: string = "exact=false" +
"&oauth_consumer_key=" + this.appToken +
"&oauth_nonce=" + nonce +
"&oauth_signature_method=" + this.oauth_signature_method +
"&oauth_timestamp=" + 1511003512399 +
"&oauth_token=" + this.accessToken +
"&oauth_version=" + this.oauth_version +
"&search=Black";
let signingString = rawURL + encodeURIComponent(parameterString);
let signingKey = encodeURIComponent(this.accessToken) + "&" + encodeURIComponent(this.accessTokenSecret);
let signatur: string = CryptoJS.HmacSHA1(signingString, signingKey).toString(CryptoJS.enc.Base64);
console.log("Signatur: " + signatur)
return signatur;
}
I hardcoded the parameter for now as well as the timestamp and the nonce to check the signature against the signature that as generated by postman. If I copy and paste the signature generated by postman into the OAuth header and get authorization. So the error must be in the signature part.
Of course, 5 minutes after posting I saw my mistake. The sginingkey need to be
let signingKey = encodeURIComponent(this.appSecret) + "&" + encodeURIComponent(this.accessTokenSecret);
and not
let signingKey = encodeURIComponent(this.accessToken) + "&" + encodeURIComponent(this.accessTokenSecret);

Cannot pass URL from JavaScript to PHP in Laravel

I'm trying to get three values from a front-end form in JavaScript and then passing those values to the Laravel controller.
I can get two values (Key and Id) but I cannot get the third value because it is a URL. If I comment the URL variable then I'm getting the rest of the two values (Key and Id) but if I'm passing the URL along other two values then I'm not getting anything in my controller.
I have tried these two JavaScript methods encodeURIComponent() and encodeURI() to encode the https URL given but still no luck.
This is my code in JavaScript:
let get_url = $("#get-url").val();
let get_key = $("#get-key").val();
let get_id = $("#get-area").data('getId');
toastr.remove();
if (get_key) {
var req = new Image();
req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
console.log(req.src);
toastr.success(MEASURE.UTILITIES.translate("success_request_successfully_sent"));
$("#btn-send-data-request").hide();
$("#block_get_url").hide();
$("#block_get_key").hide();
$("#csv_get_request_message").show();
} else {
toastr.error(MEASURE.UTILITIES.translate("error_enter_valid_data"));
}
Your get_url contains a url, which i believe has https:// or http://
This is a problem when you are adding to the API URL you are constructing as adding more / changes the ROUTE.
For example your API URL expects req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
which is something like http://www.laravel.com/api/senddata/123/123/urlhere but you are making is something like http://www.laravel.com/api/senddata/123/123/http://urlhere which means you are altering the ROUTE.
To solve that you can URL Encode the URL before passing it.
Change your code to this should work : let get_url = encodeURIComponent($("#get-url").val());
Reference: https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

loading saving and showing json results in javascript

I have a php file called rows2.php that shows results like so after entering new fields in a database. It is simply showing the new id of the field :-
{'new_id':'92'}
I want to load this with javascript and add the new_id to existing list with : either side of the number and display it but I seem to be struggling? Many thanks.
The javascript to load the page and get the result is :
$.getJSON("rows2.php", function(result) {
var new_id=console.log(result[0].new_id);
document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + 'new_id' + ':';
})
You should use
document.getElementById('vehicle_list').innerHTML = ''+document.getElementById('vehicle_list').innerHTML+'new_id'+':';
instead of
document.getElementById('vehicle_list').value = ''+document.getElementById('vehicle_list').value+'new_id'+':';
.value is used only in case of input elements otherwise you must use .innerHTML
Don't put the variable name (new_id) in quotes.
document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + new_id + ':';

Display thumbnailPhoto from Active Directory using Javascript only - Base64 encoding issue

Here's what I'm trying to do:
From an html page using only Javascript I'm trying to query the Active Directory and retrieve some user's attributes.
Which I succeded to do (thanks to some helpful code found around that I just cleaned up a bit).
I can for example display on my html page the "displayName" of the user I provided the "samAccountName" in my code, which is great.
But I also wanted to display the "thumbnailPhoto" and here I'm getting some issues...
I know that the AD provide the "thumbnailPhoto" as a byte array and that I should be able to display it in a tag as follow:
<img src="data:image/jpeg;base64," />
including base64 encoded byte array at the end of the src attribute.
But I cannot manage to encode it at all.
I tried to use the following library for base64 encoding:
https://github.com/beatgammit/base64-js
But was unsuccesful, it's acting like nothing is returned for that AD attribute, but the photo is really there I can see it over Outlook or Lync.
Also when I directly put that returned value in the console I can see some weird charaters so I guess there's something but not sure how it should be handled.
Tried a typeof to find out what the variable type is but it's returning "undefined".
I'm adding here the code I use:
var ADConnection = new ActiveXObject( "ADODB.connection" );
var ADCommand = new ActiveXObject( "ADODB.Command" );
ADConnection.Open( "Data Source=Active Directory Provider;Provider=ADsDSOObject" );
ADCommand.ActiveConnection = ADConnection;
var ou = "DC=XX,DC=XXXX,DC=XXX";
var where = "objectCategory = 'user' AND objectClass='user' AND samaccountname='XXXXXXXX'";
var orderby = "samaccountname ASC";
var fields = "displayName,thumbnailPhoto";
var queryType = fields.match( /,(memberof|member),/ig ) ? "LDAP" : "GC";
var path = queryType + "://" + ou;
ADCommand.CommandText = "select '" + fields + "' from '" + path + "' WHERE " + where + " ORDER BY " + orderby;
var recordSet = ADCommand.Execute;
fields = fields.split( "," );
var data = [];
while(!recordSet.EOF)
{
var rowResult = { "length" : fields.length };
var i = fields.length;
while(i--)
{
var fieldName = fields[i];
if(fieldName == "directReports" && recordSet.Fields(fieldName).value != null)
{
rowResult[fieldName] = true;
}
else
{
rowResult[fieldName] = recordSet.Fields(fieldName).value;
}
}
data.push(rowResult);
recordSet.MoveNext;
}
recordSet.Close();
console.log(rowResult["displayName"]);
console.log(rowResult["thumbnailPhoto"]);
(I replaced db information by Xs)
(There's only one entry returned that's why I'm using the rowResult in the console instead of data)
And here's what the console returns:
LOG: Lastname, Firstname
LOG: 񏳿က䙊䙉Āā怀怀
(same here Lastname & Firstname returned are the correct value expected)
This is all running on IE9 and unfortunetly have to make this compatible with IE9 :/
Summary:
I need to find a solution in Javascript only
I know it should be returning a byte array and I need to base64 encode it, but all my attempts failed and I'm a bit clueless on the reason why
I'm not sure if the picture is getting returned at all here, the thing in the console seems pretty small... or if I'm nothing doing the encoding correctly
If someone could help me out with this it would be awesome, I'm struggling with this for so long now :/
Thanks!

Categories

Resources