-1

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") ;
        }
    );
}


});

3 Answers 3

1

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 called data. 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:

<?php
    //validate here and store success in boolean $success
    if($success==true){ echo "true"; exit; }
    else{ echo "false"; exit; }
?>

Then, your javascript callback parameter data will 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:

$("#mydiv").click(function(){

    var button = $(this) ;

    if (!button.hasClass('active')) {
        $.post("ajax.php", { user: "2", action: "start" },
            function(data){
                if(data=="true"){
                    button.addClass('active');
                    button.html("End");
                }
            }
        );
    }
    else {
        $.post("ajax.php", { user: "2", action: "stop" },
           function(data){
                if(data=="true"){
                    button.removeClass('active');
                    button.html("Start");
                }
           }
        );
    }


});

That should do the trick. If you need to return several data points, e.g. an object with attributes, check JSON.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I might be missing the obvious, but how would I configure my <button> to display the End or Start text?
From your code it seems like your button has the id "#mydiv" - an id like "mybutton" would probably be a better fit. Either way, your button's id has to be in there. Instead of a button tag I would use an input tag and then change its value property like this: button.attr('value','changed text');
Thanks for the reply. But I'm struggling to get this working. Aside from including jQuery, is there anything else I need to do? XHR in my element inspector is showing no requests when the button is clicked?
What id does the button have? Make sure to put it inside the $("#yourbuttonidhere").click(...)
Thanks for the reply. The issue was checking if the DOM was ready $(document).ready(function() - thanks!
1

You can access $_SESSION securely from within the called php script.

I assume on the php script you are printing true or false. In which case you may want to add the if statement in your callback function. The data contains the return of the php script.

Comments

0

If the answer of the PHP script is success/error, consider using HTTP headers to indicate this, e.g.

on fail, render:

header("HTTP/1.0 406 Not Acceptable");

This make's your life easy in jquery because you can then just write handlers for success and error.

As for the Session, it should work find, the browser will pass the session cookie when it makes the AJAX request and PHP will load the session correctly..

You can modify your code above with something like this:

$.ajax({
  url: 'http://blarg.com',
  data: { your post data },
  success: function(data) {  do something },
  error: function(o,textStatus) { do Error }
});

Check out the API for more details: http://api.jquery.com/jQuery.ajax/

2 Comments

Thanks for the reply. So should the above code be suitable? How can I modify it to change state depending on the result of the request (i.e change the text to start / stop)?/ Thanks!
I added an example for that, you just define handlers and thats it.. Set the header to Unacceptable if its a fail and you'll have nice clean code..

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.