1

I am trying to send some data from a JavaScript program to a MySQL database using a PHP file (using PDO). I had gotten it to work a few months ago, but I accidentally deleted the file containing the save_data() function I use to send the data from the JavaScript file to the PHP file, and I can't get it to work anymore.

Here is my save_data function:

function save_data(expData){
    data = JSON.stringify(expData)
    $.post('./saveData.php',data,function(response){
        console.log("Response: "+response);
    })
}

And here is my PHP file:

<?php
$pdo = new PDO("mysql:host=host;dbname=name;",'admin','p');

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

$pdo->prepare("INSERT INTO `response` (`ip`, `complete_sequence`, `total_wins`, `key_presses`, `run_length`, `subject_condition`, `time_elapsed`, `total_answered`, `total_forfeits`, `total_losses`, `total_missed`, `total_paper`, `total_rock`, `total_scissors`, `total_ties`, `run_test_part_one`, `run_test_part_two`, `run_test_part_three`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")->execute([
$_SERVER['REMOTE_ADDR'],
$data['completeSequence'],
$data['totalWins'],
$data['key_presses'],
$data['runLength'],
implode (", ", $data['SubjectCondition']),
$data['time_elapsed'],
$data['totalAnswered'],
$data['totalForfeits'],
$data['totalLosses'],
$data['totalMissed'],
$data['totalPaper'],
$data['totalRock'],
$data['totalScissors'],
$data['totalTies'],
$data['runsTestPartOne'],
$data['runsTestPartTwo'],
$data['runsTestPartThree']
]);

echo "{'result':'success'}";

What I find strange is that the PHP file reports success after save_data() runs in the code, but no new rows are added to my Database (it doesn't update).

Also, the PHP file has not been touched since I was last able to successfully update my database, so I'm fairly sure that the problem lies in save_data(), but I can't figure out what that is.

I've already looked through already answered questions about issues similar to this, but in all the cases I could find the problem was that a row with a specific entry was not found, so 0 rows were successfully updated. In this case, nothing in the Database is being searched for, I am adding a completely new row, so I can't understand why I would get a success message if the Database is not updated.

I'm very new to web development, so any help I could get with this would be really appreciated!

UPDATE: I've been asked to show where the data is sent from. The data is sent from an HTML file written using a JavaScript library called JsPsych. The actual program itself is very lengthy but here is the specific part where the relevant data is stored and save_data() is called:

 //place data in jsPych data structure
    jsPsych.data.addDataToLastTrial({
        totalAnswered: subjectData.answered,
        totalMissed: subjectData.missed,
        totalRock: subjectData.rock,
        totalPaper: subjectData.paper,
        totalScissors: subjectData.scissor,
        completeSequence: full_sequence,
        totalWins: finalscore.wins,
        totalLosses: finalscore.losses,
        totalTies: finalscore.ties,
        totalForfeits: finalscore.forfeits,
        runLength: runLength.toString(),
        runsTestPartOne: partOneRT,
        runsTestPartTwo: partTwoRT,
        runsTestPartThree:partThreeRT,
        eventLog:event_log,
    });

    //write data to Database
    save_data(jsPsych.data.getLastTrialData());
dangchithao
  • 613
  • 2
  • 8
  • 24
Daniel B
  • 11
  • 4
  • Don't you need to execute your query too? e.g. `$pdo->execute();` –  Aug 17 '18 at 09:01
  • I htink that in $_POST['json'] the key 'json' no exist , try so see with var_dump($_POST) all post values , and get what you need – eborrallo Aug 17 '18 at 09:09
  • Maybe this helps: https://stackoverflow.com/questions/8893574/php-php-input-vs-post – Adder Aug 17 '18 at 11:10
  • You're just `echoing` a string at the end, not catching any errors then echoing, which is why it's saying it worked. also @Ivanov is right, you need to execute it. Please put this code at the top of your php file and post the error `error_reporting(E_ALL); ini_set('display_errors', 1);` – Isaac Aug 17 '18 at 11:33
  • Thank you Isaac, I believe that I am executing the query on line 5 of the PHP file, towards the very end of the line, but the error catching was very informative. Here is the error message that I get: `Notice: Undefined index: json in D:\home\site\wwwroot\javascript-randomness-project-master\saveData.php on line 6

    Warning: implode(): Invalid arguments passed in D:\home\site\wwwroot\javascript-randomness-project-master\saveData.php on line 14
    {'result':'success'}`
    – Daniel B Aug 17 '18 at 15:01
  • @DanielB That means `$_POST['json']` is not set. Show us where that data is supposed to be sent from. – GrumpyCrouton Aug 17 '18 at 18:04
  • Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – GrumpyCrouton Aug 17 '18 at 18:04
  • @GrumpyCrouton I've edited the post with the code where `save_data()` is called and where the relevant data is stored. Is that what you meant or did I misunderstand you? – Daniel B Aug 18 '18 at 18:28
  • That doesn't show how that post request is sent to your script, are you sure you are sending the information properly? – GrumpyCrouton Aug 19 '18 at 19:17

1 Answers1

0

There ended up being two problems, one was that my JSON string was not named 'json' in the save_data() function, so the PHP script was throwing an error when I tried using an uninitialized variable since $_POST['json'] did not exist. The updated and correct function is this one:

function save_data(expData){
   data = JSON.stringify(expData)
    $.post('./saveData.php',{json:data},function(response){   //send POST request to PHP file
        console.log("Response: "+response);
    })
}

The fix is in line 3, where the input is {json:data} instead of simply data.

The second problem was that the database itself was misbehaving. One column in particular refused to accept new entries and would throw an error whenever INSERT was run. This problem was found by adding a try-catch block to the PHP so that any errors thrown by the database itself were reported. Here are the relevant parts of the updated PHP file:

<?php
try{
error_reporting(E_ALL); ini_set('display_errors', 1);
$pdo= new PDO( /*irrelevant*/);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

#irrelevant code ---------

}

catch(exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

That problem was solved by simply deleting the column and adding it again. It was a simple fix but I've included the code to find the problem because I found it useful to be able to see errors thrown by the database itself.

Thank you to everyone who responded for all the help!

Daniel B
  • 11
  • 4