Reputation: 13
I want to pass some json data from javascript using ajax to php file
I've tried a lot of solutions from internet but none of them is working.
This is my javascript file (a.html):
<html>
<head></head>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
</script>
<script>
var dataPwm = {dataHeat : 1};
console.log(dataPwm)
$.ajax({
type: "POST",
url: "b.php",
data: {dataHeat : 1},
//cache: false,
success: function(response){
console.log(response);
}
});
</script>
</body>
</html>
and this is my php file in same directory (b.php):
<?php
$json_string = $_POST["dataHeat"];
var_dump(json_decode($json_string));
?>
i expect the output of 1, but the result is NULL
Upvotes: 1
Views: 68
Reputation: 1651
there may be a few problems here
If there is an error in the browser console, then the jquery is not include
You do not need to use json_decode
if you want the result to come here
console.log (response);
need to do
$dataHeat= $_POST["dataHeat"];
echo $dataHeat;
Upvotes: 0
Reputation: 862
You did not include Jquery! use this in head and it will work:
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
you are using jquery for ajax, therefore you should first load it and then use it. it is that simple. other than that your code is completely correct. and you should expect int(1) in console.
Upvotes: 1