Skip to content

AJAX Form Post example

KOTRET edited this page Jan 13, 2013 · 2 revisions

this is an example of how to use AJAX to post form data to the server, process it with F3 / php, and return the inserted data via AJAX, which you can then use jQuery / Javascript to update a div to show the newly inserted content and hide the original html form, etc.

your HTML template: a form with action & id

    <form
        action="/forums/{{@forum_id}}/{{@topic_id}}/{{@topic_subject_uri}}"
        id="forumPostingForm"
        method="post"
    >

jQuery code for sending the forms data with AJAX

    /* jQuery ajax function 
     * post using the comment form & get back response from server & display on page.
    */

    $(function() /* anonymous func */
    {
        /* capture the form submit event */  		
        $("#forumPostingForm").submit(function(event)
        {   
            /* stop form from submitting normally */
            event.preventDefault();             

            /* setup post function vars */
            var url = $(this).attr('action');
            var postdata = $(this).serialize();                

            /* send the data using post and put the results in a div with id="result" */
            /* post(url, postcontent, callback, datatype returned) */
            
            var request = $.post(
                url,
                postdata,
                formpostcompleted,
                "json"            
            ); // end post function            

            function formpostcompleted(data, status)
            {
                /* write server response to console for troubleshooting */
                console.log(data);
                console.log(status);
            }
         }); // end submit function
    }

PHP-function called by the handler inserts data & responds with JSON formatted object

    // return response using JSON for AJAX
    F3::route('POST /forums/@forum_id/@topic_id/@topic_subject_uri', function()
    {
        // clean, validate form post data
        // save to db, typically using ORM / Axon object
        // this example uses Axon named $posting
        
        // create assoc array object
        $return_array = array(); 
        
        // set values
        $return_array['id']			= $posting->id;
        $return_array['parent_id']        	= $posting->parent_id;
        $return_array['user_id']        	= $posting->author_id;
        $return_array['author_name']    	= $posting->author_name;
        $return_array['author_location'] 	= $posting->author_location;
        $return_array['posting_datetime'] 	= date('D F j, Y, g:i a');
        $return_array['body_text']       	= $posting->body_text;

        // send to browser as JSON encoded object
        echo json_encode($return_array);
	
    });

now you can use jQuery code in your HTML template to insert the functions return data in a div and hide the original HTML form