I have an array in javascript and I need to convert it into PHP array. So I have this code and I have tried other codes too but no one has worked.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="res" style="border: 1px solid black; width: 400px; height: 200px;"></div>
<br>
<input type="file" name="img[]" id="img" multiple>
<input type="submit" name="submit" id="submit">
<script>
var array = new Array();
$('#img').change(function() {
var img = $('#img').val().split('\').pop();
array.push(img);
document.getElementById('res').innerHTML = array;
});
$('#submit').click(function() {
var send_data = JSON.stringify(array);
$.ajax({
type: "POST",
enctype: "multipart/form-data",
url: "test.php",
data: {send_data:send_data},
datatype: "JSON",
success: function(data) {
}
});
});
</script>
</body>
</html>
And my test.php
<?php
$data = $_POST['send_data'];
$decoded = json_decode($data, true);
var_dump($decoded);
?>
2
Answers
HTML && Javascript sample code:
PHP Code:
You can transform a javascript array (call it
myDataAsJSArray
) into a JSON string, beforePOST
-ing:After
POST
-ing, you can transform the JSON string into a PHP array:Note that if you omit the optional
TRUE
parameter immediately above, PHP will transform your JSON into a PHP Object, rather than a PHP Array.Further Reading: