If the request is ajax, save the form and return a json response.
        Otherwise return super as expected.
321090
def form_valid(self, form):
        
        self.object = form.save(commit=False)
        self.pre_save()
        self.object.save()
        if hasattr(form, 'save_m2m'):
            form.save_m2m()
        self.post_save()

        if self.request.is_ajax():
            return self.render_json_response(self.get_success_result())
        return HttpResponseRedirect(self.get_success_url())
436464
def form_invalid(self, form, prefix=None):
        
        response = super(FormAjaxMixin, self).form_invalid(form)
        if self.request.is_ajax():
            data = {
                "errors_list": self.add_prefix(form.errors, prefix),
            }
            return self.json_to_response(status=400, json_data=data,
                                         json_status=AjaxResponseStatus.ERROR)
        return response
555424
def render_to_json(response, request=None, **kwargs):
    
    # determine the status code
    if hasattr(response, 'status_code'):
        status_code = response.status_code
    elif issubclass(type(response), Http404):
        status_code = 404
    elif issubclass(type(response), Exception):
        status_code = 500
        logger.exception(str(response), extra={'request': request})
        
        if settings.DEBUG:
            import sys
            reporter = ExceptionReporter(None, *sys.exc_info())
            text = reporter.get_traceback_text()
            response = HttpResponseServerError(text, content_type='text/plain')
        else:
            response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
    else:
        status_code = 200

    # creating main structure
    data = {
        'status': status_code,
        'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
        'content': response
    }

    return JSONResponse(data, **kwargs)
1365461
function() {
            this.xhr = $.ajax(_.extend({}, {
                "type":     this.options.method,
                "url":      this.options.url,
                "data":     this.options.params,
                "dataType": this.options.dataType,
                "context":  this,
                "success":  function(data) {
                    logging.debug("Result for request ", this.options);
                    this.trigger("done", data);
                },
                "error": function(xhr, textStatus, errorThrown) {
                    logging.error("Error for request ", this.options);
                    this.trigger("error", {
                        'status': textStatus,
                        'error': errorThrown,
                        'content': xhr.responseText,
                        'xhr': xhr
                    });
                }
            }, this.options.options));
            return this;
        }
1011710
def ajax_upload(self, request, folder_id=None):
        
        mimetype = "application/json" if request.is_ajax() else "text/html"
        content_type_key = 'content_type'
        response_params = {content_type_key: mimetype}
        folder = None
        if folder_id:
            try:
                # Get folder
                folder = Folder.objects.get(pk=folder_id)
            except Folder.DoesNotExist:
                return HttpResponse(json.dumps({'error': NO_FOLDER_ERROR}),
                                    **response_params)

        # check permissions
        if folder and not folder.has_add_children_permission(request):
            return HttpResponse(
                json.dumps({'error': NO_PERMISSIONS_FOR_FOLDER}),
                **response_params)
        try:
            if len(request.FILES) == 1:
                # dont check if request is ajax or not, just grab the file
                upload, filename, is_raw = handle_request_files_upload(request)
            else:
                # else process the request as usual
                upload, filename, is_raw = handle_upload(request)

            # Get clipboad
            # TODO: Deprecated/refactor
            # clipboard = Clipboard.objects.get_or_create(user=request.user)[0]

            # find the file type
            for filer_class in media_settings.MEDIA_FILE_MODELS:
                FileSubClass = load_object(filer_class)
                # TODO: What if there are more than one that qualify?
                if FileSubClass.matches_file_type(filename, upload, request):
                    FileForm = modelform_factory(
                        model=FileSubClass,
                        fields=('original_filename', 'owner', 'file')
                    )
                    break
            uploadform = FileForm({'original_filename': filename,
                                   'owner': request.user.pk},
                                  {'file': upload})
            if uploadform.is_valid():
                file_obj = uploadform.save(commit=False)
                # Enforce the FILER_IS_PUBLIC_DEFAULT
                file_obj.is_public = settings.MEDIA_IS_PUBLIC_DEFAULT
                file_obj.folder = folder
                file_obj.save()
                # TODO: Deprecated/refactor
                # clipboard_item = ClipboardItem(
                #    clipboard=clipboard, file=file_obj)
                # clipboard_item.save()
                json_response = {
                    'thumbnail': file_obj.icons['32'],
                    'alt_text': '',
                    'label': str(file_obj),
                    'file_id': file_obj.pk,
                }
                return HttpResponse(json.dumps(json_response),
                                    **response_params)
            else:
                form_errors = '; '.join(['%s: %s' % (
                    field,
                    ', '.join(errors)) for field, errors in list(uploadform.errors.items())
                ])
                raise UploadException(
                    "AJAX request not valid: form invalid '%s'" % (form_errors,))
        except UploadException as e:
            return HttpResponse(json.dumps({'error': str(e)}),
                                **response_params)
84590
def get_json_response(self, content, **kwargs):
        """"""

        # Don't care to return a django form or view in the response here.
        # Remove those from the context.
        if isinstance(content, dict):
            response_content = {k: deepcopy(v) for k, v in content.items()
                                if k not in ('form', 'view') or k in ('form', 'view')
                                and not isinstance(v, (Form, View))}
        else:
            response_content = content

        return HttpResponse(content=json.dumps(response_content),
                            content_type='application/json; charset=utf-8',
                            **kwargs)
1322071
def form_valid(self, form):
        
        form.save()
        return super(SubscriptionView, self).form_valid(form)
1014095
function renderJSON( request, reply, err, result ){
	if(err){
		if(err.code === 404){
			reply(new hapi.error.notFound(err.message));
		}else{
			reply(new hapi.error.badRequest(err.message));
		}
	}else{
		reply(result).type('application/json; charset=utf-8');
	}
}
50435
def post(self, request, **resources):
        
        if not self._meta.form:
            return None

        form = self._meta.form(request.data, **resources)
        if form.is_valid():
            return form.save()

        raise FormError(form)
26829
def render(self, form=None, **kwargs):
        
        form = form or self.get_form()
        context = self.get_context_data(form, **kwargs)
        return self.render_to_response(context)
1036369
def _as_json(self, response):
        
        # Assume ClientResponse has "body", and otherwise it's a requests.Response
        content = response.text() if hasattr(response, "body") else response.text
        try:
            return json.loads(content)
        except ValueError:
            raise DeserializationError(
                "Error occurred in deserializing the response body.")
1188430
def get_content_json(request):
    """"""
    result = _get_content_json()

    resp = request.response
    resp.status = "200 OK"
    resp.content_type = 'application/json'
    resp.body = json.dumps(result)
    return result, resp
930489
def get_json(response):
    """"""

    json_field_or_function = getattr(response, 'json', None)
    if callable(json_field_or_function):
        return response.json()
    else:
        return jsonutils.loads(response.content)
988518
def render_to_json_response(self, context, **response_kwargs):
        
        return HttpResponse(
            self.convert_context_to_json(context),
            content_type='application/json',
            **response_kwargs
        )
998039
def form_valid(self, form, forms):
        
        if self.object:
            form.save()
            for (formobj, linkerfield) in forms:
                if form != formobj:
                    formobj.save()
        else:
            self.object = form.save()
            for (formobj, linkerfield) in forms:
                if form != formobj:
                    setattr(formobj.instance, linkerfield, self.object)
                    formobj.save()
        return HttpResponseRedirect(self.get_success_url())
199004
def json(
    body,
    status=200,
    headers=None,
    content_type="application/json",
    dumps=json_dumps,
    **kwargs
):
    
    return HTTPResponse(
        dumps(body, **kwargs),
        headers=headers,
        status=status,
        content_type=content_type,
    )
1156202
def post(self, request, *args, **kwargs):
        
        self.object = self.get_object()
        self.get_context_data()
        inlines = self.construct_inlines()

        if all_valid(inlines):
            return self.forms_valid(inlines)
        return self.forms_invalid(inlines)