0
I got the following JSON
, that I create by the method JSON.stringify(dados
), and walkthrough ajax
to the php
:
{"nome":"nome_da_pessoa", "registro":"registro_da_pessoa", "departamento":"_$oid/5aac50..."}
When I receive it in PHP, I do the conversion by json_decode($_POST['dado']);
.
I would like to iterate this array, and when I find the value _$oid/, separate and update the item only with the part after the /.
For example: dado[departamento] = "5aac50..."
Follow the codes that aren’t working.
Js Code:
var dados = {};
$("form input").each(function () {
var campo = $(this).attr("name"), valor = $(this).val();
dados[campo] = valor;
});
$("form select").each(function () {
if ($(this).attr("carrega") == "s") {
var campo = $(this).attr("name"), valor = "_$oid/" + $(this).val();
dados[campo] = valor;
} else {
var campo = $(this).attr("name"), valor = $(this).val();
dados[campo] = valor;
}
});
dados["excluido"] = "n";
dados["logado"] = "n";
var dado = JSON.stringify(dados);
$.ajax({
url: 'funcoes/registros.php',
data: {
"funcao": "incluidado",
"collection": collection,
"dado": dado
},
type: 'post',
dataType: 'json',
cache: false,
beforeSend: function (xhr) {
},
error: function (jqXHR, textStatus, errorThrown) {
},
success: function (dados) {
preenchetabela(collection);
}
});
PHP code:
$collection = $_POST['collection'];
$dado = json_decode($_POST['dado']);
// CONSEGUIR ALTERAR O $oid_
foreach ($dado as $key => $value) {
$procura = '_$oid/';
if (strripos($value, $procura) === false) {
// não altera nada
} else {
// remove o _$oid do valor
$tags = explode($procura, $value);
$dado[$key] = $tags[1];
}
}
try {
$insert = new MongoDB\Driver\BulkWrite; // Monta o BulkWrite
$insert->insert($dado);
$conexao->executeBulkWrite($bd . "usuarios", $insert);
echo json_encode("Registro realizado com sucesso!");
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
This is not clear, much code but it does not go straight to the point. Quall the doubt actually?
– felipsmartins
Excuse the lack of clarity. In fact it is difficult to explain everything. My intention is to create a JS library that allows you to follow patterns for creating forms, without having to keep developing a function for each form. I am scanning the patterns and when I find a select field that has been populated with Collection results, I am adding _$oid/ before its _id to be able to turn into Objectid and refer it to coutra Collection. I don’t know if it was clear, but the code worked as the changes I commented in the answer below. Vlw for help!
– Diego de Lima