Get value returned in a JS URL

Asked

Viewed 92 times

0

I need to create a very simple script that makes a small calculation.

I have a URL that returns a value in the following format: 10.00, something like this:

https://domain/api/products.php? pid=10&get=price&billingcycle=Monthly

I need to create a function that takes the value returned from that URL and subtracts that value (-5.00), then prints the result in a <span> that has a specific ID.

<span id="result"></span>

How can I create such a function?

1 answer

3


To request the API and calculate the result would be something like this:

function makeRequest() {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            calcPreco(xmlHttp.responseText);
    }
    xmlHttp.open("GET", "PONHA_SUA_URL_AQUI", true); // true para asynchronous 
    xmlHttp.send(null);
}

function calcPreco(preco) {
    preco = preco.replace(",", ".");
    preco -= 5;
    document.getElementById("result").textContent = preco;
}

To recover the price that is in a url parameter would be something like this:

function calcPreco(){
   let preco = new URL(location.href).searchParams.get("get");
   preco -= 5;
   document.getElementById("result").textContent=preco;
}


If you receive a number with , in the parameter (something like 10,50) do:

function calcPreco(){
   let preco = new URL(location.href).searchParams.get("get");
   preco = preco.replace(",", ".");
   preco -= 5;
   document.getElementById("result").textContent=preco;
}
  • Didn’t work here, is it why it returns the value with comma in the URL?

  • floating numbers in JS are with . instead of ,... It would, for example, 10.50 instead of 10,50

  • And is there any way to convert this into the function? Because I can’t change it in the API.

  • yes, just make a value replace... something like preco.replace(",", ".");... The response code has been fixed to add this useCase.

  • Weird, it’s not printing the result in span..

  • A doubt, what would be the searchParams.?

  • I believe I have misunderstood your problem, this solution takes the value passed by the url... what you really want is to make a request to this url and calculate the price on the right answer?

  • That, exactly...

  • checks if the new answer helps you

  • Do you have a specific way to call this function? I tried it here and I still can’t print the result.

  • depends on the logic of your code, could be for example: <body onload="makeRequest()">

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.