I have a javaScript array which I need to store in PHP so that later I can store it to MySQL database.
index.php
<form method="post">
<button type="submit" class="btn btn-default" id="php-submit" name="php-submit"><span class="glyphicon glyphicon-upload"></span></button>
<table class="table" id="table-1">
<-- my finalArray gets generated by selecting some of these table cell values -->
</table>
</form>
app.js
$('#php-submit').click(function()
{ // For demo purpose, I have written hardcoded array values here
var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
// console.log(finalArray);
str_json = JSON.stringify(finalArray);
console.log(str_json);
$.ajax({
type: "POST",
url: "script.php",
data: {data : str_json},
cache: false,
success: function(){
alert("OK");
}
});
// $.post('script.php', { data: finalArray }, function (data) {
// alert("OK");
// });
});
After user clicks ('#php-submit') button, I want to be display 'finalArray' or 'str_json' on my script.php.
Below are 4 different approaches that I have tried.
script.php
// approach 1: output --> blank page
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
// approach 2: ouptut --> null
$data = json_decode(stripslashes($_POST['data']));
var_dump($data);
// approach 3: output --> null
header('Content-type: application/json; charset=utf-8');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;
// approach 4: output --> array(1) { [0]=> string(4) "null" }
$data = $_POST['data'];
$json_encode = json_encode($data);
$ar = explode(',', $json_encode);
var_dump($ar);