Fork me on GitHub

How to submit a form using Ajax?  Bottom

  • Hi,

    I have a form which when submitted is supposed to trigger an update via Ajax. I can handle the backend part, my question is how do I submit form values to Ajax without causing a page refresh?

    Greetings/Thanks
    R
  • So if you have form - you need to bind js observer which will catch submit event and proceed submission via Ajax.

    Example:

    Code

    <form id="myform" method="post" ... >
        ...
    </form>

        $('myform').observe('submit',submitHandler);
        function submitHandler(event) {
            event.preventDefault(); // this stops default event execution - so form wont be send in normal way
            var form = e.findElement('form'); // find form element in event handler, if this function is used for one form do it simple: vaf form = $('myform');
            var pars = form.serialize(); // get form values
            new Zikula.Ajax.Request("ajax.php?module=foo&func=bar", {
                    method: 'post',
                    parameters: pars,
                    onComplete: youCompleteRequestHandler
                });
        }


    Edit - script tags where striped by Dizkus... So just remember to pust js code inside script tag



    Edited by Jusuff on Mar 02, 2011 - 03:46 AM.

    --
    Polish Zikula Team
    Bianor Works - my Zikula works on CoZi
  • Great, that was what I was looking for.

    Thanks a lot
    Robert
  • One thing: Ideally the javascript should be in a separate .js file , and included with the pnajaxheader plugin.
    That is, for 1.2.x at least, I'm sure 1.3 renames everything.



    Edited by ccandreva on Mar 02, 2011 - 03:04 PM.
  • Yes, you're right. This was just fast example :)
    And in 1.3 pnajaxheader was renamed to ajaxheader.

    --
    Polish Zikula Team
    Bianor Works - my Zikula works on CoZi
  • Hi Jusuff,

    I would need 1 more piece of help/advice please. On my page, I have multiple forms (I in advance know the name/id of the forms). How would I change the submitHandler() function to accept a parameter which tells it the name/id of the form and how would I then change the calling code to reflect this?

    Yes, I am rather incompetent when it comes to JS icon_smile

    Greetings/Thanks
    Robert
  • The example code I've posted above contains what you need :)
    Take a look at:

    Code

    var form = e.findElement('form');

    This way "form" refers to form element, which was submitted. If you need directly it's ID attribute, just get it:

    Code

    formId = form.id;

    or even:

    Code

    var formId = e.findElement('form').id;




    Edited by Jusuff on Mar 08, 2011 - 02:17 AM.

    --
    Polish Zikula Team
    Bianor Works - my Zikula works on CoZi
  • I was wondering if something might be possible with a link [including an ID] and catching the page with the pnmod/pnmodapi function...

    - Igor
  • Igor - I'm not sure what you want achieve...

    --
    Polish Zikula Team
    Bianor Works - my Zikula works on CoZi
  • Hi Jusuff,

    thanks very much for your help, I got things to work using the following code:

    Code

    function submitHandler(event) {
                    event.preventDefault();
                    var form = event.findElement('form');
                    var formID = form.id;
                    var pars = form.serialize();

                    /* DEBUG
                    var str = '';
                    var elem = form.elements;
                    for(var i = 0; i < elem.length; i++)
                    {
                            str += "Type:" + elem[i].type + "  ";
                            str += "Name:" + elem[i].name + "  ";
                            str += "Value:" + elem[i].value + "";
                            str += "\n";
                    }
                    alert (str);
                    */


                    var skuArray = [];
                    for(var i=0; i<5; i++) {
                            if (typeof form["sku_array["+i+"]"] != 'undefined') {
                                    skuArray[i] = form["sku_array["+i+"]"].value;
                            }
                    }
                    //alert (skuArray);
                            show_data(form.product_id.value, skuArray, form.qty.value);
                   
            }


    Greetings/Thanks
    Robert
  • Actually, I just discovered something interesting/mysterious. The following code:

    Code

    function add_response(req)
    {
        if (req.status != 200 ) {
            pnshowajaxerror(req.responseText);
            return;
        }

        var json = pndejsonize(req.responseText);

        for(var i=0; i<25; i++) {
            $('line_' + i).style.display = 'none';
        }

        for(var i=0; i<json.totalItems; i++) {
            $('name_' + i).innerHTML     = json.lines[i].name;
            $('qty_'  + i).innerHTML     = json.lines[i].qty;
            $('link_' + i).href          = json.lines[i].href;
            $('line_' + i).style.display = '';
        }
       
        $('totalCost').innerHTML = json.totalCost;
        $('totalItems').innerHTML = json.totalItems;
    }


    under some conditions (which I don't quite understand yet) never reaches the last 2 statements but (and here it gets interesting) the Error console shows no errors and I know that I have more than json.totalItems elements (which are processed in the loop) defined in my HTML page.

    Any ideas? Any tips on how to debug this?

    Greetings/Thanks
    R

This list is based on users active over the last 60 minutes.