Ajax POST using a variable and an object

Asked

Viewed 102 times

0

Hello, I’m having trouble sending a POST, using Ajax, only that the content has to be in this format:

name: 'Nome Candidato',
contents = {
'email': '[email protected],
'formacao': 'superior completo'
}

When doing the POST by Postman, it sends normally:

inserir a descrição da imagem aqui

But when doing it by HTML, it always returns error 422 in the URL.

var vNome = $("#nome").val();
var vEmail = $("#email").val();

var vData = {
    name : vNome
    <<<<<< Não sei o que colocar aqui >>>>>>
};

$.ajax({
    method: "POST",
    url: vUrl,
    data: JSON.stringify(vData)
})
.done(function(msg){
    $("#resultado").html(msg);
})
.fail(function(jqXHR, textStatus, msg){
    alert(jqXHR);
}); 

2 answers

3


The first mistake is here:

name: 'Nome Candidato',
contents = {
'email': '[email protected],
'formacao': 'superior completo'
}

Because, apparently, you’re trying to send an object, however, the syntax of an object, in javascript, is not thus there (I don’t mean because of the single quotes, as much as it works, I mean because of the equality after the happy word), but this, here, is the correct syntax:

name: 'Nome Candidato',
contents: {
  email: '[email protected]',
  formacao: 'superior completo'
}

Another thing: Sending in this way data: JSON.stringify(vData), their data will be sent as string, but not objects, because the function stringify converts an object to a string.

So, to correct, I’m sending you a complete and tested code, I hope it helps you.

index php.:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

</head>

<body>
    <input type="text" id="nome" autofocus>
    <input type="text" id="email">
    <input type="text" id="formacao">
    <button id="enviar">Enviar</button>

    <pre id="resultado"></pre>

    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
    <script>
        $(document).ready(function() {

            $("#enviar").click(function() {

                var vNome = $("#nome").val();
                var vEmail = $("#email").val();
                var vFormacao = $("#formacao").val();

                //Um arquivo de servidor em php, somente para teste:
                var vUrl = "teste.php";

                //Sintaxe correta:
                var vData = {
                    name: vNome,
                    contents: {
                        email: vEmail,
                        formacao: vFormacao
                    }
                };

                $.ajax({
                        method: "POST",
                        url: vUrl,
                        data: vData
                    })
                    .done(function(msg) {
                        $("#resultado").html(msg);
                    })
                    .fail(function(jqXHR, textStatus, msg) {
                        alert(jqXHR);
                    });
            });


        })
    </script>
</body>

</html>

php test.:

<?php
print_r($_POST);

print_r("\n<strong>Chaves:</strong>\n\n");

print_r(array_keys($_POST));

print_r('<h3>Saida:</h3>');

var_dump('name =>'.$_POST['name']);

var_dump('contents[emai] => '.$_POST['contents']['email']);

var_dump('contents[formacao] => '.$_POST['contents']['formacao']);

/*Saída:

Array
(
    [name] => Taffarel
    [contents] => Array
        (
            [email] => Xavier
            [formacao] => sadfads
        )

)

Chaves:

Array
(
    [0] => name
    [1] => contents
)

string(15) "name =>Taffarel"
string(24) "contents[emai] => Xavier"
string(29) "contents[formacao] => sadfads"
*/

I almost forgot: the variable vUrl had some value in its code?

Print:

inserir a descrição da imagem aqui

REFERENCE:
Ajax Form Data

  • 1

    Thanks for the help Taffarel. It really was JSON.stringify. Thank you!

0

var vData = {
    name : vNome,
    contents : {
        e-mail : vEmail,
        formacao : 'Superior completo'
   }
};
  • I keep getting the same information Danilo. I’ve done this test, I believe it is a variable (name) and an object (Contents)

  • Try taking out JSON.stringify or changing it to JSON.parse

  • 1

    @Danilokörber your answer is very vague, could explain how she supposedly answers the question?

Browser other questions tagged

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