I cannot get my AJAX to work. Any help would be appreciated as I have spent hours on this with no avail. I am using test-data until I stop getting an error:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
My AJAX:
$.ajax({
type: 'POST',
url: 'addsMeal.php',
dataType:'json',
data: ({name: 'Emma'}),
success: function () {
console.log("Sent data to addsMeal PHP file successfully.");
}
});
addsMeal.php:
<?php
// topFields, newIngredient
$name = $_POST['name'];
echo($name);
?>
The error is:
Warning: Undefined array key "name" in C:xampphtdocsGroceryListGeneratorPagesaddsMeal.php on line 3.
The console logs the data was sent successfully…
2
Answers
Try modifying your PHP code to check if the ‘name’ key exists before accessing it:
This will prevent the warning and handle cases where the ‘name’ parameter is not received properly.
As a brief and quickly written example of a single page jQuery/PHP app perhaps the following might help clarify some of the points made above.
Which outputs a nonsense string: