Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
How to handle multiple response types in ajax

Currently, I have a form, submitting which will redirect to an error page or download a file. However, recently server side was modified, and as for now, it could also return some JSON, which I need to handle. Thus, as far as I've got, you can't get a form submission result, I've made a POST call instead of a form, but how could I handle different return types? I ought to use jQuery for it, and currently it works as follows only for downloading:

$.ajax({
            url: 'some-url',
            type: 'POST',
            cache: false,
            data: {
                // some required data
            },
            xhrFields: {
                responseType: 'blob'
            },
            success: function(response, status, req) {
                if (response.hasSuggestions) {
                    // this code is prepared to work with JSON data
                    return;
                }

                var fileName = req.getResponseHeader('content-disposition').split('; ')[1].replace('filename=', '');

                var contentType = req.getResponseHeader('content-type');

                var blob = new Blob([response], { type: contentType });

                var isIE = false || !!document.documentMode;
                if (isIE) {
                    window.navigator.msSaveBlob(blob, fileName);
                } else {
                    var url = window.URL || window.webkitURL;
                    link = url.createObjectURL(blob);
                    var a = $("<a />");
                    a.attr("download", fileName);
                    a.attr("href", link);
                    $("body").append(a);
                    a[0].click();
                    a.remove();
                }
            },
        error: // some error handler
    })

And if server returns JSON data or redirect, I'm just getting "[object Blob]". I know, that it is due to response-type field, but how could I handle different types of response? P.S. If I'll not set a response-type, there will be a huge headache on properly converting string to blob

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!