I have this array of objects:
var desks = [];
function Desk(id, name, x, y) {
var desk = {};
desk.id = id;
desk.name = name;
desk.x = x;
desk.y = y;
desks.push(desk);
}
And I have a MySQL table with desk_id, desk_name, desk_x and desk_y columns.
When I click a button I want to update the values in the table with the Desk objects.
Here's basically what I'm trying achieve:
JS
$("#btn").click(function() {
$.ajax({
method: "POST",
url: "phpfile.php",
data: desks
})
});
PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require "../db.php";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$desks = $_POST("desks");
for($i = 0; $i < sizeof($desks); $i++) {
$sql = "UPDATE desks SET desk_x=$desks[i]->x WHERE desk_id=$desks[i]->id";
$conn->query($sql);
$sql = "UPDATE desks SET desk_y=$desks[i]->y WHERE desk_id=$desks[i]->id";
$conn->query($sql);
}
$conn->close();
}
?>
I don't know whats wrong with it. Any help is appreciated.
data: desksisn't going to send the data like you think (look at the request in Network tab of developer tools). Also$_POST("desks"),$_POSTis an array not a function:$_POST["desks"]var desk = {}; desk.id = id; desk.name = name; desk.x = x; desk.y = y;, you can just declare the object values like so:var desk = { id: id, name: name, x: x, y: y };