Request jQuery Post + PHP + Mysql does not save data

Asked

Viewed 405 times

1

I am making a registration via jQuery Ajax, so I created the following function:

function salvarCadastro(titulo, form, caminho) {
    var dadosFormulario = $("#" + form).serialize();

    var myData = $("#" + form).serialize();
    jQuery.ajax({
        type: "POST",
        url: caminho,
        dataType: "text",
        data: myData,
        cache: false,
        success:function(response){
            data = data.trim();
            if (data == 'S') {
                alert('Dados registrados com sucesso.');
            } else {
                alert('Não foi possivel registrar os dados!');
            }
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert('Houve um prolema de requisição ao ' + titulo');
        }
    });

    return false;
}

In my php file it looked like this:

<?php
    session_start();
    $mysql = new mysqli('localhost', 'root', '', 'teste');

    $id        = $_POST['id'];
    $ordem     = $_POST['ordem'];
    $descricao = utf8_decode(trim($_POST['descricao']));

    $sql = "UPDATE dados SET ordem = '$ordem', descricao = '$descricao' WHERE id = $id";

    $mysql->query($sql);
    if (empty($mysql->error)) {
        echo "S";
    } else {
        echo "N";
    }
    $mysql->close();
?>

If I perform a post directly from the form to the PHP file it returns me "S" the same occurs via Ajax, however via Ajax it does not save the information in the database.

  • Also add your HTML to the question. It might be something there.

  • I would say that this is impossible, are sure that AJAX is running the same URL that you are running directly?

  • Are you sure the data is being passed via AJAX? I have never used dataType: "text", but rather 'json'... Try. What is date? Where did you get this variable? data = data.trim(); You are not using the return in ajax anywhere (sponse)... This return should be in your comparison.

  • See if the data is actually arriving in the script via ajax. I think the error can only be at this point.

1 answer

1

There is an easier way than I use. Try in PHP code, instead of "S" and "N" put echo "<script> alert ('mensagem'); <\script>"; or is something in the query string.

I do it like this and it always worked.

 $sql = "UPDATE dados SET ordem = '".$ordem."', descricao = '".$descricao."' WHERE id = ".$id;

Browser other questions tagged

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