shorif2000
shorif2000

Reputation: 2654

how to get array when using hapi, vision and ejs

i am posting checked values as an object via jquery post to nodejs. im not sure how to do request.payload.card as i get the following result

content of request.payload

[Object: null prototype] { 'card[]': '2S' }

I have tried to use parse(...) from const { parse } = require('querystring'); but this gives empty object {}

update

here is my form in ejs view

<form id="frm_cards" method="POST" action="/g/f15cde50-6c2b-479a-8105-3c1ea63fb982/e">
  <div class="container">
    <div id="cards">
    <div class="row"><div class="row col-sm-12"><div class="col-sm-6 col-md-2"><div><img class="col-sm-12 col-md-11" src="https://....com/static/img/KH.png"></div><div class="text-center"><input name="card" id="card_[object Object]" type="checkbox" value="KH"> Discard</div></div><div class="col-sm-6 col-md-2"><div><img class="col-sm-12 col-md-11" src="https://....com/static/img/4H.png"></div><div class="text-center"><input name="card" id="card_[object Object]" type="checkbox" value="4H"> Discard</div></div><div class="col-sm-6 col-md-2"><div><img class="col-sm-12 col-md-11" src="https://....com/static/img/9S.png"></div><div class="text-center"><input name="card" id="card_[object Object]" type="checkbox" value="9S"> Discard</div></div><div class="col-sm-6 col-md-2"><div><img class="col-sm-12 col-md-11" src="https://....com/static/img/JS.png"></div><div class="text-center"><input name="card" id="card_[object Object]" type="checkbox" value="JS"> Discard</div></div><div class="col-sm-6 col-md-2"><div><img class="col-sm-12 col-md-11" src="https://....com/static/img/KC.png"></div><div class="text-center"><input name="card" id="card_[object Object]" type="checkbox" value="KC"> Discard</div></div></div><div class="col-xs-2"></div></div></div>
    </div>
      <button id="submit" type="button" class="btn btn-primary btn-block">submit</button>
    </form>

The jquery in the view that posts to handler

var allVals = [];
$('input[name="card"]:checked').each( function(){
   allVals.push($(this).val());
});

if(allVals.length == 0 ){
  alert(`error`);
  return;
}   
const params = $('#frm_cards').serialize(); 

//stringify to handle arrays
$.post(`/g/<%= gId %>/e`, params )
.done((data, textStatus, xhr) => {
...
})
.fail((error) => { console.error(error)});

my handler

const cards =
    typeof req.payload.card === "string"
      ? [req.payload.card]
      : req.payload.card;

If i select 1 checkbox it sends as string. if i select more than one then it comes as array.

Upvotes: 0

Views: 321

Answers (1)

Rami Jarrar
Rami Jarrar

Reputation: 4643

You can use it like this request.payload['card[]'] so in your handler

let cards = request.payload['card[]']
cards = typeof cards === "string" ? [cards] : cards;

you can also use isArray

cards = Array.isArray(cards) ? cards : [cards];

Upvotes: 0

Related Questions