Ss-utils "Soft Redirect" doesn't work

Just noticed a feature in ss-utils called Server Initiated Actions more specifically the “Soft Redirect” on ajax form submissions.

I’m curious on how it works because it doesn’t seem to do a soft redirect. I’m probably using the wrong $.ajax() is my assumption. Or we need to manually add a check for the header X-Location? Or is there another way?

// In a Service class:
public HttpResult Any(MyRequest request)
        {
            // Do Stuff

            return HttpResult.SoftRedirect("/home");
        }

The clientside ajax is:

$(formId).submit(function(e) {
    e.preventDefault();
    var $form = $(this);
    if (!$form.valid()) {
      return false;
    }
    $(submitId).attr("disabled", "disabled");
        $.ajax({
      type: $form.attr("method"),
      url: $form.attr("action"),
      data: $form.serialize(),
      dataType: "JSON",
      success: function(data) {
        // if not a soft-redirect then do:
        $form.hide();
        document.getElementById("viewAfterSubmit").scrollIntoView();
      },
      error: function(xhr, err, status) {
        $(submitId).removeAttr("disabled");
        var r = JSON.parse(xhr.responseText);
        var errStatus = r && r.responseStatus;

        if ($form) {
              $($form).applyErrors(errStatus);
        }
        return;
      }
    });
    return true;
  });

It can only work if you’re using a client library that handles it like ss-utils bindForm() or ajaxSubmit() APIs.

FYI this is the code that handles it:

1 Like

Just a FYI… Probably because I’m not using bindForm() or ajaxSubmit(), but I get a client side error:

JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

The error happens within the client side .ajax() and causes the error: function(xhr, err, status) {} to be triggered.

when using

return HttpResult.SoftRedirect(myUrl);

The way to fix it is to return:

return new HttpResult
            {
                Headers =
                {
                    { "X-Location", myUrl }
                }
                , Response = new {}
            };

I’m guessing since the Response is undefined or empty is causing the JSON.Parse error.

Right you can’t parse an empty JSON response. You can test this JS behavior in any browser, e.g:

JSON.parse("")

VM199:1 Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

If your Service doesn’t return a JSON response your client shouldn’t be trying to parse it as JSON.

Right. It caught me off guard, because the code isn’t directly calling JSON.parse() rather it must be doing it internally in the .ajax() code.