简体   繁体   中英

AJAX send multiple variables, including JSON, to php for database insert

I am trying to send two variables to my PHP file to insert them into a database. One variable is called 'skuLabel', which is just text and the other is 'jsonString', which is a JSON representation of a canvas design. When I just try to send the 'skuLabel', it works fine and inserts it like I would expect. But, when I send either just the 'jsonString' or both, my PHP errors that the two indexes do not exist when I try to access them. I've been working on this for several days now, trying many different methods, all with the same result. This is my first attempt at using AJAX, so I am sure I am doing something simple wrong. I appreciate any help anyone can give!

Here is my code:

var skuLabel = document.getElementById('sku').value;
var jsonString = JSON.stringify(canvas.toDatalessJSON());
$.ajax({
    type:   'POST',
    url:    'uploadDesign.php', 
    dataType: 'json',
    data:   {sku: skuLabel, json: jsonString},
    success: 
            function(data){
                alert(data);
            }
});

And PHP:

$sku = $_POST['sku'];
$jsonData = $_POST['json'];
if($mysqli->query("INSERT INTO designs (sku, jsonData) VALUES($sku, $jsonData)")===TRUE){
    printf("Inserted successfully.\n");
}
if($stmt = $mysqli->prepare("INSERT INTO designs (sku, jsonData) VALUES(?, ?)")){
    $stmt->bind_param('ss', $sku, $jsonData);
    $stmt->execute();
    $stmt->close();
}

This fixed it. Thanks, Quentin!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM