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

Using services in controllers and ajax issue?

Already using Phalcon on my site and I want to change some currently working forms to be submitted with ajax instead, this is my test code. When this form is submitted without using ajax, $messages is an array containing a few elements, with ajax only an empty json object is sent back. Not sure what is happening, again validator works fine without ajax and messages should not be empty. Another example, I also use the Stripe API in my code and tried putting working code in here that sends off a request to get some of my Stripe data from their servers and then sending it back in my response, normally works, only a null object is sent back in response.. Hope this is clear, I can only seem to send back a hard coded array with my ajax response.

jQuery ajax request:

$(function(){
    $("#new_form").submit(function(e){
        e.preventDefault();
        $.ajax({
            url: '/forms/create',
            data: $(this).serializeArray(),
            type: 'POST',
            dataType: 'json',
            success: function(data) { alert(JSON.stringify(data)); },
            error: function(data) { alert('Failed!'); }
        });
    });
});

Controller action: Does not work

// Does not work
public function createAction()
    {
    // this code returns null object in response, 
    // messages should have an array with a few elements
    // my validator works fine when the form is submitted without ajax

        if($this->request->isPost() && $this->request->isAjax()){
            $messages = $this->myCustomValidator->validate($this->request->getPost());
            $this->response->setJsonContent($messages);
            $this->view->disable();
            return $this->response;
        }
    }

Response:

{}

Controller action: This works

// This works
public function createAction()
    {
    // this returns the expected json object

        if($this->request->isPost() && $this->request->isAjax()){
            //$messages = $this->myCustomValidator->validate($this->request->getPost());
            $this->response->setJsonContent(array("test" => "response"));
            $this->view->disable();
            return $this->response;
        }
    }

Response:

{ "test" => "response" }


8.1k

You can create AJAX request with form-data sent for use possibility read POST.

You can use php://input stream fro read post data also.