0

Now I know this has been asked before, but none of the responses have offered up insight for me to date;

I have an HTML page with the script below (ultimately I shall use this script to suck data out of an app), basically testing to send some data in JSON format to a PHP page which is to populate a MYSQL database with the record.

My problem is that I get no table record update. Nada.

This has been messing me around for a few weeks now; the closest I have got is:

Send JSON data from Javascript to PHP?

My limited success to date has been to grab data from a .json file and update the database that way on a php page. So, the JSON is fine in the script, and the connection to the database is ok. I just don't seem to be able to pass it from an html page to php and populate the db. I cannot understand why this has to be that difficult.

Any suggestions/pointers would be appreciated (I need to keep this simple as I am a relative novice). Thank you in advance.

HTML page script

    <script>
    var jsonQuizData = {};
    var qID = '9';
    var learnersName = 'Bart Bundy';
    var learnersEmail = 'bbundy@blue.com';
    var quizName = 'SomeQuiz99';
    var quizScore = '33%';
    var result1 = 'Some blob data goes in here?';
    var dbString, request; 
 
    jsonQuizData = '{ "id":qID, usersName":learnersName,  "usersEmail":learnersEmail,  "quizTitle":quizName, "qScore":quizScore, "Output1":result1 }';

    dbString = JSON.stringify(jsonQuizData);

    request = new XMLHttpRequest();
    request.open("POST", "process.php", true);
    request.setRequestHeader("Content-Type", "application/json"); 
    request.send(dbString);
    </script>

process.PHP page

<?php
    header("Content-Type: application/json; charset=UTF-8");

    //Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection etc. performed here

    $data = json_decode(file_get_contents("php://input"));

    $id = $data['id'];
    $name = $data['usersName'];
    $email = $data['usersEmail'];
    $qtitle = $data['quizTitle'];
    $result1 = $data['Output1'];
    $qScore = $data['score'];

    //insert into mysql table
    $sql = "INSERT INTO quiz01(quiz_id, quiz_title, fName, eMail, quiz_score, q1_answer)
    VALUES('$id', '$qtitle', '$name', '$email', '$qScore', '$result1')";

    if(!mysqli_query($conn,$sql))
    {
    die('Error : ' . mysqli_error($conn));
    }
    else
 {
 echo "Data inserted successfully";
 }

    //Close connection
    /?>

.... Brick wall time

user4020527
  • 1
  • 8
  • 20
  • Where have you defined your database connection variables like $servername? – jhilgeman Jan 14 '18 at 01:19
  • Any specific reason why you are using `file_get_contents("php://input")` instead of the `$_POST` variable that should be passed in? Add `print_r($_POST);` to the top of your php and watch what it spills out when your XMLHttpRequest hits it (network tab in browser). Side note: this is all super easy utilizing jquery .ajax. – IncredibleHat Jan 14 '18 at 02:37

2 Answers2

0

Your stringify portion in your sample is not right, it's already a string, so I think you mean to do:

var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy@blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
// Here you have to stringify the data object, not a string of the data object.
jsonQuizData = JSON.stringify({"id":qID, "usersName":learnersName, "usersEmail":learnersEmail,  "quizTitle":quizName, "qScore":quizScore, "Output1":result1});

request = new XMLHttpRequest();
request.open("POST", "process.php", true);
// Send the regular form header
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        alert(this.responseText);
    }
};
// Now when it sends, it should send it properly as a post
request.send('json='+jsonQuizData);

Then in the PHP, you don't need to send the line:

header("Content-Type: application/json; charset=UTF-8");

and you can alter this line:

$data = json_decode(file_get_contents("php://input"));

to just:

$data = json_decode($_POST['json'],true);

It should now all be in the regular $_POST, then you need to bind parameters when you insert.

Rasclatt
  • 12,498
  • 3
  • 25
  • 33
  • Hi guys, getting pretty late now; still no success...... Tips much appreciated. I'm still hammering away. All the best. – Stonker Baksteen Jan 16 '18 at 00:49
  • Also, you may want to consider doing jQuery AJAX, it is very easy and very straight-forward. It's about as easy as it gets when it comes to ajax. – Rasclatt Jan 16 '18 at 01:23
  • A huge thank you to Rasclatt for your patience. Silly error in my workings, I had omitted a ; semicolon in the script. Silly me. Once again, thank you – Stonker Baksteen Jan 22 '18 at 22:56
0

Update: Right, got it working doing the following:

HTML page

<script>
var jsonQuizData = {};
var learnersName = 'Professor T';
var learnersEmail = 'prof.teerlink@pooh.com';
var quizName = 'TidlyWinks101w';
var quizScore = '100%';
var result1 = 'Balls said the crow';
var dbString, request;  

jsonQuizData = JSON.stringify({"quizTitle":quizName, "usersName":learnersName, "usersEmail":learnersEmail, "qScore":quizScore, "Output1":result1 });

$(document).ready(function()
{
$("button").click(function()
    {
    $.post("working01.php", 'json='+jsonQuizData, 
    function(data,status)
        {
        //alert("Data: " + data + "\nStatus: " + status);
        document.getElementById("AV1").innerHTML = data;
        });
    });
});
</script>

And PHP page...

<?php
//Set up connections to database etc...

if (isset($_POST['json'])) 
{
$str = $_POST['json'];
$contents = json_decode($str);
$qtitle = $contents->quizTitle;
$name = $contents->usersName;
$email = $contents->usersEmail;
$qScore = $contents->qScore;
$result1 = $contents->Output1;
}
$sql = "INSERT INTO quiz01(quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$qtitle', '$name', '$email', '$qScore', '$result1')";

if(!mysqli_query($conn,$sql))
{
    die('Error : ' . mysqli_error($conn));
}
else
{
    echo "Data inserted successfully";
}

//Close connections
?>

But so want to do it utilising the XMLHttpRequest() object and send the json. as per Rasclatt. Thanks