Best way to loop through arraylist in grails - javascript

I'm sending string array to my controller that contains array of Ids in it.
function submit(){
var ids = [];
bootbox.confirm("Are you sure to send data?", function(confirmed){
if(confirmed){
$('input[id^="tdCheckbox_"]').each(
function () {
var $this = $(this);
if($this.is(":checked")){
ids.push($this.attr("id").replace("tdCheckbox_",""));
}
}
);
$("#Ids").val(ids);
$("#submitForm").submit();
}
});
}
<g:formRemote name="submitForm" url="[controller:'myController', action:'submit']" onSuccess="removeIds(data)">
<g:hiddenField name="Ids" />
</g:formRemote>
CONTROLLER:
def submit(){
def result = [success:false]
if(params?.Ids){
String[] ids = params?.Ids
ids.eachWithIndex{ it, int i ->
//HERE OUTPUT IS LIKE
//4
//,
//5
//,
//6
println(it.value)
}
result["id"] = params?.Ids
}
render result as JSON
}
In eachWithIndex loop i'm getting output with , (comma) that I do not require, I think there must be a good option to loop through it.
Please suggest the same.

problem that you submitting from javascript one string value (ids delimited with coma)
ids=1,2,33
and on the level of groovy/grails the params?.Ids returns you just a String like this: "1,2,33"
and assigning a String to a String[] just splits it by chars...
as workaround in groovy you can use params?.Ids?.split(',')
String[] ids = "1,2,33".split(',')
or submit multiple values form javascript like this:
ids=1 & ids=2 & ids=33
in this case grails will return you an array for params?.Ids expression if more then one value submitted with the same name

Related

How to pass array from Javascript to controller's action?

I have JS function like this inside the #section Scripts of .cshtml view:
function SendIndexes() {
var selectedSortOption = $("#SortBy").find('option:selected');
var sortIndex = selectedSortOption.val();
var selectedFilterByTypeOption = $("#filter_marker_bytype").find('option:selected');
var filterByTypeIndex = selectedFilterByTypeOption.val();
var selectedFilterByScoreOption = $("#filter_marker_byscore").find('option:selected');
var filterByScoreIndex = selectedFilterByScoreOption.val();
var selectedFilterByStatusOption = $("#filter_marker_bystatus").find('option:selected');
var filterByStatusIndex = selectedFilterByStatusOption.val();
var markerFilterIndexes = [filterByTypeIndex, filterByScoreIndex, filterByStatusIndex];
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes=${markerFilterIndexes}`
}
and the controller action signature like this:
public async Task<IActionResult> MarkersList(List<string> markersForUpdateIds, IEnumerable<int> markerFilterIndexes, int page = 1, string message = "", int sortIndex = 0)
{
...
}
The problem is that the array of three elements is not passed at all. However, if I only push a single variable (element) to this array, then it is passed to the controller's action as it should.
Why is this happening and how to have all three elements passed to the controller?
I'll suggest you to use [FromQuery] attribute in your parameter and format your URL like this: myparam=myvalue1&myparam=value2&myparam=myvalue3.
public async Task<IActionResult> MarkersList([FromQuery]List<string> markersForUpdateIds, [FromQuery]IEnumerable<int> markerFilterIndexes, [FromQuery]int page = 1,[FromQuery] [FromQuery]string message = "", [FromQuery]int sortIndex = 0)
{
...
}
Take a look of ModelBinding:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#sources
For passing an array to the controller action. Data formats that use subscript numbers (... [0] ... [1] ...) must ensure that they are numbered sequentially starting at zero. Here you don't need to define an array, just format your url like this:
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes[0]=${filterByTypeIndex}&markerFilterIndexes[1]=${filterByScoreIndex}&markerFilterIndexes[2]=${filterByStatusIndex}`
Since the data in the array is just int type data, you can omit the subscript numbers.

How to search array keys in JavaScript/jQuery using indexOf

I have an array members. This array has a name as the index (e.g. "John Smith") and an array with "degree" and "id", like so:
I have a search that fires on keyup action. It is supposed to search through the member names (the index) and then output the name of any matching members to the console:
function memberSearch(){
var $input = $("#guestsearch>input");
var val = $input.val();
console.log(val);
$.each(members, function(i,v){
if(i.indexOf(val)>-1){
console.log(members[i]);
}
})
}
However, this doesn't output anything except the search value val. Even if the $.each function is just console.log(i), nothing outputs.
If I manually type console.log(members) into console, the screenshot from above is the result.
members is populated by this segment of a function:
$.each(json.response.data[0].members, function(i,v){
var m = json.response.data[0].members[i];
var name = m.name;
if(name.typeof!=="undefined"&&name!=""&&name!=null&&name.length>0){
members[name] = [];
members[name]["degree"] = m.degree;
members[name]["id"] = m.id;
}
})
How can I make this search work?
If members is an object, which it looks like with the key/value pairs, you can use Object.keys(objVariable) to get the keys of an object to loop over and do your comparison/regex logic on.
Object.keys(members).forEach(function(name){
if (/* logic to match on name */) {
console.log(members[name]);
}
});
Otherwise if members is an array containing those objects...
var matchingUsers = members.filter(function(){
var username = Object.keys(this)[0];
return (/* match username to whatever */);
});
Then matchingUsers would be an array containing all the users that passed your criteria.

Get individual values from Third Party Response Data in HTML page

I need a help for How to get Individual values from HTML page.
i got response from some PAYU payment gateway team in HTML page but i need individual attributes values from tacking Transaction
Below is the response am getting from PAYU Team:
<h1>This is the success url</h1>
<p>Your transaction is completed successfully. Bank response is
mihpayid=403993715514374636&mode=&status=failure&unmappedstatus=userCancelled&key=gtKFFx&txnid=txn1r23fw&amount=100.00&discount=0.00&net_amount_debit=0.00&addedon=2016-04-25+10%3A48%3A29&productinfo=oxygenconcentrator&firstname=test&lastname=&address1=&address2=&city=&state=&country=&zipcode=&email=test%40gmail.com&phone=8152709721&udf1=&udf2=&udf3=&udf4=&udf5=&udf6=&udf7=&udf8=&udf9=&udf10=&hash=6a9d21bd423d61cd5a7d91098aa1140314e45eaddd8d4b9148399caba8ac61a9476aec130eb369f7d526e741b1b6c47b1ca71bec21fa69aa3deaa13740dbffbc&field1=&field2=&field3=&field4=&field5=&field6=&field7=&field8=&field9=Cancelled+by+user&payment_source=payu&PG_TYPE=&bank_ref_num=&bankcode=&error=&error_Message=
</p>
<script>
PayU.onSuccess("mihpayid=403993715514374636&mode=&status=failure&unmappedstatus=userCancelled&key=gtKFFx&txnid=txn1r23fw&amount=100.00&discount=0.00&net_amount_debit=0.00&addedon=2016-04-25+10%3A48%3A29&productinfo=oxygenconcentrator&firstname=test&lastname=&address1=&address2=&city=&state=&country=&zipcode=&email=test%40gmail.com&phone=8152709721&udf1=&udf2=&udf3=&udf4=&udf5=&udf6=&udf7=&udf8=&udf9=&udf10=&hash=6a9d21bd423d61cd5a7d91098aa1140314e45eaddd8d4b9148399caba8ac61a9476aec130eb369f7d526e741b1b6c47b1ca71bec21fa69aa3deaa13740dbffbc&field1=&field2=&field3=&field4=&field5=&field6=&field7=&field8=&field9=Cancelled+by+user&payment_source=payu&PG_TYPE=&bank_ref_num=&bankcode=&error=&error_Message=");
</script>
I got this response from below snippet
iabRef.executeScript(
{ code: "document.body.innerHTML" },
function( values ) {
alert(values[0]);
console.log(values[0]);
}
);
so i need individual attribute values like mihpayid ,mode,status and so on......
Assuming that values or values[0] will have :
"mihpayid=403993715514374636&mode=&status=failure&unmappedstat"
Then you could write a function as below:
function extractScript(source){
var pattern = /<script>(\w+)<\/script>/
var matches = source.match(pattern);
return matches[1];
}
function getValue(source, key){
var pattern = key+'=(\\w+)(&)?';
var expr = new RegExp(pattern);
var result = source.match(expr);
return result[1];
}
Then in executeScript:
iabRef.executeScript(
{ code: "document.body.innerHTML" },
function( values ) {
//incase values[0] contains result string
console.log(getValue(values[0], 'mihpayid'))
//or
//incase values[0] contains result string
console.log(getValue(values, 'mihpayid'))
}
);
You can just get the contents of the p tag then perform a split twice
Assuming that p is the only p tag in the page you can get the value by calling
var text= document.getElementByTagName('p').innerHtml;
First split the &
var theArray= text.split('&');//or just & depending on how your text comes out
this will return an array that'll contain something like [status=failure,phone=8152709721]
Then you can loop through this array and create an object
var obj = {} ;
//loop here then do this within the loop
var kv=theArray[i].split('=');
obj[kv[0]] = kv[1];
So you can get your attributes by calling obj.status

Array is not serialized and resulting a string

A list that contains a set of arrays is being serialized into jquery. However when check in client side, it is receiving only a string instead of the array object.
c#:
public string jsscript(){
// datatable processing
var arrList = new List<object>();
foreach (DataRow row in table.Rows)
{
string name = row[0].ToString();
string quantity = row[1].ToString();
string balance = row[2].ToString();
string remove = "X";
arrList.Add( new[] { name, quantity, balance, remove });
}
return (new JavaScriptSerializer()).Serialize(arrList);
}
js:
<script>
//dom...
function theDomHasLoaded(e) {
dbdata = <%=jsscripts()%>;
</script>
see JSON string to JS object
you need to use JSON.parse(..) on the serialised string
that is of course presuming that that is the problem... It's not entirely clear what your problem is.

Unable to map javascript array in struts 2 action as List<String>

In an html page, I have checkboxes like following:
<input name="serviceareas" type="checkbox" id="cb1" value="1">
<input name="serviceareas" type="checkbox" id="cb2" value="2">
...
with the help of jquery I create javascript array of values for all the checked checkboxes
getSelectedValues : function() {
var allVals = [];
$('#checkboxTable :checked').each(function() {
allVals.push($(this).val());
});
//alert("allVals: "+allVals);
return allVals;
}
, and sends it to Struts 2 Action. For example in firebug request, I see :-
serviceareas 21,26,30
In the Action I have tried mapping it to
private List<String> serviceareas = new ArrayList<String>();
But instead SOP is printing it as an Object and it isn't able to cast it to java List
public class CreateEventAction extends ActionSupport {
private List<String> serviceareas = new ArrayList<String>();
public List<String> getServiceareas() {
return serviceareas;
}
public void setServiceareas(List<String> serviceareas) {
this.serviceareas = serviceareas;
}
#Override
public String execute() throws Exception {
if(this.serviceareas != null) {
for (String serviceAreaId : this.serviceareas) {
System.out.println("String :"+serviceAreaId);
}
}
return SUCCESS;
}
Output:
String :21,26,30
Please help. Thanks in advance.
Assuming that you submit to action works, try to construct your parameters like that:
serviceareas=21&serviceareas=26&serviceareas=30
Aleksandr M's answer should work. I am posting this answer just to make it more clear how to implement it.
Instead of submiting javascript array, submit a string.
getSelectedValues : function() {
var allVals = '';
$('#checkboxTable :checked').each(function() {
allVals += "serviceareas="+$(this).val()+"&"; //prepare the string
});
if(allVals.length>0){
allVals = allVals.substring(0,allVals.length-1); //remove last '&'
}
return allVals; //submit this string as parameter
}
I think this is not possible. When you submit a form which has a check box or multiple list in the servlet we normally call getPrameterValues() , this method internally convert the coma seperated string to and array and returns it as an array of string. But here in your case you just submit a coma separated string and action servlet call interanlly call getPrameter() , so it will be a sting there and initilaise your List with one string. to get it done you will have to submit the form which has the checkbox group.
here you can do a quick fix by spliting this coma separated string in your action class ....or you need to find out the way how you can submit with respective property in your actionFor( struts 1.2). Let me have a quick refferences of struts 2. anyhow the current approach is wrong.

Categories