data record via ajax

0

I'm trying to make data records by ajax and the data is not going to BD . I did a direct test between html and php and it worked, but html , ajax and php will not. HTML:

<form method="post">

AVERAGE MONTHLY SALE Sale S / Margin

Follow the code JQ with ajax :

$(document).ready( function(){

    $("#salvar").click( function(){

        var dataString = $("form").serialize();

        $.ajax({
            url: 'php/salvarCustos.php',
            type: 'POST',
            dataType: 'json',
            data: dataString,

            success: function(data){
                alert(JSON.stringify(data));
                if(data.status == 1){
                    $("#msg").val(data.status);
                    $("#msg").show();
                }
                if(data.status == 2){
                    $("#msg").val(data.status);
                    $("#msg").show();
                }
            },

            error: function(data){
                alert(data);
            }
        });
    });
})

PHP:

@$vendaMediaMensal = $_POST['vendaMediaMensal'];
@$vendaSemMargemPercentual = $_POST['vendaSemMargemPercentual'];
$vendaMediaMensal = floatval(str_replace(',', '.', str_replace('.', '', $vendaMediaMensal)));
$vendaSemMargemPercentual = floatval(str_replace(',', '.', str_replace('.', '', $vendaSemMargemPercentual)));
$qryConsulta = mysql_query("SELECT * FROM custos");
$qryNum = mysql_num_rows($qryConsulta);

if($qryNum == 0){
    $qryInsere = "INSERT INTO custos VALUES('$vendaMediaMensal','$vendaSemMargemPercentual')";
    $insere = mysql_query($qryInsere);
    echo json_encode( array('status' => 1, 'msg' => 'Cadastro efeutado com sucesso!'));
}else{
    $qryAtualiza = "UPDATE custos SET vendaMediaMensal='$vendaMediaMensal'";
    $atualiza = mysql_query($qryAtualiza);
    echo json_encode( array('status' => 2, 'msg' => 'Atualização efeutada com sucesso!'));
}
    
asked by anonymous 06.06.2015 / 05:52

2 answers

1

I see a problem in the query. It is necessary to indicate the fields where these values will be inserted.

It should be:

"INSERT INTO custos ('campo1','campo2') VALUES ('$vendaMediaMensal','$vendaSemMargemPercentual')";
    
06.06.2015 / 11:51
0

This should be because you are setting up your ajax to send json, only with the code below:

var dataString = $("form").serialize();

... you are sending "application / x-www-form-urlencoded" (in terms of formatting it is the same as in the querystring of a url).

You should pass an object (or JSON) in the "data" attribute:

data: { atributo: "Valor" }

And in PHP you could get the data like this:

$body = json_decode(file_get_contents('php://input'));
echo $body->atributo;

Or ... You can simply leave everything as is and remove the "dataType" attribute. In that case it will work like submit without ajax.

    
07.06.2015 / 04:33