POST API Rest JSON

Asked

Viewed 1,576 times

1

I have a form in HTML which should send data to a server in format JSON. How I format this input data and send to a Rest API the JSON data the way I described below?

In my view I need to do a POST, the difficulty is to format the way it should be sent.

Form:

<form>
  <div class="form-group">
    <label for="nome">Nome</label>
    <input type="text" class="form-control" id="nome" placeholder="Enter name">
  </div>
  <div class="form-group">
    <label for="pw">Password</label>
    <input type="password" class="form-control" id="pw" placeholder="Password">
  </div>
  <div class="form-check">
    <label class="form-check-label">
      <input type="checkbox" class="form-check-input">
      Check me out
    </label>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

The server should receive the data in JSON as follows

{
    "nome": "Ricardo",
    "pw": "01023423sdqz1",
}

4 answers

3

I would change the button to type="button" not to give the full post and on the onclick of the button I would call this code below:

$.ajax({
    url: 'http://coloqueaquisuaurl.com/caminho',
    type: 'POST',
    data: { nome: $('#nome').val(), pw: $('#pw').val() },
}).done(function (data) {
    alert('entrei aqui');
})

2

If you use php, you can format it as follows:

$json = array('nome' => $_POST['nome'], 'pw' => $_POST['password']);
$json = json_encode($json)

1

If you are using jQuery, the answer is simple:

var conteudoDoForm = $("form").serialize();

If not, you can use this method mentioned in Stack Overflow in English:

function serialize(form, evt){
    var evt    = evt || window.event;
    evt.target = evt.target || evt.srcElement || null;
    var field, query='';
    if(typeof form == 'object' && form.nodeName == "FORM"){
        for(i=form.elements.length-1; i>=0; i--){
            field = form.elements[i];
            if(field.name && field.type != 'file' && field.type != 'reset'){
                if(field.type == 'select-multiple'){
                    for(j=form.elements[i].options.length-1; j>=0; j--){
                        if(field.options[j].selected){
                            query += '&' + field.name + "=" + encodeURIComponent(field.options[j].value).replace(/%20/g,'+');
                        }
                    }
                }
                else{
                    if((field.type != 'submit' && field.type != 'button') || evt.target == field){
                        if((field.type != 'checkbox' && field.type != 'radio') || field.checked){
                            query += '&' + field.name + "=" + encodeURIComponent(field.value).replace(/%20/g,'+');
                        }   
                    }
                }
            }
        }
    }
    return query.substr(1);
}

-1

You’ll have to use javascript for that reason.

Follow an example

document.getElementById('submit').onclick = function(){
  let jsonArr = {
    "nome": document.getElementById('nome').value,
    "senha": document.getElementById('pw').value
  }
  
  console.log(jsonArr)
  
  axios.post('SUA URL', jsonArr)
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })
}
  <div class="form-group">
    <label for="nome">Nome</label>
    <input type="text" class="form-control" id="nome" placeholder="Enter name">
  </div>
  <div class="form-group">
    <label for="pw">Password</label>
    <input type="password" class="form-control" id="pw" placeholder="Password">
  </div>
  <div class="form-check">
    <label class="form-check-label">
      <input type="checkbox" class="form-check-input">
      Check me out
    </label>
  </div>
  <button class="btn btn-primary" id="submit">Submit</button>


<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.