Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Ajax Form Submit

Can any one please share the code of any simple form which is using ajax posting to controller from scratch.



5.2k
Accepted
answer

Volt Template Engine code:

{{ form('method': 'post', 'name':'ahsan', 'id':'ahsan') }} <input type="hidden" id="token" name="token" value="<?php echo $this->security->getToken()?>"/> <label for="name">Name</label> {{textfield("name","size":32)}} <br> {{submitbutton('Enter Products',"id":"enter")}} {{end_form()}}

//Including Jquery file <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>

//My Jquery Code

<script type="text/javascript"> $(document).ready(function() { $("#id").submit(function(e){ var tokenvalue = $("#token").val(); var productname = $("#name").val(); e.preventDefault(); $.ajax({ url: 'save', //write only function name controller name not required data: {postvalue:productname,tokenval:tokenvalue}, type: 'POST', success: function(data) { alert(data); }, error: function(data) { alert('Failed!'); } }); });

});

</script>

My Controller Code

public function saveAction() {

    if ($this->request->isPost() == true) 
    {
        if ($this->request->isAjax() == true) 
        {
            echo "succespost and ajax";
        }
        else
        {
            echo "failure not ajax";
        }
    }   
    else
    {
        echo "failure not post";
    }
}

above written code is verified and tested.