-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);
}
3
  • 1
    what browsers do you need to support? Commented Jan 10, 2017 at 9:29
  • Try out this $.getJSON('newlink', function(data) { console.log(data) }) Commented Jan 10, 2017 at 9:30
  • Use jQuery's $.getJSON() or learn raw XMLHttpRequests, which is what I recommend if you're learning. Commented Jan 10, 2017 at 9:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
  });

3 Comments

Just don't expect it to work on many a Browser.
Yep, you can load a polyfill - github.com/github/fetch, but this looks like more of an experiment than production code
@PHPglue - it doesn't work natively in IE, and the "new IE", which is Safari - otherwise support is pretty universal

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.