0

I am working on Zend and my objective is to get the returned content of a form with AJAX (so that I don't have to reload all the page).

Here is what I have :

ZendForm -> FormController -> View

On the FormController, I check if there is a post :

if(isPost) {$this->sendJson($data);}
else {return $From;}

In my view i display the form with a echo $this->smartForm($Form);

My problem is on the view I couldn't figure out how to use AJAX to dump the array without reloading the page.

My Form View and controller are working fine, my issue is only on the method. If someone could give me a snap of a code or an example that would be great.

Thank you

Brad
  • 5
  • 6
  • show us your JS – delboy1978uk Jun 05 '18 at 14:43
  • @delboy1978uk i don't have one... thats what iam asking for, i've seen a lot of Js sources but i don't understand them quit good to put something on my view. – Brad Jun 05 '18 at 15:08
  • so how are you calling the controller? – delboy1978uk Jun 05 '18 at 15:10
  • @delboy1978uk I've edited the post. Iam just using a smartForm for the form itself but in the case there is a post i don't know how to get the data and display it using Ajax without reloading the all the page – Brad Jun 05 '18 at 19:23
  • You really need to learn javascript or a javascript library like jquery to achieve your goal. – Garry Jun 09 '18 at 09:03

2 Answers2

0

I use jQuery to make ajax requests as it is fairly simple to use. Here is a code snippet I have used on my latest project.

$('#category_form').on('click', 'input[type="submit"]', function (event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    var form = $('#category_form').find('form');
    form.find('img.loadingSquares').css('visibility', 'visible');
    $('#overlay').css('display', 'block');
    clearMessage();
    var formData = new FormData(form[0]);
    formData.append('submit', $(this).val());
    $.ajax({
        method: "POST",
        url: "/author/categories/get-products",
        dataType: "json",
        processData: false,
        contentType: false,
        data: formData,
    }).done(function (json) {
        if (json.message) {
            displayMessage(json.message);
        }
        if (json.products) {
            console.log(json.products);
            $('#category_form').find('#products-container').empty().html(json.products);
        }
    }).fail(function () {
        displayMessage(ajaxFailGenericError);
    }).always(function () {
        $('#overlay').css('display', 'none');
        $('img.loadingSquares').css('visibility', 'hidden');
    });
});

See here for more info on jQuery

I hope this points you in the right direction

Garry
  • 1,455
  • 1
  • 15
  • 34
0

You've not tagged jQuery, so I'm giving you a JavaScript only answer.

Read this on sending Forms from Mozzila

Here's an answer on sending a simple form using just Javascript. Code below is from that answer.

const form = document.querySelector("#debarcode-form");
form.addEventListener("submit", e => {
    e.preventDefault();
    const fd = new FormData(form);
    const xhr = new XMLHttpRequest();
    xhr.addEventListener("load", e => {
        console.log(e.target.responseText);
    });
    xhr.addEventListener("error", e => {
        console.log(e);
    });
    xhr.open("POST", form.action);
    xhr.send(fd);
});

Make sure that the form you've rendered in the PHTML partial via ZF2 contains the correct action URL (so you've used the URL ViewHelper like so: <?= $this->url('name/of/path') ?>). This is to make sure that the JavaScript sends the data to the correct spot of your Zend Framework application.

Next, handle the data like so in your Controller:

public function handleFormAction()
{
    /** @var \Zend\Http\Request $request */
    $request = $this->getRequest();

    /** @var \Some\Namespace\Of\CustomForm $form */
    $form = $this->getCustomForm(); // You've created this using a Factory of course
    if ($request->isPost()) {
        $form->setData(\Zend\Json\Json::decode($request->getContent(), Json::TYPE_ARRAY));

        if ($form->isValid()) {
            $object = $form->getObject();

            // object handling, such as saving

            // Success response
            // Redirect to success page or something
            $this->redirect()->toRoute('success/route/name', ['id' => $object->getId()]);
        }

        // Fail response, validation failed, let default below handle it ;-) 
    }

    if ($request->isXmlHttpRequest()) {
        return new \Zend\View\Model\JsonModel([
            'form'               => $form,
            'validationMessages' => $form->getMessages() ?: '',
        ]);
    }

    // Default response (GET request / initial page load (not async) )
    return [
        'form'               => $form,
        'validationMessages' => $form->getMessages() ?: '',
    ];
}

This answer obviously misses stuff, such as creating the Form for the Controller using a Factory, routing configurations and object hydration and handling.

This is because these things are out of scope of the question.


P.S. - I've used FQCN's (Fully Qualified Class Name), you should include them at the top of the file.

rkeet
  • 3,406
  • 2
  • 23
  • 49