Dust.Js sections and paths - json

I get a error JSON in following format
error = [{field:'one', desc:'This is error for field one', value='FromPostFieldOne'},
{field:'two', desc:'This is error for field two', value='FromPostFieldTwo'}];
which I want to display in following template
{#error}
<form>
<input type="text" name="one" id="one" value="<!- value for field one from JSON-->"/>
<!-- Display error from JSON for field one here -->
<input type="text" name="two" id="two" value="<!- value for field two from JSON -->"/>
<!-- Display error from JSON for field two here -->
</form>
{/error}
I am not able to figure if I achieve this with ether "Explicit context setting" or "{#if cond="condition"} helper". All examples on Linkedin Dust site illustrate how to do this with JSON key values but not object arrays.
Help appreciated !!!!

your json is not valid you should make something like this:
error = [
{
field:'one',
desc:'This is error for field one',
value:'FromPostFieldOne'
},
{
field:'two',
desc:'This is error for field two',
value:'FromPostFieldTwo'}
];

Related

How do I POST an array to the server?

I am trying to post an array of multiple geolocation addresses (generated by Google maps) to my server. The array displays correctly as an array while on the client side, however, the array arrives at the server as a string and not as an array. I am not entirely sure why this happens, also I can't figure out how to convert this string back into an array on the server.
Find below the code of the array while on the client side via the browser:
console.log("Geolocations: " ,selecedAddresses);
This codeabove yields an array of 3 items as illustrated below:
Geolocations: (3) ['Kileleshwa, Nairobi, Kenya', 'Ntinda, Kampala, Uganda', 'Uhuru Highway, Nairobi, Kenya']
When the same array is expanded for better readability:
0: "Kileleshwa, Nairobi, Kenya"
1: "Ntinda, Kampala, Uganda"
2: "Uhuru Highway, Nairobi, Kenya"
length: 3
For me to be able to POST the array to the server, I assign the array value to an HTML input field in a form.
document.getElementById('locationArray').value = selecedAddresses;
Find below the code to my HTML form where input field resides:
<form action="/advertiser" method="POST" enctype="multipart/form-data">
<div class="mb-3">
<input type="text" name="locationArray" value="" hidden/>
</div>
<button type="submit" class="btn btn-secondary"> Add location </button>
</form>
When the user clicks on the Add location button, the array is submitted to the server.
And now for the server side code...
app.route('/Geolocations')
.post((req, res)=>{
let locationArray = req.body.locationArray;
console.log("locationArray: " +locationArray);
})
The code above yeilds:
locationArray: "Kileleshwa, Nairobi, Kenya, Ntinda, Kampala, Uganda, Uhuru, Highway, Nairobi, Kenya"
Instead of the desired out put:
['Kileleshwa, Nairobi, Kenya', 'Ntinda, Kampala, Uganda', 'Uhuru Highway, Nairobi, Kenya']
Looking forward to your help.

AWS S3- Policy Condition Failed- eq key

I am working on uploading files to s3 from the website. I get all needed information from my nodejs server which uses aws sdk. The problem I have is that it generates a key which I have to use in my form like this:
<input type="hidden" name="key" value="xxx" /><br />
And it works, but every file I upload has the name of the 'key'. If I change it to sth like this:
<input type="hidden" name="key" value="xxx/name.jpg" /><br />
It gives me an error:
Invalid according to Policy: Policy Condition failed: ["eq", "$key", "xxx"]
Here are my conditions to generate the policy:
Conditions: [
['starts-with', '$key', ''],
["starts-with", "$Content-Type", "image/"],
{"x-amz-server-side-encryption": "AES256"}
]
How can I set the name of the file?
I solved it. The problem was that in parameters object which is passed this function:
s3.createPresignedPost(params, function(err, data)
I had parameter Fields which included key:
Fields: {
key: key,
},
Simply deleting it fixed the problem

htmlspecialchars() expects parameter 1 to be string array given

I have an input field in which I am passing an array from my controller as hidden input but its giving me this error of array given.
Code of my view is
<input type="hidden" name="DiseaseDiagnosed[]" value="{{$DiseaseDiagnosed}}">
Code of controller passing the value to view is
return view('/doctorPanel/diagnoseDisease', ['chart' => $chart, 'patient' => $patient, 'symptomsStated' => $symptomsStated, 'DiseaseDiagnosed' => $DiseaseDiagnosed]);
Kindly tell me why I am getting this error
<input type="hidden" name="DiseaseDiagnosed[]" value="{!! jsond_encode($DiseaseDiagnosed) !!}">
Actually, your input is DiseaseDiagnosed is an array which is returned to view.
So you have to use {{ json_decode($DiseaseDiagnosed) }}
You can also try
#foreach($DiseaseDiagnosed as $disease)
<input type="hidden" name="DiseaseDiagnosed[]" value="{{ $disease }}">
#endforeach
Blade Template engine is producing this error. you can't print array like this using {{ }}. When passing this value, you can encode it using 'DiseaseDiagnosed'=>json_encode($DiseaseDiagnosed]), then you can use that syntax. After that when you want to use this value, don't forget to decode it using json_decode()
In order to create an array with inputs you need to have 1 input for each value inside the array. You are appending an array on the value when it only accepts Strings so thats why it warns you that an array was given when a String was expected.
As #Adnan suggested you can solve this using:
#foreach($DiseaseDiagnosed as $disease)
<input type="hidden" name="DiseaseDiagnosed[]" value="{{ $disease }}">
#endforeach
Then in your controller you will recieve the array DiseaseDiagnosed with all the values you inserted, eg: You will recieve all the values within the same array->
dd($request->DiseaseDiagnosed);
// You will see this is an array with all the values

HTML Form: POST an array of objects

Submitting a class roster. Adding 3 students at once. Each student has first, last, age.
Question: How can we get all of the students in an array of arrays?
students[0] => Array (
["first"] => "first name for 0",
["last"] => "last name for 0",
["age"] => "age for 0"
),
students[1] => Array (
["first"] => "first name for 1",
["last"] => "last name for 1",
["age"] => "age for 1"
),
...
Details
For one student:
<input type="text" name="first">
<input type="text" name="last">
<input type="text" name="age">
We can return multiple students in separate arrays like this:
<input type="text" name="students[first][]">
<input type="text" name="students[last][]">
<input type="text" name="students[age][]">
which returns an array of firsts, lasts and ages
students["first"] = [array of first names]
students["last"] = [array of last names]
students["age"] = [array of ages]
Theoretically we can get all the info for a student by accessing the same index (say "3" for each array).
We do not want to programatically add an index in the form.
Do not want:
<input type="text" name="students[hardcoded_index][first]">
<input type="text" name="students[hardcoded_index][last]">
<input type="text" name="students[hardcoded_index][age]">
If for any reason it matters, we are using Rails for views but can use form helpers or HTML.
tl;dr: Add empty brackets ([]) after students to the input names.
Fiddling with Rack::Utils.parse_nested_query it seems you can get the payload you want like this:
<!-- first student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">
<!-- second student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">
Note the empty brackets ([]) after students. This tells Rack you want the students param to be an array. Subsequent params encountered (with the same name) will start a new element.
POST /myroute?students[][first]=foo&students[][last]=bar&students[][age]=21&students[][first]=baz&students[][last]=qux&students[][age]=19
Gets parsed like this:
{"students" => [
{
"first" => "foo",
"last" => "bar",
"age" => "21"
},
{
"first" => "baz",
"last" => "qux",
"age" => "19"
}
]}
Further reading: http://codefol.io/posts/How-Does-Rack-Parse-Query-Params-With-parse-nested-query
I know the question is old , but I would like to add my experiences
also for future readers.
For those of you who want to process the data in a PHP enviroment ,
#messanjah's method won't work ,
The methods for parsing data like the built-in serializeArray or serialize are not parsing it as expected either.
This is what I tried so far ...
students[name]
students[][name] - Very Strange since it was meant to automatically index the array
students[name][]
Neither of them worked, but this students[<hardcoded-index>][name] worked for PHP ,
I know that although the question is against this method , but it
will be useful for PHP users who will land here in the nearby future
as the asker needed it for Ruby On Rails.
The method you choose to hard code the indexes is upto you , you can use a cleaner method by using javascript or you can manually hard code them initially in your form element.
Cheers

How to process a POST request in SWI-Prolog?

I have an HTML form like this one:
<form action="test" method="post">
<input name="first_name" type="text"/>
<input name="last_name" type="text" />
<input name="age" type="text" />
<input type="submit" value="Send"/>
</form>
How do I get the values of the input fields and print them on screen, just like in any other procedural programming language such as PHP, ASP or JSP?
I tried to solve the problem the following way:
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- http_handler(root(test), reply, []).
:- http_handler('test', reply, []).
server(Port) :-
http_server(http_dispatch, [port(Port)]).
reply(Request) :-
member(method(post), Request), !,
http_read_data(Request, Data, []),
format('application/x-www-form-urlencoded', []),
format(Data).
That brought me nothing more than an error with the 500 code (internal server error).
You should use the http/http_client library (:- use_module(library(http/http_client))).
Additionally, I'm not sure how having two handlers for test will work.
Finally, I think that format(Data) might not work, especially since it is expected to return an html document.
By the way, to retrieve the values of the fields you can do something like:
http_read_data(Request, [first_name=FN, last_name=LN, age=A|_], []).
I'm pretty new with the http prolog lib, I would suggest checking http://www.pathwayslms.com/swipltuts/html/
Essentially, you'll handle the request like normal, checking that the method(Method) term in the request is method(post).
http_read_data will read the request body.
the body will be encoded like an URI query string, so uri_query_components/2
will convert it to a list of Key=Value terms
?- uri_query_components('a=b&c=d%2Bw&n=VU%20Amsterdam', Q).
Q = [a=b, c='d+w', n='VU Amsterdam'].
For others looking for similar info - if your response is json, you can use read_json_dict to get the data as a dict.
I use library(http/http_parameters). With that, I can do
load_graph(Request) :-
http_parameters(Request,
[path(Path, [atom]),
aperture(Aperture, [integer])]),
where load_graph is the handler for the form
...
html(form([action(Ref)],
dl([dt('Root Path'), dd(input([name=path, type=text, value=Default])),
dt('Aperture'), dd(select([name=aperture], Aplist)),
dt('Go!'), dd(input([type=submit, value='Load!']))
]))).