0

I am trying to save data on click of button using Javascript and PHP.

Button click:

            var xhr = new XMLHttpRequest();
            var url = "savedata.php";
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            /*xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var json = JSON.parse(xhr.responseText);
                    console.log(json.rawText + ", " + json.convertedText);
                }
            };*/
            var data = JSON.stringify({"rawText": rt, "convertedText": ct});
            xhr.send(data);

savedata.php

<?php
header("Content-Type: application/json");

require('db/db.php');
session_start();

    $saverawText = $_POST['rawText'];
    $saveConvertedText = $_POST['convertedText'];

    $ins_query="insert into cmn_data (`rawtext`,`convertedtext`) values ('$saverawText','$saveConvertedText')";
    $result = mysqli_query($con, $ins_query);

?>

In Db: One record is created but it is empty so every time I click save button 1 record is created but empty. What is the wrong the above syntax?

Thanks!

Sanjana Nair
  • 2,232
  • 4
  • 22
  • 40

2 Answers2

2

PHP does not parse JSON requests to $_POST array itself. You should either parse request body in php:

$request = json_decode(file_get_contents('php://input'), true);
$saverawText = $request['rawText'];
$saveConvertedText = $request['convertedText'];

or pass data to request with FormaData object:

var data = new FormData();
data.append("rawText", rt);
data.append("convertedText", ct);
xhr.send(data);

And as mentioned before, including user input directly into sql could cause sql injections. Use mysqli_real_escape_string to escape user inputs or PDO driver, which is bit more complicated but more reliable approach.

zoryamba
  • 166
  • 8
  • forgot to wrap `php://input` with `file_get_contents` and parse json as associative array. updated `$request = json_decode(file_get_contents('php://input'), true);` Try it, should work now – zoryamba May 09 '19 at 18:39
0

You can POST your values like that :

var xhr = new XMLHttpRequest();
var url = "savedata.php";
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
/*xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.rawText + ", " + json.convertedText);
    }
};*/
var data = "rawText=" + rt + "&convertedText=" + ct;
xhr.send(data);
Ugo T.
  • 1,008
  • 8
  • 12