Magnanimity
Magnanimity

Reputation: 1313

Symfony 3 - Sending AJAX request as XmlHttpRequest() (javascript) does not pick up request as XmlHttpRequest in backend

I have an ExceptionListener implemented in Symfony3 (also works in Symfony2). The ExceptionListener identifies whether the request was normal HTTP or AJAX (XmlHttpRequest) and generates a response accordingly. When using jQuery .post() or .ajax(), the ExceptionListener returns $request->isXmlHttpRequest() as TRUE, but when using javascript var xhr = new XmlHTTPRequest(), the ExceptionListener returns $request->isXmlHttpRequest() as FALSE. I am using the latter in a small amount of instances where files need to be uploaded via AJAX (which cannot be done using .post() or .ajax().

I am looking for a solution (either frontend or backend) to resolve my ExceptionListener incorrectly picking this up as a normal HTTP request.

Frontend Code:

function saveUser()
{
    var form = document.getElementById('userForm');
    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();

    xhr.open('POST', '{{url('saveUser')}}', true);
    xhr.onreadystatechange = function (node) 
    {  
        if (xhr.readyState === 4) 
        {  
            if (xhr.status === 200) 
            {  
                var data = JSON.parse(xhr.responseText);
                if (typeof(data.error) != 'undefined')
                {
                    $('#processing').modal('hide');
                    $('#errorMsg').html(data.error);
                    $('#pageError').modal('show');

                }
                else
                {
                    $('#successMsg').html('User Successfully Saved');
                    $('#processing').modal('hide');
                    $('#pageSuccess').modal('show');
                    $('#userModal').modal('hide');
                    updateTable();
                }
            } 
            else 
            {  
                console.log("Error", xhr.statusText);  
            }  
        }  
    };
    $('#processing').modal('show');
    xhr.send(formData);

    return false;
}

ExceptionListener.php (partial)

# If AJAX request, do not show error page.
if ($request->isXmlHttpRequest())  # THIS RETURNS FALSE ON JS XmlHTTPRequest()
{
    $response = new Response(json_encode(array('error' => 'An internal server error has occured. Our development team has been notified and will investigate this issue as a matter of priority.')));
}
else
{       
    $response = new Response($templating->render('Exceptions/error500.html.twig', array()));
}

Upvotes: 2

Views: 5284

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

When using vanilla ajax you need to pass the following header to your ajax request

xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Upvotes: 8

Related Questions