-1

I am trying to build a browser extension with key functionality including fetching a text input from html pages and concat it with a URL and fetch json from that concated URL.

I want to know how to fetch json from a URL to a variable using JavaScript.

This is the html script to grab the user inserted text.

<html>
<body>
<input type="text" id="search" name="Name" maxlength="10" class="searchField" autocomplete="off" title="" ><br>
  </p>
</form>
<p align="center">
<button type="button" id="srchbutton" style="background-color:Thistle;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:%"> Search</button>
</p>
<script language="javascript" type="text/javascript" src="thanq.js">
    var button= document.getElementById('srchbutton');
    button.onclick= linkprocess();
    console.log("hi there");
</script>
</body>
</html>

and this is the JavaScript in which I am trying to access the json from URL.

var oldlink='URL';
var newlink;
function linkprocess(links){
    var text= document.getElementById('search');
   newlink=oldlink+text;
   GetJson(newlink);
   console.log(newlink);
}
Joe
  • 4,877
  • 5
  • 30
  • 51
Abdul Rahim A
  • 23
  • 2
  • 6

2 Answers2

0

You can use xmlhttp request in pure javascript to do this. Take a look at this w3 schools article: JSON Http Request

To simplify the code written, you could you jQuerys $.get() or $.ajax() methods once you are comfortable with the mechanism.

hairmot
  • 2,975
  • 1
  • 13
  • 26
0

Or you can use the modern fetch API, e.g:

const searchVal = document.getElementById('search').value;

fetch('http://someprefix/' + searchVal)
  .then(response => response.json())
  .then(data => {
    console.log('Fetched:', data);
  })
  .catch(err => {
    console.error('Fetch error:', err);
  });
Dominic
  • 62,658
  • 20
  • 139
  • 163