javascriptphpjsondatabasetransmitfile

JSON in PHP can't transmit Strings


Solved Hello everyone I want to transmit an json from php to an js file and id works. However if I want to transmit an String in the Json it doesn't work. The Debuger says JSON Parse error: Unexpected identifier "Test" if you know an other way id would be great also.

<?php
$con = mysqli_connect('','root','','JobBlocks');
$sql = "SELECT * FROM JobBlocksDaten";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
$DB_inhalt = mysqli_fetch_assoc($res);
$datenzUE = "{\"name\": Test, \"age\": 31,}";
echo $datenzUE;
?>

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <script type="text/javascript" src="jQuery.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    $("#sub").click(function(){
    $.ajax({
    type: "POST",
    url: "http://localhost/jQuery&PHPnew/tst.php",
    success: function(data){
    alert(data);
    var Daten = JSON.parse(data);
    alert(Daten.name);
    alert(Daten.age);
    }
    })
    })
    })

    </script>
    </head>
    <body>
    <button id="sub">Submit result</button>
    <main id="main">
    </main>
    </body>
    </html>

Solution

  • JSON strings need to be quoted, and the last element can not have a trailing comma, so you'd need this:

    $datenzUE = "{\"name\": \"Test\", \"age\": 31}";
    

    But that's a bad idea. You're best off using json_encode(), which will do all the quoting and escaping for you:

    $array = ['name' => 'Test', 'age' => 31];
    $datenzUE = json_encode($array);