The question does not include jQuery but using this framework sometimes makes the work easier, so one way you could do what you want is as follows:
Collect data from form
: Look at this post on serializeArray()
Convert them to JSON format: Explained below
Sending them via AJAX to PHP
In PHP script convert them to array with json_decode()
and save in BD
If you get PHP's successful response, insert the item on the page.
OBS:
STEP 1
The data collected from the form with serializeArray()
will be in the following format
[ { name: "domain-input", value: "meuConteúdo" },
{ name: "domain-input2", value: "conteúdo qualquer" }
]
STEP 2
var unindexed_array = $("form").serializeArray(); // Coleta os dados do form
var jsonData = {}
$.each(unindexed_array, function(i, item) {
// Para cada item em 'unindexed_array', fazer o que está aqui dentro.
jsonData[item["name"]] = item["value"]; // salva
});
After that, jsonData
will be in the following format (JSON):
jsonData = {
"domain-input" : "meuConteúdo",
"domain-input2" : "conteúdo qualquer"
}
STEP 3
$.ajax({
data: jsonData, // dados a serem enviados
dataType: "json", // Formato do dado **recebido como resposta do servidor**. html, json, text ...
method: "post", // post ou get
url: "myPHPscript.php", // url invocada
success: function(data, textStatus, jqXHR) {
// Executado em caso de sucesso.
alert(data+" "+textStatus+" "+jqXHR+" ");
},
error: function (jqXHR, textStatus, errorThrown) {
// Executado em caso de erro.
alert(jqXHR+" "+ textStatus+" "+ errorThrown);
error();
}
});
You can view more in this post or jQuery documentation .
STEP 4
Receive data in PHP with json_decode()
.
PHP file:
$domain-input = json_decode($_POST["domain-input"], true);
$domain-input2 = json_decode($_POST["domain-input2"], true);
// Salva no BD
if (sucesso) {
$resposta_array['status'] = 'success';
} else {
$resposta_array['status'] = 'error';
}
echo json_encode($resposta_array);
I hope I have helped.
EDITION
In STEP 3 , to ensure that past data is in JSON format, you can use the JSON.stringify
function of Javascript. What it does is convert the argument passed to it into a JSON string - which is to be expected by its hehe name. Also, add contentType: "application/json"
to the options object passed to the $.ajax
function. Then:
$.ajax({
contentType: "application/json",
data: JSON.stringify(jsonData), // dados a serem enviados agora com a certeza de estarem em JSON.
dataType: "json", // Formato do dado **recebido como resposta do servidor**. html, json, text ...
method: "post", // post ou get
url: "myPHPscript.php", // url invocada
success: function(data, textStatus, jqXHR) {
// Executado em caso de sucesso.
alert(data+" "+textStatus+" "+jqXHR+" ");
},
error: function (jqXHR, textStatus, errorThrown) {
// Executado em caso de erro.
alert(jqXHR+" "+ textStatus+" "+ errorThrown);
error();
}
});
STEP 4 , the correct one would be
header('Content-Type: application/json; charset=utf-8'); // Altera o cabecalho para que o retorno seja em JSON
$aDados = json_decode(file_get_contents("php://input"), true); // Ver comentário abaixo.
// Verificar se foi recebido dados
// Usar assim: $aDados['domain-input']
// Salvar no BD
if (sucesso) {
$resposta_array['status'] = 'success';
} else {
$resposta_array['status'] = 'error';
}
echo json_encode($resposta_array); // Converte para JSON e imprime na página.
The expression file_get_contents("php://input")
is used to collect data sent by AJAX because $_POST
is empty since content-type
of request ( read more here ) will be application/json
(passed by the ajax function) which is not supported by the variable $_PHP
according to its documentation .
A problem caused by this (and that may not make a difference for most cases) is that php://input
will not be available if form
is sent using enctype="multipart/form-data"
which means that it will not be possible to include example, image uploads. For your case, there do not seem to be any problems as you will only submit texts.