We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Ajax Form Submit

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



14.7k
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> {{text_field("name","size":32)}} <br> {{submit_button('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.

Where the incluyed?

Volt Template Engine code:

Comment Preview Help ||

Where Where

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> {{text_field("name","size":32)}} <br> {{submit_button('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";
   }

}