I want to post a data using ajax call. The ajax call us working fine but when I am alerting the data, it is showing all the html tags and then I am not able to retrieve the data in php.
My code for file Filterpage.php is as below:
<html>
<body>
<?php
$data= $_POST['grpNm'];
echo $data;
?>
<script>
$(document).ready(function(){
var GrpNm="ABC";
$.ajax({
type: "POST",
url:"FilterPage.php",
data: {grpNm : GrpNm},
success: function(data){
alert(data);
},
error:function(data){
alert("No");
},
});
});
</script>
</body>
</html>
The alert(data) in ajax call is giving all the html tags and in php I am getting the following error: Notice: undefined index:grpNm
Please help me where I am doing wrong.. I have searched many questions and tried the answers but not working
CodePudding user response:
I think you miss something. Your Ajax call didn't return undefined index:grpNm
when you open the file in browser localhost/Filterpage.php
PHP can't find $_POST['grpNm']
then your ajax fires and request to the same file.
As you return HTML as well it's obvious you see some HTML too. you should kill the process after echo $data;
so the rest of the page will not return in the output.
<?php
if(isset($_POST['grpNm'])){
echo $_POST['grpNm'];
die;
}
?>
<html>
<body>
<script>
$(document).ready(function(){
var GrpNm="ABC";
$.ajax({
type: "POST",
url:"Filterpage.php",
data: {grpNm : GrpNm},
success: function(data){
alert(data);
},
error:function(data){
alert("No");
},
});
});
</script>
</body>
</html>
So here you echo data at the top and kill the process after that. then no HTML will return to ajax call. we also check if the index exists that prevents undefined index:grpNm
warning when you open the URL.
also, it's a good idea to separate your business logic to another PHP file and call that PHP file via ajax.