Hi I’m not really sure where to start with this, but I’m just looking to learn ajax and php, but am unsure what I’m missing here.
I want this code set up so that every time I click .test-ajax it increments a number, because I’m looking to learn how it works with php Im hoping to have the incrementing happening in a php file.
Here is my jQuery
$(document).ready(function(){
$('.test-ajax').live('click', function(event)
{
$.ajax({
url: 'variableplusone.php',
type: 'post',
data: { offset: 2 },
success: function(offset) {
alert(offset);
}
});
});
});
and my variableplusone.php file…
<?php
$x = add_one();
function add_one()
{
if (isset($_POST['offset']))
{
$offset = $offset;
echo $offset;
}
}
return $x;
Just wondering how to get the value of $offset to be affected in the php file, and then returned back and updated?
Obviously, you need to check your $_POST[‘offset’] is a number and other sanity checks. To return the value to the javascript, it is enough to echo it, or die. In the javascript, you will receive one single value, which in your example would be 3 (you pass 2, and the PHP increments it by one).
EDIT: To “keep” the changes to the number, you have a choice: Either you remember it on the client side with javascript or cookies, or you remember it on the server side with a session variable.
Above is one way to remember it on the client. Be aware that if the user refreshes the page, it is reset to the default (2).