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 the following:
- Collect data from
form
: Look at this post about serializeArray()
- Convert them to JSON format: Explained below
- Send them via AJAX to PHP
- In the PHP script convert them to array with
json_decode()
and save in comic
- If you get a successful PHP response, insert the item in 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 see more in that post or in the documentation jQuery.
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’ve helped.
EDITION
In the STEP 3, to ensure that the data passed is in JSON format, you can use the function JSON.stringify
Javascript. What it does is convert the argument passed to it to a JSON string - which is expected by its name hehe. Still, add contentType: "application/json"
the options object passed to the function $.ajax
. So:
$.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();
}
});
In the STEP 4, the correct 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
will be empty since the content-type
of the request (read more here) will be application/json
(passed by the ajax function) which is not supported by the variable $_PHP
according to your documentation.
A problem caused by this (and which may not make a difference to most cases) is that php://input
will not be available if the form
be sent using enctype="multipart/form-data"
which means it won’t be possible to include, for example, image uploads. For your case, there doesn’t seem to be any problems since you will only send texts.
It is quite wide your question. Not that it is not good. A solution, quite used, would be to use AJAX. With javascript you "call" a php file that saves this data and updates a div. As if it were a "chat". Give a search, have many examples on the internet. If you have a more specific problem there you post it here it will be easier to help you.
– Andrei Coelho
I guess I couldn’t explain myself, I found some examples, but I’m really not good with js and I wanted to continue writing code that I can understand. Basically I want to perform a query and save in the database each time the user enters something in this field. I already found "n" examples, even at the moment I’m trying, <script> $("input[name=domain_input]"). keypress(Function(){ $.post( "<?=base_url()?>Protocol/add_domain", { given: $("input[name=domain_input]").val() } ); }); </script> but I still can’t get the table data right.
– Guto G
I get it. Put this code you mentioned here, in the question. It will help someone to answer you. I have saved here in the favorites.
– Andrei Coelho
If no one answers by tomorrow. I’ll make an example for you.
– Andrei Coelho
I appreciate the help, buddy, have a great night.
– Guto G