-4

I'm trying to fetch data from URL with GET method on javascript,

fetch('/api/staffattendance/{makedate}')
  .then(res => res.json())
  .then(res => {
    //this.staffs = res.data;
    console.log(res.data);
  })
  .catch(err => console.log(err));

How can I pass the variable here:

fetch('/api/staffattendance/{makedate}')

Like this

enter image description here

Thanks in Advance,

xxx
  • 1,153
  • 1
  • 11
  • 23
ubakara samy
  • 159
  • 2
  • 3
  • 8
  • 1
    Did you search a bit? Maybe `\`my_string${my_variable}\`` is what you are looking for. Or string concatenation. There are plenty of solution available and well documented – Ulysse BN Jun 22 '18 at 07:50
  • 2
    Looks like you're trying to use [`Template Literals`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) – Alex Jun 22 '18 at 08:01
  • Does this answer your question? [Most efficient way to concatenate strings in JavaScript?](https://stackoverflow.com/questions/16696632/most-efficient-way-to-concatenate-strings-in-javascript) – miken32 Jan 17 '20 at 17:42

4 Answers4

6

One method is the string concatenation but js has introduced another mechanism called template literal:

Embed the string with `` and user variable with ${makedate}.

`/api/staffattendance/${makedate}`

Let me know if this helps.

Shreyak Upadhyay
  • 439
  • 6
  • 10
  • Hi guys, I tried all solution mention in this. but nothing worked. I want to fetch data for "vall" id, please help me. fetch('https://performancetestdmb.azurewebsites.net/api/products/'+vall+'/Category2') – Manpreet Dhiman Apr 07 '21 at 11:57
2

You can also put the string in backticks ``, and include ${yourVariable} where you want your variable, example:

  fetch(`/api/staffattendance/${makedate}`)
    .then(res => res.json())
    .then(res => {
      //this.staffs = res.data;
      console.log(res.data);
    })
    .catch(err => console.log(err));
miken32
  • 42,008
  • 16
  • 111
  • 154
1

Did you encompass the whole URL in acutes ( these little guys to the left of your '1' key) WHILE using this ${your-variable} around your JavaScript?

double-beep
  • 5,031
  • 17
  • 33
  • 41
ThirdGhostHand
  • 377
  • 5
  • 19
0
fetch('/api/staffattendance/'+makedate+'')

Simply concatenation works for me like this

ubakara samy
  • 159
  • 2
  • 3
  • 8