17

Is it possible to simulate/make an XMLHttpRequest request (ajax) in symfony2 tests?

4 Answers 4

38

After search with "Problematic" answer, the correct syntax is:

$crawler = $client->request('GET', '/foo/', array(), array(), array(
    'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
Sign up to request clarification or add additional context in comments.

Comments

6

The Request#isXmlHttpRequest() method simply checks if the X-Requested-With header is equivalent to XMLHttpRequest. If that's the method you're using to determine if a request is an ajax call, then you can simulate the behavior in the test client by adding the appropriate header to the request:

class FooFunctionalTest extends WebTestCase
{
    $client = static::CreateClient();
    $crawler = $client->request('GET', '/foo/', array(), array(), array(
        'X-Requested-With' => 'XMLHttpRequest',
    ));
    // ...
}

More information can be found about the Request object in the source code.

1 Comment

syntax problem, see my answer. Thank's =)
2

For POST, PUT:

$crawler = $client->request('POST', '/foo/', array('param' => 'value'), array(),
array(
    'HTTP_X-Requested-With' => 'XMLHttpRequest',
));

For POST, PUT with raw JSON body:

$crawler = $client->request('POST', '/foo/', array(), array(), array(
    'HTTP_X-Requested-With' => 'XMLHttpRequest',
    'CONTENT_TYPE' => 'application/json',
), '{"param": "value"}');

Comments

1

If you are working with Symfony 3.x or 4.x this is the correct way to do it using POST method.

$data = ['some' => 'value'];
$client = static::createClient();
$client->request('POST', '/some_uri', ['data' => $data], [],; [
  'HTTP_X-Requested-With' => 'XMLHttpRequest',
]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.