This is my first dabbling in Ajax and I'm confused.
Problem: JS variable doesn't seem to get passed to php through Ajax.
I get this notice:
Notice: Undefined index: text in C:\\xampp\\htdocs\\Website\\ref_files\\delete.php on line 31
Line 31 is: $name = $_POST['text'];
So the problem seems to be that ' text
' is not being passed to the php as far as I can tell?
Both the JS and the PHP are in delete.php which is included in WhatsNew.php.
I get Response:
displayed on the page, as well as an alert saying "success".
There is a value in 'text', I have tested it with alert(text).
JavaScript + Ajax
<script>
var text = $('#title').text()
$.ajax({
url: "WhatsNew.php",
type: "post",
cache: "false",
data: text,
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});
</script>
PHP
<?php
$name = $_POST['text'];
echo "Response: " . $name;
?>
If more information is required it will be posted beyond this point.
You need to change data to:
data: {text: something},
and also change the name of the variable in js, as the compiler won't know which text to take, like:
var something = $('#title').text();
Please do comment if this does not work!
Try this in php on a different file with some response in success:
<?php
echo "hello";
$name = $_POST['text'];
echo "<label id='1'>Response: " . $name . "</label>";
?>
you need to change
data: text,
to
data: {text:text},
You are on track, just one modification:
data: {text:text},
You need to send text
as key to posted data.
You need to wait for the document to be ready before trying to read $('#title').text()
.
Just wrap everything in $(function() {...})
, (and data:{text:text}
as others have pointed out).
$(function() {
var text = $('#title').text();
$.ajax({
url: "WhatsNew.php",
type: "post",
cache: "false",
data: {text:text},
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});
});
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.