Send date javascript format via ajax

Asked

Viewed 121 times

0

I am trying to send data from a registration form via Ajax/javascript to a java service, but the database receives the data in date format and I do not know what I should do to convert to date, how do I perform this conversion?

function consumir() {

  $.ajax({

    type: "POST",
    url: "http://dalvz/core-web/rest/usuarios",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    cache: true,
    data: JSON.stringify({
      "nome": document.getElementById('nome').value,
      "sobrenome": document.getElementById('sobrenome').value,
      "dataNascimento": document.getElementById('dataNascimento').value,
      "email": document.getElementById('email').value,
      "senha": document.getElementById('senha').value
    }),

    success: function (data) {
      alert(data.nome);
    }

  });
}

2 answers

0

Assuming you are using the date formed "d/m/A", to insert into the Mysql database it must be in "Y/m/d".

Your code should look like this:

function consumir() {

    var data = document.getElementById('dataNascimento').value.split("-");
    var dataNascimento = new Date(data[2], data[1], data[0]);

    $.ajax({

        type: "POST",
        url: "http://dalvz/core-web/rest/usuarios",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: true,
        data: JSON.stringify({
            "nome": document.getElementById('nome').value,
            "sobrenome": document.getElementById('sobrenome').value,
            "dataNascimento": dataNascimento,
            "email": document.getElementById('email').value,
            "senha": document.getElementById('senha').value
        }),

        success: function(data) {
            alert(data.nome);
        }

    });
}

0


If you have to deliver this date in YYYY-MM-DD format and have it in DD/MM/YYYY format, you can use this code to convert.

var dataNascimento = new Date(document.getElementById('dataNascimento').substr(0, 10).split('/').reverse().join('-'));

Browser other questions tagged

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