Concurrent operation using AJAX in Symfony2

2020-08-01 06:53发布

问题:

I am currently working on a Symfony2 project that at some point involves submitting a form and performing a lengthy operation on the filesystem (recursive copy).

At the moment, the user has to wait until the filesystem operation is finished and form processed before being redirected. I have tried enhancing this functionality by using some simple AJAX. I have run into trouble of not being able to perform a form submission and querying another action/controller concurrently.

Does Symfony2 allow concurrent controller requests? If it doesn't, is there any way to complete achieve something that would work like basic concurrency?

This is the outline of what I am trying to do in terms of code:

<form action="{{ path('performSomeAction', { 'id': client.getId(), 'someId':some.someId() }) }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}

<input type="submit" />

And this is what I am trying to do concurrently to submitting the form, using asynchronous XMLHttpRequest:

<script language="JavaScript" type="text/javascript">        
        function getXmlHttpRequestObject() {
            if (window.XMLHttpRequest) {
                return new XMLHttpRequest(); //Not IE
            } else if (window.ActiveXObject) {
                return new ActiveXObject("Microsoft.XMLHTTP"); //IE
            } else {
                alert("Your browser doesn't support the XmlHttpRequest object. ");
            }
        }

        var receiveRequest = getXmlHttpRequestObject();

        function handleFetchProgress() {
            if (receiveRequest.readyState == 4) {
                var newData = receiveRequest.responseText;
                var oldData = document.getElementById("span_result").innerHTML;
                var toDisplay = oldData +  "<br />" + newData;
                document.getElementById("span_result").innerHTML = toDisplay;
            }
        }

        function fetchProgress() {     
            if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
                receiveReq.open("GET", '{{ path('fetchProgress') }}', true);
                receiveRequest.onreadystatechange = handleFetchProgress;
                receiveRequest.send(null);
            }         
        }

        $(document).ready(function() {
            $('form').submit(function() {
                setInterval("fetchProgress()", 1000);
                return false;
            });
        });

回答1:

This is probably caused by session lock and is explained here : How do I kill a session in Symfony2?

You have to unlock session write mode to admit another request to access it.

I wrote a blog post about dealing with asynchronous requests : http://blog.alterphp.com/2012/08/how-to-deal-with-asynchronous-request.html