I am trying to return an array from PHP to AJAX but it is returning NULL instead of the data I am sending back to AJAX
Here is my code
header.php
<?php
include_once("obtainData.php");
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AJAX CALL</title>
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
index.php
<?php
include_once("header.php");
?>
<div>
<h3>AJAX CALL</h3>
<p>
<?php
sendData();
?>
</p>
</div>
<?php
include_once("footer.php");
?>
footer.php
<script>
$.ajax({
url: "obtainData.php",
data: {action: 'sendData'},
type: 'GET',
success: function(data) {
alert(data);
alert("Success");
},
error: function() {
alert( "Error." );
}
});
</script>
</body>
</html>
obtainData.php
<?php
if(isset($_POST["action"])){
$action = $_POST['action'];
switch($action) {
case 'sendData':
sendData();
break;
}
}
function sendData(){
$array = [];
for($i = 0; $i < 20; $i++){
$array[$i] = "prove";
}
echo json_encode($array);
}
?>
If I call my sendData
method on my embeded PHP it shows me the output but I am not able to get it from AJAX call.
Am I missing something?
Thanks in advance!
You are using type: 'GET',
in your Ajax call.
And you are trying to retrieve $_POST
in your php file.That's why getting nothing.
SO change type: 'GET',
to type: 'POST',
The issue is because you're sending a GET request, but using $_POST
to retrieve the value. As a result isset($_POST["action"])
is always false.
Either use $_GET
to retrieve the values in your PHP code, or change the jQuery to send a POST
request.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.