Insert into mysql with php and ajax function

Asked

Viewed 31 times

0

I created the fields to be filled with the following html:

<!DOCTYPE html>
<html lang="PT-pt">
    <head>
        <meta charset="utf-8" />
        <title>Código de Barras</title>
    </head>
    <body>
    <div class="container shadowbox" style="width:700px;">  
   <h3 align="center"><strong>Registo de Atividades Diárias</strong></h3>  
   <br />  
</div>
<div> 
<input type="text" id="codigo" name="codigo" value="<?= $_GET['codigo'] ?>" />  
<div class="form-group">
<label class="col-md-4 control-label" for="IniciarTarefa" id="acao"></label>
<div class="col-md-4">
<button type="button" id="IniciarTarefa" name="IniciarTarefa" class="btn btn-info" onclick="myFunction()">Iniciar Tarefa</button>
</div>
</div>
<input type="hidden" id="IniciarTarefa1" name="IniciarTarefa"/>
<input type="hidden" name="Colaborador" id="Colaborador" value="xxxxxx">
<div class="form-group">
<label class="col-md-4 control-label" for="PequenoAlmoco" id="acao"></label>
<div class="col-md-4">
<input type="hidden" id="PequenoAlmoco" name="tarefa" value="Pequeno Almoço">
</div>
</div>
<button class="btn btn-info" onclick="inserir_registo()">Pequeno Almoço</button>
</div>


<script type="text/javascript">
function myFunction() {
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
document.getElementById("IniciarTarefa1").value = dateTime;
}

function inserir_registo()
{

    var dadosajax = {
        'codigo' : $("#codigo").val(),
        'IniciarTarefa1' : $("#IniciarTarefa1").val(),
            'Colaborador' : $("#Colaborador").val(),
        'PequenoAlmoco' : $("#PequenoAlmoco").val()
    };
    pageurl = './conexaoteste';
    $.ajax({
        url: pageurl,
        type: 'POST',
        cache: false,
        error: function(){
            alert('Erro: Inserir Registo!!');
        },
        success: function(result)
        { 
            if($.trim(result) == '1')
            {
                alert("O seu registo foi inserido com sucesso!");
            }
            else
            {
                alert("Ocorreu um erro ao inserir o seu registo!");
            }
        }
    });
}
</script>

But when I insert it into the database I get the following error on the console:

teste2? preview=true:363 Uncaught Referenceerror: in_register is not defined At Htmlbuttonelement.onclick

php:

$codigo = $_REQUEST["codigo"]; 
$IniciarTarefa = $_REQUEST["IniciarTarefa"];
$tarefa = $_REQUEST["tarefa"];
$Colaborador = $_REQUEST["Colaborador"];    

try
    {
$sql = "INSERT INTO teste (`codigo`, `IniciarTarefa`, `tarefa`, `FimTarefa`, `Colaborador`)
VALUES ('".trim($codigo)."', '".trim($IniciarTarefa)."', '".trim($tarefa)."', '".date('Y-m-d H:i:s')."', '".trim($Colaborador)."')";

$result = mysqli_query( $conn, $sql);

echo "1";
    } 
    catch (Exception $ex)
    {

        echo "0";
    }
  • looks like it didn’t even load the file with the function, is a separate html file? is included in the header?

  • @Ricardo Pontual the function is in the same HTML file and is following the HTML, is not in the page header, but has to be?

  • Iae, Bruno. This error is returned when the function has not been loaded. Can you [Edit] the question and post your HTML with the embedded script, as you mentioned? Note that even here on the site it is not returning this error... How is your tag script?

  • @Lipespry edited the question with the code exactly as it is on my page

  • 1

    Here worked normally after adding the jQuery lib: <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>. I put her inside the head. Test there.

  • don’t need to be in the head, but it is good practice to put the scripts before, unless you want it to run at the end, but also lack the reference to the jQuery, as @Lipespry commented

  • I just don’t agree with this statement: "but it is good practice to put the scripts before". The ideal is to put according to the order of use and requirement. Putting a lib that will only be used "through user action" before loading the HTML will only delay the rendering of the HTML. Always respecting the requirements: if a script needs jQuery, it should come after jQuery... kk

  • @Lipespry added the library and changed the order of the JavaScript and no longer returned the error, but I receive the log message in the database successfully, but it is not entering in the database table.

  • It turns out there is a lot of error in your code. This makes the question "broad". Starting with the part that your ajax is not sending the data in the request... You have set the variable dadosajax, but ajax does not send it to PHP...

  • @Lipespry within the variable dadosajaxis only sending the value of input with the id="pequenoalmoco". Mistakes are within the ajax or in HTML

  • 1

    You need to put the data in ajax: data: dadosajax, ...

  • @Lipespry, you mean you think it’s good to put scripts in the middle of html? The best option would be an external file, because it can still benefit from the cache when loading in the browser, now if it goes inline in the document, it would be better to organize everything in the head, or as I mentioned, by at the end what can be loaded after the load.

  • @Ricardo Considero "good" always load the scripts last (at the end of the DOM), but some are necessary before. Either in the body or in the header (head). It is a matter of optimization. The same goes for images. You can place a thumbnail in src and an attribute data-img. Then when you finish loading the DOM, you will render the original images by taking data-img. This is all about optimization. It doesn’t mean that it HAS to be so. You can load your scripts in the quiet header. But maybe it can generate a nice delay "in the first rendering...

  • 1

    @Lipespry Thanks for the tips, already corrected the mistakes I had in my code, both in HTML as ajax and already works as intended

Show 9 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.