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>
1
  • 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 <script> in your php file will never be executed as this script is never passed back to the browser. Look at @Robert and @Gergo's anwsers for help. Commented Jun 12, 2014 at 21:38

2 Answers 2

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;
?>
Sign up to request clarification or add additional context in comments.

5 Comments

I keep getting this error Notice: Undefined index: TotalPoints
Alert data gives the value of the variable as declared but echo gives no post value. Where is it losing the value.
I mean alert (data) displays 20; but echo gives No post value
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
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...
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.