So I’ve been digging online and found that a jQuery AJAX solution will be best for what I want to do.
I’ve found jquery.ajax() and jquery.post() being mentioned the most.
However the info I’ve found is extremely comprehensive, and honestly, I’m a bit lost!
I need to create a simple button, that will act as a toggle switch. It needs to POST data to a PHP script that will process it and return true, or false. The button should display set, or unset accordingly.
Here’s the snag, the result is dependent also on a database lookup returning true or false, and I need to get information from the $_SESSION securely. Since javascript is client side, i’m not keen on outputting this data into something the user can access. My question being, can I access the session from within the “called” PHP file, and it still work correctly (like an include?).
Here’s the best basic code that I’ve found, however not secure and may be incorrect..
$("#mydiv").click(function(){
var button = $(this) ;
if (!button.hasClass('active')) {
$.post("ajax.php", { user: "2", action: "start" },
function(data){
button.addClass('active');
button.html("End") ;
}
);
}
else {
$.post("ajax.php", { user: "2", action: "stop" },
function(data){
button.removeClass('active');
button.html("Start") ;
}
);
}
});
The session variables will be available in the php scripts you call. Note that the
$.post()-function is asynchronous and has a callback parameter, in your case calleddata. This callback variable will store whatever you echo in the php script that was called by$.post().Now, you can validate stuff and do whatever you like (btw, validations should always happen in your php files, never in javascript, for security reasons!).
One idea would be to echo out
"true"or"false"in your php files after validation and then exiting the php script, such as:Then, your javascript callback parameter
datawill have the value of either"true"or"false". You can simply access this variable like any other variable in javascript, and do stuff depending on its value.One solution might be:
That should do the trick. If you need to return several data points, e.g. an object with attributes, check JSON.