Converting input string into rest link javascript - javascript

I'm developing a search mechanism with REST requests.
There is an input form, that accepts product titles:
Macbook Pro
iPhone-6
Jack's iPad
I need to send those titles to server in rest format (as a part of a link), such as:
Macbook+Pro
iPhone???6
Jack???s-iPad
Is there a library or a way to do this conversion using javascript? (*I can't use json)
Thank you for your time.

If I am understanding you correctly, you wish to communicate search terms to a REST service?
Assuming your example of Macbook+Pro did not indicate a search operator, you just need to encode your parameters so that the values properly embed into a URL.
For example https://www.google.nl/search?q=These are search arguments will become https://www.google.nl/search?q=These%20are%20search%20arguments.
That, or you do a POST which contains a body (an example is a <form> submit with <input> controls).
Encoding example using plain javascript (jsFiddle):
var searchTerms = 'Macbook Pro';
var searchTermsEncoded = encodeURIComponent(searchTerms);
var url = 'https://www.google.nl/search?q=' + searchTermsEncoded;
console.debug(url); // https://www.google.nl/search?q=Macbook%20Pro
Similarly, Jack's iPad becomes Jack%27s+iPad.
Depending on the type of back-end you are using, your server will decode for you or you have to do it manually. Either way you end up with the original input strings as typed by the user.

Related

Is there a more concise way to POST a large number of input element values to an API?

I have an ASP.NET project that is currently making use of JQuery and Bootstrap to create a front-end. One part of this front-end involves the user filling out a form made up on 30+ input elements, which then needs to be submitted to a back-end API.
Usually if I needed to communicate with an API I would use JQuery's built in post() and post() methods, and constructing a query string to use within these methods.
However since there is a large amount of input elements associated with this form, I am hesitant to make use of this particular approach as it seems like a very messy and roundabout way to submit the data to the API.
Unfortunately the usual <input action="action.xx"> approach is not available to me in this particular situation, so submitting the form as a whole is not a possibility.
However I really don't want to do something like this below:
queryString =
"?input1=" + $("#input1").val() +
"&input2=" + $("#input2").val() ... //repeat for 30+ input elements
$.post(url + queryString, funtion(data){ ... });
Surely there must be a better way to go about solving this particular issue that doesn't involve creating an abhorrently large string and passing it through JQuery's post method?
Give every input a name attribute instead (the same name you want to use for the query string), and then call .serialize() on the form to generate the query string:
$('form').on('submit', function(e) {
e.preventDefault();
console.log($(this).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="inp1">
<input name="inp2">
<input name="inp3">
<button>submit</button>
</form>
Or, if you can't do that, and you want a shorter, less error-prone way of generating the string than what you're using now, iterate over an array of selectors and grab each's .val(), then join by &s:
const ids = ['input1', 'input2', 'input3'];
const queryString = ids.map(id => $('#' + id).val()).join('&');

How do I generate a unique code based on the content?

Picture that you're typing in a input. For each character you add (including special characters, like # . # ยค % & ~ and so on), a unique code will generate based on the content. Not a hash! This unique code will only be 20 characters long.
Example
This is just an example becomes H59S7Y54CI6M7S2XX8A9
This is another example becomes C77KE95HIAJ7VN582758
Hello! I am a example string! becomes Y8BV572SF8U76RXVB944
This is just an example becomes H59S7Y54CI6M7S2XX8A9
Why I want this
I am working on a project where the visitors can login to their own accounts (if they have one). As soon as they type in their email address and password, a unique code will generate based on the string (in a hidden input), so the website can identify the user and get the right data from the database.
Why do I want it?
I encrypt everything in the database with 256-bit AES and each user have their own encryption key. To identify the entered email address and password (which is encrypted with the websites encryption key until they login for the first time), this unique code (based on the string) will identify the login. To do the identification of the login with the websites encryption keys is therefore impossible. Hence my question.
This can maybe be a security risk since the unique code will be stored in the databased hashed in MD5 or Whirlpool, but I have no idea of how I can identify the login in another way. If you know a better way, please tell me.
So, how do I accomplish this? Is it even possible to do?
I know how to generate a unique code which is not based on the content (for an example, generating passwords), but I don't know how to generate a code that are unique based on the content.
I don't know the purpose, but replying directly to your question on how to generate a unique code which is based on the content, you can have something like this
function symmetricEncode(content){
var output = [];
for (var i=0; i<content.length; i++){
output.push(String.fromCharCode(~ content[i].charCodeAt()));
}
return output.join("");
}
var string = "Hey you there";
var code = symmetricEncode(string);
console.log("string to code: ", string);
console.log("code: ", code);
console.log(typeof code);
console.log("decoded code: ", symmetricEncode(code));
This code is not merely a hash, because you can decode it, meaning it is unique, that is, for every input, you get an unique output
Other types of hashes (for example multiplying all the characters) do not fulfil these criteria, because for two different inputs you may get the same output (very unlikely though possible), not being then purely reversible. The ~ makes reference to the bitwise not operator.

Dynamic search input as variable for cypher

I'm trying to create an result page with structr 2.0.1.
enter image description here
Within these page I want to show the results of the user input. The string typed into my input field should be transferred via cypher query to my Neo4j-DB.
Input = "admin" -> Cypher(Match (n) Where n.name = 'admin' Return n)
The return value will be used to instantiate a graph obj via an integer-id (that works totally fine and is no issue).
After hours of investigating unfortunately I'm not able to do it witch the built-in functionality. I tried a lot with the "Query & Data Binding", & "HTML-Properties"-Page and Java Script as well but I couldn't transfer the value from my html element to my cypher query function within my fronted.
[input field ("String")--> button fuction()--> cypher (Query) --> function input {graph.addNode(ID)}]
There must be a solution within structr to solve this problem without a direct ajax-call.
Maybe someone of you discovered the same problem or has a solution for this.
I would very appreciate some help in this case.
Thanks!
Maze
the value of your request parameter is available in StructrScript, see https://support.structr.com/article/119 for more details on that.
In the scripting context, there is an object named request that you can access directly, which will contain any request parameter you send to Structr. So in your case, you can access the value of your input field (provided that you set the name to name) like this:
${request.name}
The following steps are needed to make that work:
create <form method="POST" action="/${page.name}">
insert <input type="text" name="name" value="${request.name}">
insert <input type="submit" value="submit">
When you submit the form, the request parameter "name" will be available in the Structr context as described above.
To insert that value into a Cypher query, you have to construct the query around the request value, for example like that:
${cypher(concat('MATCH (n) WHERE n.name = "', request.name, '" RETURN n'))}
But be very careful with a setup like that, because the above code is vulnerable to a query injection attack (aka SQL injection, or rather CQL injection in this case).

How to convert javascript array to scala List object

I have inherited some code that uses the Play! framework which has scala.html files that have javascript in them. Play! and scala are all new to me.
One of the javascript functions does a post and gets back a JSON object. It then loops through the JSON object and creates an array.
var myArray = [];
function createArray(){
$.post('/createArray', $('#arrayForm').serialize()).done(function( data ) {
var obj1 = JSON.parse(data);
$.each(obj1, function(idx, obj) {
myArray.push(obj.name);
});
});
return true;
}
It then uses this array (of strings) to create a text input field that does autocomplete using the data in the array.
I want/need to convert this text input to a select dropdown using the Play! #select but the options arg for #select wants a List object (or Map or Seq - just figured List would be easier since I already have an array of strings).
If I manually create the List object, it works fine.
#select(pForm("equipName"), options(scala.collection.immutable.List("Yes","No")))
The problem is I cannot figure out how to convert the myArray array to a List object which I can then pass to the #select options.
I have found a lot of posts that talk about converting a scala List to an array but can't find a way to go the other way. I am hoping it is an easy thing that I can't seem to figure out.
Thanks in advance for the help.
You can not do that. And more precisely - you do not want to do that.
So basically your play application run on server. In your Play application all those .scala html files are compiled to generate some functions.
Now, when a play application receives a request from a client browser, it gets mapped to some controller by by router. The controller does some processing and finally take one of these above functions ( lets say for index.scala.html we get views.html.index ) and call this function with some parameters.
These functions returns some text which is then sent to the client's browser as HTTP response with response header Content-Type:text/html; charset=utf-8 which tells the browser to treat this text as html.
Now, the browser renders the html which has embedded JavaScript and hence runs the JavaScript. So... basically your JavaScrpt code does not exist on server... for play all of it is just text.
Both of these Scala code and JavaScript code are executed at very different times, at different computers and in different environments hence you can not do whatever you are saying.

Auto Complete does not filter results when I'm typing

I have very simple form that gets values in JSON format from searchAlbum.php. It works when I start typing something in, but it does not filter results, for example it shows 123 as available even though I typed ab.
This is what my saerchAlbum.php is returning
["123","abc"]
This is my Java Script code
$(document).ready(function(){
$('.albumName').autocomplete({
source: 'searchAlbum.php'
});
});
You might say that it should not filter my resoulds and I need to pass my input as a paramater but why then this examle on jquery-ui page does that for me?
The documentation isn't clear about it, but the only time the autocompleter does the filtering for you is when your code isn't getting called at all (e.g., you've given it an array as source). When your code is getting called (either client-side code because you've given a function for source, or server-side code because you've given a URL), your code is expected to do the filtering.
You might say that it should not filter my resoulds and I need to pass my input as a paramater but why then this examle on jquery-ui page does that for me?
Because the search.php page that the example calls filters the results based on the term parameter the autocompleter passes it. Compare the results you get from these:
http://jqueryui.com/demos/autocomplete/search.php?term=ti
http://jqueryui.com/demos/autocomplete/search.php?term=ro
You can see that it's filtering server-side.
The js sends a query string parameter named "term", your php code needs to return data by filtering existing data that match the "term" parameter.
This isn't a Javascript or jQuery problem, but a PHP problem. As mentioned in the linked jQuery-UI page, the source script must process the "term" property via a GET request.

Categories

Resources