def to_xhr_response(request, non_xhr_result, form):
    """
    Return an XHR response for the given ``form``, or ``non_xhr_result``.

    If the given ``request`` is an XMLHttpRequest then return an XHR form
    submission response for the given form (contains only the ``<form>``
    element as an HTML snippet, not the entire HTML page).

    If ``request`` is not an XHR request then return ``non_xhr_result``, which
    should be the result that the view callable would normally return if this
    were not an XHR request.

    :param request: the Pyramid request

    :param non_xhr_result: the view callable result that should be returned if
        ``request`` is *not* an XHR request

    :param form: the form that was submitted
    :type form: deform.form.Form

    """
    if not request.is_xhr:
        return non_xhr_result

    request.override_renderer = 'string'
    return form.render()