i'm trying to learn ajax for a new project, i need to upload data using some javascripts variables, so in order to start , i decided to try a small easy ajax problem , but i didnt work,
Notice: Undefined index: name in C:\Apache24\htdocs\d.php on line 4 is shown
My .js file :
<script>
$.ajax({
type: "POST",
url: 'd.php',
data: {name : "aa"},
success: function(output) {
alert(output);
}
error: function(request, status, error){
alert("Error: Could not delete");
}
);
</script>
My php file:
<?php
print_r($_POST['name']);
?>
Thank you
It doesn't work like that, you're never gonna see what went on behind the hood, the only way out is to log the request in txt file.
Your variable would only be defined when ajax send the POST request, to see if it is successful, edit your code like this:
<?php
//if post is set
if(isset($_POST['name'])) {
//open log.txt
$file = fopen('log.txt', 'a');
//ensure print_r give a return
fwrite($file, print_r($_POST, true);
//close log.txt
fclose($file);
}
?>
Ensure you create a file log.txt
After doing this send the ajax request and view the $_POST variables in log.txt
3 mistakes:
1 - name : aa
2 - comma after success function
3 - } at the end of ajax
var aa = 1234;
$.ajax({
type: "POST",
url: 'd.php',
data: {name : aa},
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
PHP for me:
$s = $this->input->post('name');
return print_r($s);
Try this code in javascript.
$.ajax({
enter code here
url: 'd.php',
data: {name : "aa"},
type: 'post',
dataType: 'json',
}).then(function(output) {
alert(output);
}, function(request, status, error){
alert("Error: Could not delete");
});
Ok, i wrote your code in my project to understand what was the problem, indeed the code is correct but you were missing a "," and a "}" Below you can see the working code:
$.ajax({
type: "POST",
url: 'd.php',
data: {name : "aa"},
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
Another tips for you, add a check in the .php file :
if(isset($_POST)){
my_data = $_POST['name'];
}
have a nice work!