0

I'm trying to insert JSON data into MySQL using Ajax. But I don't get anything, The query isn't working.

I tried everything, and I don't know if the problem is in Ajax, PHP or in the JSON.

Where should I start looking?

JS CODE

$("#btnprueba").click(function () {
            var array1 = [];
            $("#tabla .DataRow").each(function () {

                var firstTableData = {};
                var Aidi = $(this).find('td').eq(0).text().trim();
                    firstTableData.ID_Articulo = $(this).find('td').eq(0).text().trim();
                    firstTableData.Descripcion = $(this).find('td').eq(1).text().trim();
                    firstTableData.Valor_Venta = $(this).find('td').eq(2).text().trim();
                    firstTableData.Cantidad = $(this).find('td').eq(3).text().trim();
                    firstTableData.Subtotal = $(this).find('td').eq(4).text().trim();
                    array1.push(firstTableData);

            });

            var JsonValues = JSON.stringify(array1);
                alert(JsonValues);
            $.ajax({
                type: "POST",
                url: "GuardarDatosFactura2.php",
                data: "J="+JsonValues,
                success: function(response){
                    alert(response);
                },
                error: function(e){
                    console.log(e.message);
                },

            });

        });

Json in the variable JsonValues

[{"ID_Articulo":"001","Descripcion":"Caramelos","Valor_Venta":"6500","Cantidad":"2","Subtotal":"13000"}]

PHP CODE

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

    $ID=$data->ID_Articulo;
    $Canti=$data->Cantidad;   
    $Vlr=$data->Valor_Venta;

    $cadena2 = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";
    $create2 = mysqli_query($CON,$cadena2);

    if($cadena2){
        $MSG= "Se guardaron los datos";
    }
    else{
        $MSG= "No se guardaron los datos";
    }
    echo($MSG);



?>
5
  • Your PHP is missing an opening tag. You need <?php Commented Apr 30, 2018 at 6:23
  • 2
    Also, use bind and prepared statements. It will take care of quotes, escaping characters within the data, and most importantly, it is the best defense against SQL Injection. Commented Apr 30, 2018 at 6:25
  • Thanks, i corrected the question Commented Apr 30, 2018 at 6:25
  • $data is an array of associative arrays. Commented Apr 30, 2018 at 6:31
  • To see the errors/response of ajax call. If you are using Chrome browser press F12 and got to Network Tab ->XHR. Keep error reporting on in PHP file. Commented Apr 30, 2018 at 8:03

3 Answers 3

1

Op, don't json encode your data yourself. Let jQuery handle that. Or at least pass the JSON encoded data in an object.

What you need to do is pass the data as a javascript object to jQuery. This way you can let jQuery and PHP do all the heavy lifting.

     $.ajax({
            type: "POST",
            url: "GuardarDatosFactura2.php",
            data: {J: array1},
            //    ^^ Javascript object, passing the array as raw info.
            //    This way it will be passed as an object to your php.
            success: function(response){
                alert(response);
            },
            error: function(e){
                console.log(e.message);
            },

        });

Then in PHP you can do

$data = $_POST['J'];

PHP should have transformed it already to a native php object/array.

Just do a var_dump($data); die(); to see what it has become.

If your object is very deeply nested php might not autodecode it. Then encode it and pass the encoded var.

data: {J: JSON.stringify(array1)},

and in php

$data = json_decode($_POST['J'], false);

Notice, not asked, but need to know!

You are using unprepared variables in your sql.

"INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";

this is bad. If your website will become front facing, Anyone can then dump your database, read out your database and wreak havoc on your database because you're providing them direct access to your internals.

Please use prepared statements and never, ever use a query without prepared statements. Also you're not counting for duplicate keys. If a product already exists it should be updated, not re-inserted.

if ($stmt = $mysqli->prepare("INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES (?,?,?) ON DUPLICATE KEY UPDATE Cantidad=?, ValorVenta=?")) {
      $stmt->bind_param("i", $ID);
      $stmt->bind_param("s", $Canti);
      $stmt->bind_param("s", $Vlr);
      $stmt->bind_param("s", $Canti);
      $stmt->bind_param("s", $Vlr);

      mysqli_stmt_execute($stmt);
}
Sign up to request clarification or add additional context in comments.

Comments

1

This will help you, check I have loop over your received json in post request and generated insert query using for loop to create a single insert statement

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

$comma = "";
$query = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ";
foreach ($data as $key => $value) {
    $ID = mysqli_real_escape_string($CON, $value->ID_Articulo);
    $Canti = mysqli_real_escape_string($CON, $value->Cantidad);
    $Vlr = mysqli_real_escape_string($CON, $value->Valor_Venta);
    $query .= $comma . "('$ID','$Canti','$Vlr')";
    $comma = ",";
}

$create2 = mysqli_query($CON, $query);

if($cadena2){
    $MSG= "Se guardaron los datos";
}
else{
    $MSG= "No se guardaron los datos";
}
echo($MSG);
?>

Comments

0

You have to get the array values from json decoded data like this :

<?php 
header("Content-Type: application/json; charset=UTF-8");

$CON = mysqli_connect("localhost","root","","BDfactura") or die ("error");

$data = json_decode($_POST['J'],false);

    $ID=$data[0]->ID_Articulo;
    $Canti=$data[0]->Cantidad;   
    $Vlr=$data[0]->Valor_Venta;

    $cadena2 = "INSERT INTO ItemXVenta (IdArticulo, Cantidad, ValorVenta) VALUES ('$ID','$Canti','$Vlr')";
    $create2 = mysqli_query($CON,$cadena2);

    if($cadena2){
        $MSG= "Se guardaron los datos";
    }
    else{
        $MSG= "No se guardaron los datos";
    }
    echo($MSG);



?>

3 Comments

i have made the changes, and still without working :/
can you please print the $data array and show the output?
Hi, the output is: [object Object] using a: echo json_encode($data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.