I would like to know how I can pass a Javascript array from Javascript to PHP through Jquery/Ajax. In fact I created two files: t1.html and moslem3.php . The code of each file is below:
The code of t1.html:
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: table
});
});
</script>
</body>
</html>
The code of moslem3.php:
<?php
$myArray = $_REQUEST['table'];
echo $myArray;
?>
The file moslem3.php displays this message:
Notice: Undefined index: table in C:\wamp\www\test1\moslem3.php on line 2
So my question is: where is the wrong here exactly?..Is there any one who has any idea?
Thanks in advance.
3 Answers 3
PHP doesn't inherently know anything about the JavaScript variables being used, such as var table. Its insights for the $.ajax() request are completed limited to the data structure.
So, for PHP to know about a 'table' parameter in $_REQUEST, the data needs to include it that as a named value:
data: { table: table }
This defines the data as an Object with a property table assigned to the value of the variable by the same name.
You can witness the difference using $.param(), which $.ajax() uses:
var table = ["actor", "subject", "object"];
console.log($.param(table));
// "undefined=&undefined=&undefined="
console.log($.param({ table: table }));
// "table%5B%5D=actor&table%5B%5D=subject&table%5B%5D=object"
1 Comment
Change Jquery
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: {t_name:table },
success:function(data){
console.log(data);
}
});
});
</script>
Change in moslem3.php
<?php
$myArray = $_REQUEST['t_name'];
print_r($myArray);
?>
Output:
enter image description here
4 Comments
Try this :
$.ajax({
type : "POST",
url: 'moslem3.php',
cache:false,
async:true,
global:false,
data : {
"table": table }
}).done(function(msg) {
alert(msg);
})
echo json_encode($myArray);success: function(result){ .... }. BTW your ajax call need tweaking.