0

I have a searchbox that is working with a local Json data (in the same file) using a var but now I would like to use with an external url json file in the same way that it works before.

What I have now:

var data1 = [{"test_id":"1","test":"test","test2":"test2"}];

What I'm trying:

var data = $.ajax({
  dataType: "json",
  url: 'myjsonurl',
  data: data
});

I've tried with getJSON and with other some recommendations but are not working as I expect, in the image you can see that I'm having the data in both ways but quite different and is not working in the searchbox.

Image: https://i.stack.imgur.com/kWKkz.png

You can find the searchbox here:

https://www.js-tutorials.com/javascript-tutorial/live-search-json-objects-data-using-jquery/

Is there any idea to get same data as I have now from an external file and use it into a var as the searchbox do?

Any ideas?

Thanks in advance,

Javier
  • 1
  • 1
  • 2

2 Answers2

0

The way you are doing is, what you are getting is XHR Object.

To get proper JSON response and to work on it, you can write a success function and handle response data there or just use getJSON.

For example:

$.getJSON('https://gist.githubusercontent.com/GeekAb/027c70bd21d006027cd91f538ae4694e/raw/68fda14df1b9fbf6835a02639aa210e88826d19d/SampleJSON', 
    function( data ) {
       console.log(data);
       console.log(data[0]);
       console.log(data[0]['employee_age']);
});

You can check this Bin link https://jsbin.com/cixezewisi/edit?html,js,console

GeekAb
  • 505
  • 4
  • 15
0

First off, you have a lot of options when it comes to importing data from an external file (some easier than others). The following list is from another stackoverflow post:

  1. ES6 import
  2. Node.js Require
  3. Ajax
  4. jQuery

I suggest checking out the link, as the poster gave great detail on these options.

Anyways, it looks like you are trying to implement this with Ajax. You basically got it down correctly. Based off the image, what your issue is that using ajax has stringified your data, which is expected. All you have to do is:

var data = $.ajax({
  dataType: "json",
  url: 'myjsonurl'
});

var parsedData = JSON.parse(data)

This will parse your data into the JS array you are looking for.

wnamen
  • 550
  • 3
  • 12