1

I am new to using Ajax and am getting the success message here but there is an error that the variable is not defined.

//Variable TotalPoints is already set
$.ajax({
    type: "POST",
    url: 'save_pts.php',
    data: {'TotalPoints' : Allpts},
    success: function(data)
    {
        alert ('Success'):
    }
});
<?php // save_pts.php   
    $Allpts = $_POST['TotalPoints'];
?>
<script>
    alert("<?php echo $Allpts ?>");
</script>
Emissary
  • 9,954
  • 8
  • 54
  • 65
  • You need to make sure you have a value set for `Allpts` in your javascript and your `save_pts.php` should echo the results you want back. The ` – Ballbin Jun 12 '14 at 21:38

2 Answers2

3

Your code should be like this:

$.ajax({
type: "POST",
url: 'save_pts.php',
data: {TotalPoints : Allpts},
success: function(data)
{
    alert (data):
}
});

PHP CODE(save_pts.php)

<?php 
$Allpts = "No post value";
if(isset($_POST['TotalPoints'])){  
$Allpts = $_POST['TotalPoints'];
}
echo $Allpts;
?>
Hackerman
  • 12,139
  • 2
  • 34
  • 45
  • I keep getting this error Notice: Undefined index: TotalPoints – Solid Future Jun 12 '14 at 21:36
  • Alert data gives the value of the variable as declared but echo gives no post value. Where is it losing the value. – Solid Future Jun 12 '14 at 21:44
  • I mean alert (data) displays 20; but echo gives No post value – Solid Future Jun 12 '14 at 21:53
  • Of course it's not gonna display values on is own, because it's not receiving any post var...that's because you are using ajax – Hackerman Jun 12 '14 at 21:59
  • You made an ajax call to save_pts.php and in that way you are sending a post request to your php file and one of the var is named TotalPoints....if you execute the php file alone the post var TotalPoints doesn't exist, ergo, shows the "No post Value" message... – Hackerman Jun 12 '14 at 22:04
2

TotalPoints is the key of the property. The value is Allpts, so you need to create a variable with the name Allpts:

var Allpts = 10;
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94