Gurami
Gurami

Reputation: 82

Send JSON data to MySQL database?

I need to send JSON data to a MySQL database, but when I am trying to do this, my code only sends "{"0":"A" to the MySQL database.

Here is my code:

JavaScript

<span id="start_button_container">Send and start</span>

const allCards = {
    '0':'A &#9830;','1':'A &#9829;','2':'A &#9827;','3':'A &#9824;',
    '4':'10 &#9830;','5':'10 &#9829;','6':'10 &#9827;','7':'10 &#9824;',
    '8':'K &#9830;','9':'K &#9829;','10':'K &#9827;','11':'K &#9824;',
    '12':'Q &#9830;','13':'Q &#9829;','14':'Q &#9827;','15':'Q &#9824;',
    '16':'J &#9830;','17':'J &#9829;','18':'J &#9827;','19':'J &#9824;'
};

let userInTable = localStorage.getItem( 'saved_user' );
if (userInTable) { // Save user and find table onclick START
    saveUser.style.display = 'none';
    hello.textContent = "Hi " + userInTable;
    start.onclick = () => {
        if (userInTable) {
            let x = new XMLHttpRequest();
            let url = "php/findtable.php";
            let data = JSON.stringify(allCards);
            let params = "cards="+data+"&user="+userInTable;
            x.open("POST", url);
            x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            x.send(params);
            x.onreadystatechange = () => {
                if (x.readyState == 4 && x.status == 200) {
                    console.log(x.responseText);
                }
            }
        }
    }
}

Here is my PHP code:

if (isset($_POST["cards"],$_POST["user"])) {
    $cards = $_POST["cards"];
    $user = $_POST["user"];
    $query = "INSERT INTO tables (u_1,all_cards) VALUES (?,?)";
    if ($stmt = $conn->prepare($query)) {
        $stmt->bind_param("ss", $user, $cards);
        if ($stmt->execute()) {
            print_r($cards);
        }
    }
}

What am I doing wrong?

Upvotes: 1

Views: 1710

Answers (2)

Gurami
Gurami

Reputation: 82

The encodeURIComponent() function helped me a lot:

let data = JSON.stringify(encodeURIComponent(allCards));

Upvotes: 1

Roboroads
Roboroads

Reputation: 1709

If you/somebody still want to know why this happens, every ampersand (&) is a new input in a querystring. Meaning var1=value&var2=value&var3=value. Your JSON contains ampersands, so the parser thinks you are starting a new variable.

var1=value&var2={"a":"&2934;"}
                      ^ This one starts a new variable

var2 contains {"a":"1 and processes 2934;"} as a new variable name.

encodeURIComponent escapes the ampersands, so the query string parser does not use it for division of variables.

Upvotes: 0

Related Questions