Error entering data into database with Jquery and Ajax

Asked

Viewed 120 times

0

This code snippet always returns ERROR: 200. It is entering the data into the database normally, but returns error in the interface.

    $("#registrar").click(function(){
        $.ajax({
            url : "registra.php",
            method: "POST",
            dataType : "json",
            data : {participante1 : $("#participante1 option:selected").val(),
                    participante2 : $("#participante2 option:selected").val(),
                    score1 : $("#score1").val(),
                    score2 : $("#score2").val()},

            success : function(resp){
                alert("Registro efetuado com sucesso!");
            },

            error : function(err){
                alert("ERRO: " + err.status);
            }
        });
    });

PHP code:

<?php 
    $con = pg_connect("host=localhost port=5432 dbname=Jogos user=postgres password=postgres");
    $participante1 = $_POST['participante1'];
    $participante2 = $_POST['participante2'];
    $score1 = $_POST['score1'];
    $score2 = $_POST['score2'];
    $comando = "INSERT INTO disputas (participante1, participante2, score1, score2) 
                VALUES ('$participante1', '$participante2', '$score1', '$score2')";
    pg_query($con, $comando);
    pg_close($con);
?>
  • Strange the error code is 200, but try to add in PHP the line: http_response_code(200) and see if anything changes.

  • Hasn’t changed at all, keeps showing the same mistake.

  • Ok, you set the response to be JSON, but PHP does not return a valid JSON. It probably works if you change to text or make PHP return a valid JSON.

  • I switched to text and it worked. Thanks a lot for the help.

1 answer

1


This behavior happens when you set the expected return to JSON in:

dataType : "json"

however the server does not return a valid JSON. This way, jQuery, when analyzing the return, considers that there was an error and triggers the function error, even with the return 200 HTTP code. To fix this, simply modify the return type to text or make PHP return a valid JSON.

I mean, do:

$("#registrar").click(function(){
    $.ajax({
        url : "registra.php",
        method: "POST",
        dataType : "text",
        data : {participante1 : $("#participante1 option:selected").val(),
                participante2 : $("#participante2 option:selected").val(),
                score1 : $("#score1").val(),
                score2 : $("#score2").val()},

        success : function(resp){
            alert("Registro efetuado com sucesso!");
        },

        error : function(err){
            alert("ERRO: " + err.status);
        }
    });
});

Browser other questions tagged

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