necesito transferir una variable de js a una página php y luego insertarla en la base de datos
el codigo js
function tableText(tableCell) { var x =tableCell.innerHTML; console.log(x); }
también probé el ajax
function tableText(tableCell) { var x =tableCell.innerHTML; console.log(x); $.ajax({ type: 'POST', url: 'try.php', data: x , complete: function(text){ return text; } }); }
no estoy seguro si lo hice bien y no sé cómo llamarlo en la página php
Entonces, ¿cómo obtener una variable de JavaScript a PHP?
Pruebe este: (Editar, conjunto de explicaciones json)
function tableText(tableCell) { var x =tableCell.innerHTML; console.log(x); $.ajax({ type: 'POST', url: 'try.php', dataType: "json", data: { x:x }, complete: function(text){ return text; } }); } function tableText(tableCell) { var x =tableCell.innerHTML; console.log(x); $.ajax({ type: 'POST', url: 'try.php', dataType: "json", data: { x:x }, success : function(text){ $('#MyDiv').html(text); } }); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Puede recuperar por $_POST['x']
como una publicación normal.
Para el retorno en php necesitas usar echo json_encode(['text'=>'ok']);
.
No está enviando sus datos correctamente con ajax, su ajax debería verse así
Editar: agregue una alerta dulce para mostrar un mensaje atractivo después de su inserción
function tableText(tableCell) { var x =tableCell.innerHTML; console.log(x); $.ajax({ type: 'POST', dataType: 'json', url: 'try.php', data: { x:x }, success: function(text) { //SWAL Swal.fire( 'Success!!', text, 'success' ) } }); } <!-- SWEET ALERT --> <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
y en su archivo try.php
<?php $_REQUEST['x'];//here you receive what you send thru ajax //here goes your insert echo json_encode('insert was successfull')//this msg is what you will see when you return text ?>