1

how to send json from html to php using ajax post method? i refered to this and this in order to get here but i have been getting null return value since, the rest of similar questions get me nowhere.

html(jquery ajax):

$('#unit1').change(function() {
var data = "";
  var selectedUnit1 = this.value;
  var dropDownNumber = "1";
  var postData = {"selectedUnit": selectedUnit1, "unitNumber": dropDownNumber};
$.ajax({
            type: "POST",
            dataType: "json",
            url: "ex02test.php",
            data: {data:postData},
            success: function(response){
                alert(response.title); // to test for return value, now it returns null, 
//hard-coding $unitTitle(example $unitTitle = 'hi'; in php file makes it display 'hi' so the php side is definitely working
                // data = jQuery.parseJSON(response);
                $('#txtHint').val(response[0].title);
            },
            error: function(e){
                console.log(e.message);
            }
    });
$('#totalcost').val(valueFUnction());
});

php:

<?php
$jsonData=$_POST["data"];

$data = json_decode($jsonData);

$unitCode = $data->selectedUnit;

$dropDownNumber = $data->unitNumber;

$unitTitle = $dropDownNumber;
$unitFee = "10";

$reply->title = $unitTitle;
$reply->fee = $unitFee;

$jsonReply = json_encode($reply);

header('Content-Type: application/json');
echo $jsonReply;
?>
Wei Xiong
  • 167
  • 4
  • 13
  • Hi can you just see what is `alert(response)` giving ? Also , where did you declare `$reply` ? – Swati Nov 02 '20 at 14:32
  • $reply is declared on $reply->? i followed https://www.w3schools.com/js/js_json_php.asp alert(response); does not work – Wei Xiong Nov 02 '20 at 16:25

1 Answers1

0

A first step to debug this would be to update your PHP file to something like this:

<?php
var_dump($_POST);
die();

You can then see that there probably is no data key in the $_POST variable, but your JSON content is posted directly into the body of the POST.

In this case, I would expect you could just retrieve the values in PHP with something like:

$selectedUnit = $_POST["selectedUnit"];

But please check the output of the var_dump() to see exactly what is sent to the server.

jonasdev
  • 696
  • 5
  • 11
  • so... how do i get the data in php? – Wei Xiong Nov 02 '20 at 10:33
  • just tried your suggestion for retrieving the value, the alert message does not work anymore haha... havent not tried the var_dump... may i know how to use it? tried to echo var dump into a div, but the div did not display any changes – Wei Xiong Nov 02 '20 at 11:08