tags:

views:

200

answers:

1

I am trying to do a comment system with jquery and ajax, sometimes I require a user to enter a captcha image when they are posting too often.

I am using the facebox plugin for jquery with is a popup type dialog box,
I am triggering this box to open, when the backend script tells it that the user needs to enter a captcha, it then pops up the box and loads the php captcha file on screen.

This is where I am having trouble, I need the box to not only open the captcha, but to also populate the comment into this box into like a hidden form field, so that if a user enters the correct captcha code, it will then post there comment, otherwise, they are approving the captcha and then nothing will happen, so I need to then post the comment. Also if they get the captcha wrong, then I need to reload the captcha again with there comments still there, that should be easy if I can get the first part working.

Here is my code so far for this part, can anyone help?

$.ajax({
    type: "POST",
    url: "process.php",
    data: args,
    cache: false,
    success: function (data) {
        // there was an error so we will show an error message
        if (data == 'error') {
            alert(data);
            //we need the user to submit a captcha to post there data
        } else if (data == 'captcha') {
            jQuery.facebox(function () {
                jQuery.facebox({
                    ajax: 'captchabox.php'
                })
            })
            //everything is all good, let post there comment
        } else {
            $('#comments').prepend(data);
            $(this).remove();
        })
    };

    // remove loading image
    $('#load').fadeOut();
}
});
+2  A: 

Yes it can but it is more dependent on what you are posting to than jQuery itself; that is to say the page or webservice you are utilizing for processing. You can return a complex object as the result of a service call (using JSON or XML), arrays, or a single response.

On your process.php it could return a response object containing a value for success (true/false), reason/message (string), and any other number of values you might need. Then in your code you could check:

if (data.Success) { /* code here */ } else { ... }

See the following link for returning JSON via PHP: http://us2.php.net/manual/en/book.json.php

Fooberichu
Ok sounds like thats the right track to be on. So on my processing script I can use json_encode in php, so I then send it back to jquery as a json string, once here I need to break it back into it's own variables, do you know how I can do that?
jasondavis
You can use the plugin here: http://json.org/json2.js -- this isn't an actual jQuery plugin directly but one that John Resig (creator of jQuery) suggests using.
Fooberichu