bielu000
bielu000

Reputation: 2241

Zend Framework 3 AJAX responding data

I try to do async contact form validation in ZF3 by using ajax. Thats my ContactController

public function contactAction()
{
    $form = $this->form;
    $request = $this->getRequest();
    $response = $this->getResponse();
    $vm = new ViewModel(['form' => $this->form]);

    $form->setInputFilter(new ContactFormFilter());

    if (!$this->getRequest()->isPost())
        return new ViewModel(['form' => $this->form]);

    $data = $request->getPost();

    $form->setData($data);

        if (!$form->isValid())
        {
            $vm->setTerminal(true);
             return $response->setContent(\Zend\Json\Json::encode($form->getMessages()));
        }

}

and below is contact.phtml with jquery script.

$(function(){
    $("#foo").submit(function(event){
        event.preventDefault();


        $.ajax({
            url: '/kontakt',
            type: 'POST',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            async: true,
            data: ($("#foo").serialize()),
            success: function (data) {
                console.log(data);
                alert(data);
            },
            error: function (data) {
                console.log(data);

            }
        });
    })
})

Form has "foo" id;

The problem is, that when I submit I get respond like this each time: (its from console)

Object
-email :Object
-message :Object
-subject :Object
-personal-data :Object

and when I open for exmaple "message Object" it shows me : isEmpty :" Field is required" even when the message field isn't empty!

Could anyone know what I am doing wrong?

Upvotes: 1

Views: 2304

Answers (1)

madalinivascu
madalinivascu

Reputation: 32364

Remove contentType: "application/json; charset=utf-8", to send the data as url encoded

Upvotes: 1

Related Questions