1

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.

4

2 Answers 2

1

Do like this
JS

$("#btn").click(function() {
    $.ajax({
        method: "POST",
        url: "phpfile.php",
        data: {desks:desks}
    })
});

PHP

$desks = $_POST("desks");
$sql = "UPDATE desks SET desk_x=$desks->x,desk_y=$desks->y WHERE desk_id=$desks->id";
$conn->query($sql);
Sign up to request clarification or add additional context in comments.

Comments

0

You need the stringify the array when you send it.

JS

$("#btn").click(function() {
    $.ajax({
        method: "POST",
        url: "phpfile.php",
        data: { "desks" : JSON.stringify(desks) }
    })
});

PHP

$desks = json_decode($_POST["desks"]);

foreach($desks as $key => $value) {
    $sql = "UPDATE desks SET desk_x=".$value->x.",desk_y=".$value->y." WHERE desk_id=".$value->id;
    $conn->query($sql);
}

Comments

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.