How do I POST an array to the server? - html

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.

Related

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

MeteorJS: How to get id to load from collection

I'm trying to load an array (with simple text) and trying to load it up on the template whenever it is called. How do I get the ID from that specific item to get the array that I stored in it?
HTML Template:
<template name="commentMarker">
<div id="viewMarker">
<h3 id="markerTitle">{{markerName}}</h3>
<h6 id="markerCategory">{{markerCategory}}</h6>
<br>
<fieldset>
<legend>Description</legend>
<p>{{markerDescription}}</p>
</fieldset>
<form id="commentForm">
<fieldset>
<legend>Comments</legend>
<input type="text" id="markerId" name="idForComment" value={{markerId}}>
<textarea rows="3" cols="19" name="comment" id="commentArea" placeholder="Insert your comment here..."></textarea>
{{#each comments}}
<p id="oneComment">{{this}}</p>
{{/each}}
</fieldset>
<input type="submit" value="Comment" class="commentButton">
<input type="submit" value="Close" class="exitButton">
</form>
</div>
</template>
JS:
Template.commentMarker.helpers({
comments(){
alert(template.find("#markerId").value);
if(commentArray.length===0) return;
else return commentArray;
}});
This is where I insert the comment into the collection's item and it's working fine
Template.commentMarker.events({
'click .commentButton': function(e, template){
e.preventDefault();
var id = template.find("#markerId").value;
var comment = template.find("#commentArea").value;
Points.update(id, { $push: { comments: comment }});
commentArray = Points.findOne(id).comments;
template.find("#commentArea").value = ' ';
}
I tried with commentArray as a global variable which still is. But I'm at loss how I can get the Id from that specific item, I even put it's Id (with hidden display) in the form to actually be able to insert the comment. But it doesn't help me with showing the comments because I cannot seem to get to this field in the Template.helpers ...
Not entirely sure what you are trying to do. It's almost like as if you are displaying the comments right after you updated in to the collection. It looks like you are doing this entirely on local and not a online collection.
However, storing it as a session would work...or reactive var. Might not be the best solution tho. Basically replace commentArray = Points.findOne(id).comments; with:
Session.set('comments', Points.findOne(id).comments)
Then to get it out in helpers:
let commentArray = Session.get('comments')
It's not safe to use it all the time tho for sensitive data. Also try catch the findOne(id).comments because it does produce errors if it happen to not find it.
NOTE: If you are going to use Meteor.Methods, you cannot use Session. You have to return the id and find it in your helpers.

Remove object from array typescript(Angular 2)

I just try to delete object from array in typescript, in angular 2.4.0, let me show the code, its my html file:
button type="submit" (click)="addAnotherLanguague()" >Add non native languague</button>
<li *ngFor="let languague of listOfLanguagues;">
<div class="form-item form-item--text">
<label class="label invisible">Years studied</label>
<input type="number" min="0" [(ngModel)]="languague.yearsStudied" name="years" placeholder="Years studied"/>
</div>
<button type="submit" (click)="removeLanguague(languague)" >Remove</button> // here you can see use of method
</li>
And there is component.ts
(...)
this.listOfLanguagues = new Array <LanguagueInformationData>();
}
addAnotherLanguague(){
this.listOfLanguagues.push(new LanguagueInformationData);
}
removeLanguague(languague){
this.listOfLanguagues.slice(this.listOfLanguagues.indexOf(languague), 1);
}
(...)
Adding works well, but I tried everything to remove and still dont know how to transfer that languague's reference, I dont want to use .pop, because I want to remove exactly this languague below which is button.
Can you help me?
[edit]
I got problem again with this code, because every time I try to add new languague(push) it clears my data on classes existing in array, do you know what can cause it ?
<li *ngFor="let languague of listOfLanguagues; let i = index">
<button type="submit" (click)="removeLanguague(languague, i)" >Remove</button>
removeLanguague(languague, index){
this.listOfLanguagues.splice(index, 1);
}
You have to use splice and not slice
this.listOfLanguagues.splice(this.listOfLanguagues.indexOf(languague), 1);
slice returns a section of an array, and splice removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements

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!']))
]))).

Passing a url in a form from page to servlet drops part of query string

If I have a form on a JSP like this:
<form action = "/myApp/myServlet?rssFeedURL=${rssFeedURL}' />" method = "post">
<input type = "button" value = "See data for this RSS feed."/>
</form>
What I find is that if the variable ${rssFeedURL} has no query string, then the server receives it properly, e.g.:
http://feeds.bbci.co.uk/news/rss.xml
But if a query string exists, e.g.:
http://news.google.com/news?ned=us&topic=m&output=rss
I expect that it is to do with the encoding of the '&' character. Can anyone advise?
The server receives only:
http://news.google.com/news?ned=us
My pages are charset=UTF-8 encoded.
You need to URL-encode request parameters. Otherwise they will be interpreted as part of the initial request URL.
JSTL offers you the <c:url> for this.
<c:url var="formActionURL" value="/myApp/myServlet">
<c:param name="rssFeedURL" value="${rssFeedURL}" />
</c:url>
<form action= "${formActionURL}" method="post">
...
An alternative is to create an EL function which delegates to URLEncoder#encode().