Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
+2 votes
929 views
in Plugins by
I am working on my first custom page plugin, and all is clear. Here is form, I can add text and other content. But I need ajax form. Of course I can learn how to do it, but if you can answer me, would be great ;)
Q2A version: 1.5.1

1 Answer

+2 votes
by
selected by
 
Best answer

Sure, here's a basic guide to how I do it. On the page plugin you can just send an AJAX request to the same page and handle it in the PHP. You don't necessarily have to use a form. I use this jQuery:

<script>
$.ajax({
    type: 'post',
    data: { ajax_add_message: "the text" },
    success: function(response) {
        // do processing here
    }
});
</script>

Note, you'd normally put that in some kind of event handler, for example in place of the ... in $('#something').click( function() { ... }); Or maybe inside a form submission handler.

Next, in the PHP you can arrange your process_request function like this:

function process_request($request)
{
    $message = qa_post_text('ajax_add_message');
    if ( !empty($message) )
    {
        // we received an AJAX request
        echo 'Success!';
        return;
    }

    // otherwise, this is a normal page request
    $qa_content = qa_content_prepare();
    $qa_content['title'] = 'Page title';
    // rest of the page stuff here, including the JS above

    return $qa_content;
}

OK so here we check for the variable sent via AJAX, ajax_add_message. If it exists then we do some processing and output a string of text, which is what gets put in the response variable in the Javascript.

That's the basic shell, hopefully it will help you! If you have any questions feel free to ask and I'll try and answer :)

by
Thanks. Looks good, but this is best way to use ajax in Q&A? I know how to use ajax in php, but not sure, how ajax works in Q&A engine. I will check you code more later. Thanks anyway.
by
As far as I know, there is no "official" way to use it, you just use AJAX to post data to a URL and the URL returns some output.

This is the easiest way that I found but maybe it's better to have a separate page plugin that just handles the AJAX requests.
by
Thanks, selected :)
...