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

171
Views
window.location.replace unexpected behaviour

I have a button that when clicked, is initiating a POST request to my API. I then want to take the response URL from the API call and redirect to it.

This is what my JS look like:

function submitPassowrd(url) {
let xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
let u = xhr.responseText
if (xhr.status === 200) {
    window.location.replace(u);
    return false
}
return false
}

The problem is, that instead of redirecting to the URL from the API response, it is concatenating it to the base URL. So if the URL is http://example.com, it will just add it like: http://127.0.0.1:8081/http://example.com.

That said, when I am using a hard-coded URL, it works just fine and redirects me properly to the website provided in window.location.replace. For example:

function submitPassowrd(url) {
let password = document.getElementById('password').value;
let xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify();
let u = xhr.responseText
if (xhr.status === 200) {
    window.location.replace('http://example.com'); // <<<<<<< hard-coded URL
    return false
}
return false
}

Also, I tried using window.location.href which caused the exact same behavior.

What can explain this behavior?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should use window.location.href or simply window.location instead of window.location.replace for this use case imho.

That been said, the possible explanation for .replace behavior is that the url is encoded and thus not perceived as a url (rather a string only) and thus gets concatenated to the current page url. You can console.log the output of u to see if the returned string is encoded?

about 4 years ago · Juan Pablo Isaza 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!