This is my html with script
<div id="info" class="container-fluid">Here is some text</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
$.post("testPHP.php", {name: "John"}, function(data)
{
$( "#info" ).html( data )
})
</script>
and the php code
<?php
$name=$_POST['name'];
echo $name;
?>
In html I may see the name John displayed in the div with id info. But when I run the php file I get this error
Notice: Undefined index: name in C:\\xampp\\htdocs\\ticketing\\testPHP.php on line 2
How can I send a variable via Ajax to a php file and echo this?
Ajax in pass some extra data like type:"ajax" and file in check
<?php
if (isset($_POST['type']) && $_POST['type']=='ajax') {
$name = $_POST['name'];
echo $name;
} else {
echo "You access with direct URL";
} ?>
Try to check if there is a post request in your testPHP.php
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
// do something else here
}
It won't send any data because there is no form in it. No object will be serialized(input, select, etc.).
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.