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

248
Views
jQuery ajax requests repeats when error occurs

I've read through several posts related this this kind of issue, but I'm still not identifying the issue here.

When the following function is called and receives a 200 response, all is well; when it encounters 404 the ajax is repeated; adding a timeout only limits the time frame during which the repeat requests are made. There has to be a simple reason for this, but it is eluding me ...

function myFunction(ID) {
    var url = 'http://example.org/' + ID;
    var response;
    $.ajax(url, {
        success: function (responseText) {
            if (responseText !== undefined) {
              response = responseText;
            }
        },
        error: function (xhr, ajaxOptions, errorMsg) {
            if (xhr.status == 404) {
                console.log('404: ' + errorMsg);
            } else if (xhr.status == 401) {
                console.log('401: ' + errorMsg);
            }
        }
    });
    return response;
}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use the below given approach to get the data for your error without repetition in AJAX.

$.ajax(url, {
    success: function (responseText) {
        if (responseText !== undefined) {
          response = responseText;
        }
    },
    error: function (xhr) {
        //the status is in xhr.status;
        //the message if any is in xhr.statusText;
    }
});

UPDATE

You cannot return the response because you have an async request and response variable will be returned before the actual ajax requests gives a response. So I suggest You either use a callback function on success ore use a synchronous request.

So to get the response you can have a function like so:

function getResponse() {
    return $.ajax({
        type: "GET",
        url: your_url,
        async: false
    }).responseText;
}

Or the callback approach is:

$.ajax(url, {
    success: function (responseText) {
        if (responseText !== undefined) {
            theCallbackFunction(responseText);
        }
    },
    error: function (xhr) {
        //the status is in xhr.status;
        //the message if any is in xhr.statusText;
    }
});

function theCallbackFunction(data)
{
    //do processing with the ajax response
}
about 4 years ago · Santiago Trujillo Report
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!