user2148965
user2148965

Reputation: 52

JSON to PHP with AJAX

I want send a JSON string over to a PHP file with some user info and then insert that info into a MySQL DB.

My HTML:

<!DOCTYPE html>
<head>
    <script src="script.js"></script>
</head>
<body>
    <form name="form1" action="" onSubmit="sub()">
        <input type="text" name="username" id="usrnm" />
        <input type="text" name="password" id="pswrd" />
        <input type="text" name="firstname" id="frstnm" />
        <input type="text" name="surname" id="surnm" />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

My Javascript in script.js:

function sub() {
        var un = document.getElementById("usrnm").value;
        var pw = document.getElementById("pswrd").value;
        var fn = document.getElementById("frstnm").value;
        var sn = document.getElementById("surnm").value;
        var jsonObj = {username:un, password:pw, firstName:fn, surName:sn};
        var xmlhttp = new XMLHttpRequest();     
        xmlhttp.open("POST","server.php" ,true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("data="+encodeURIComponent(JSON.stringify(jsonObj)));
    };

My PHP:

<?php 
    $con=mysqli_connect("localhost","root","", "somedatabase");
    $data = $_POST["data"];
    $res = json_decode($data, true);
    mysqli_query($con,"INSERT INTO sometable (username,password,firstname,surname) VALUES ($res[username],$res[password],$res[firstname],$res[surname])");
    mysqli_close($con);
?>

My PHP inserts a new row into the DB when I replace the values in the insert statement with normal string values but nothing gets inserted when I try to use the values from my PHP object.

Upvotes: 1

Views: 358

Answers (2)

Martin
Martin

Reputation: 1134

Arrays using text as keys should always be quoted. e.g. $array_name['key']

therefore try changing your query line to

mysqli_query($con,"INSERT INTO sometable (username,password,firstname,surname) VALUES ($res['username'],$res['password'],$res['firstname'],$res['surname'])");

If you still have issues try testing the result of $res

print_r($res);

Upvotes: 0

Willem Mulder
Willem Mulder

Reputation: 13994

Make it like

VALUES (" . $res['username'] . "," . $res['password'] . "," . $res['firstname'] . "," . $res['surname']. ")"

Instead of directly in the string. PHP will not pick that up.

Upvotes: 1

Related Questions