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:
REFERENCE:
Ajax Form Data
Thanks for the help Taffarel. It really was JSON.stringify. Thank you!
– Luiz Henrique