How to store the JSON value fetch from a URL using JQuery?

ajax get json from url
ajax json
javascript get data from url
ajax read json file
json call
javascript get json from url without jquery
how to display json data in html using ajax
getjson return data

I am new to JQuery. I am trying to develop a small travel website for checking PNR. I am currently using an API provided by one of the travel company. As soon as we hit the API Url, browser displays the result in JSON format.

I am using JQuery, JS and HTML. I want to know how to store the JSON value (in string format) retrieved from hitting an API, in a variable and use it later in the script.

PS: Though I have found many answer in Stackoverflow but none of the result works. Kindly help with the appropriate value.

Sample Code: (I am using one textbox and button)

    <script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;

//Suggest the code here, to fetch the result from url and store in the variable result.

</script>

<input type="text" placeholder="Enter PNR" id ="input_pnr"/>
<input type="button" value="Search PNR" onclick="search_pnr()"/>

Below is the JSON value getting from server

{"to_station": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "total_passengers": 1, "pnr": "6717552286", "journey_class": {"name": null, "code": "3A"}, "train": {"classes": [{"available": "N", "name": "SECOND AC", "code": "2A"}, {"available": "Y", "name": "THIRD AC", "code": "3A"}, {"available": "N", "name": "SECOND SEATING", "code": "2S"}, {"available": "N", "name": "FIRST AC", "code": "1A"}, {"available": "Y", "name": "AC CHAIR CAR", "code": "CC"}, {"available": "N", "name": "FIRST CLASS", "code": "FC"}, {"available": "N", "name": "3rd AC ECONOMY", "code": "3E"}, {"available": "N", "name": "SLEEPER CLASS", "code": "SL"}], "days": [{"code": "MON", "runs": "N"}, {"code": "TUE", "runs": "Y"}, {"code": "WED", "runs": "N"}, {"code": "THU", "runs": "Y"}, {"code": "FRI", "runs": "N"}, {"code": "SAT", "runs": "Y"}, {"code": "SUN", "runs": "N"}], "number": "22405", "name": "BGP-ANVT GARIB RATH"}, "from_station": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "passengers": [{"booking_status": "CNF/G12/36/GN", "no": 1, "current_status": "CNF/-/0/GN"}], "reservation_upto": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "response_code": 200, "boarding_point": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "debit": 3, "doj": "25-08-2018", "chart_prepared": false}

Kindly also help how to read both the objects and array in the given JSON.


You can use ajax to fetch the result from the url

var result;
var url = "http://api website/pnr"+pnr;
$.ajax
({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: function(data)
    {
        result = data;
        alert(JSON.stringify(data));
    }
});

JavaScript, JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and  Using JavaScript Fetch API to Retrieve sample JSON data A while ago I wrote an article called Using jQuery.AJAX() to Retrieve Sample JSON Data . Since this time I’ve been slowly using more and more native JavaScript to get things done, so I thought it was time to revisit this concept using the fetch() API.


You just need to parse JSON and how to read each object. This should give you good start

$.ajax({
    type: "GET",
    url: "http://api_website/pnr"+pnr,
    data: data,
    success: function(resultData) { 
        console.log(resultData);

        var to_station = resultData.to_station;
        var trains = resultData.train;
        var passengers = resultData.passengers;

        alert("Station Name: "to_station.name);
        alert("Passengers: "passengers.booking_status);


    },
    error(function() { 
        alert("Something went wrong"); 
    }
});

You can read more bout how to read JSON here.

jQuery.getJSON(), getJSON( url [, data ] [, success ] )Returns: jqXHR A plain object or string that is sent to the server with the request. most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different Collection Manipulation · Data Storage · DOM Element Methods · Setup Methods. I am currently using an API provided by one of the travel company. As soon as we hit the API Url, browser displays the result in JSON format. I am using JQuery, JS and HTML. I want to know how to store the JSON value (in string format) retrieved from hitting an API, in a variable and use it later in the script.


$.ajax({
  method: "GET",
  url: url
})
  .done(function( data ) {
    console.log(data)
    // see what properties you need from data object and save it to variable
    var data = data
  });

jQuery.get(), jQuery.get( url [, data ] [, success ] [, dataType ] )Returns: jqXHR A plain object or string that is sent to the server with the request. text string, JavaScript file, or JSON object, depending on the MIME type of the response. to the same origin policy; the request can not successfully retrieve data from a different domain,  First, we will fetch the JSON data by using the fetch API. This will return a promise with our JSON data. Then we will append the data dynamically by creating HTML elements on the fly. We will then append our JSON data to those elements. Getting JSON data from an API and display it on a web page is a common thing you will do quite often.


First thing,

Use a javascript file....API calls are better off done in a js file rather than in a script tag. Second thing, if you want to store it in a json format, you can store it in a value like the way you have declared your url variable. Since, you are fetching the data, I'm assuming this is a get request, you can find more information about them in the following links -

  1. https://www.sitepoint.com/ajaxjquery-getjson-simple-example/
  2. https://api.jquery.com/jquery.get

Also, if the data isn't very sensitive, you can store it in the local storage of your browser, so that you can access it later on in other web pages as well.

In your current json data, I would say that if you declare it to a variable say apiResult Your to_station would be apiResult.to_station, the lng value would be apiResult.to_station.lng and so on.

How to retrieve data from JSON file using jQuery and Ajax?, The jQuery. getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server. callback − This optional parameter represents a function to be executed whenever the data is loaded successfully. jQuery.getJSON( url [, data ] [, success ] )Returns: jqXHR. Description: Load JSON-encoded data from the server using a GET HTTP request. A string containing the URL to which the request is sent. A plain object or string that is sent to the server with the request.


Hope any of this helps, and good luck.

Everyone already added the AJAX examples, so I will leave that out.

So for reading the objects, you just have to parse what you need through various means, if you know what the object looks like and exactly what you need you can use dot notation. If you are looking to grab things more dynamically you can using higher order functions or for loops as well as Object prototypes example getting the entries (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)

You might consider using localStorage for storing the information depending on what you are using it for which is a built-in Web API here is MDN's definition

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Ajax/jQuery.getJSON Simple Example, Florian Rappl demonstrates how to use jQuery's getJSON helper to load formats such as BSON, where JSON-like objects are stored in a binary format. The url parameter is a string containing the URL to which the request is sent. function success(data) { // do something with data, which is an object }. As like as the previous example, we can do this by using JavaScript’s built-in JSON.parse() method. Using jQuery the $.parseJSON method will support this conversion and make it working in many obsolete web browsers. The following code uses jQuery to convert a JSON input string into a JavaScript Object.


How to fetch and parse JSON text (given in URL) through jQuery , To request a JSON data from url, using JavaScript fetch function : [code]// url (​required), options (optional) fetch( 'https://url', How do I fetch and parse JSON text (given in URL) through jQuery/JavaScript? Consider “res” as a variable that stores the JSON response from url alert(s.name) // prints the value of name​. } });. To retrieve data from JSON file using jQuery and Ajax, use the jQuery.getJSON( url, [data], [callback] ) The jQuery.getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. Here is the description of all the parameters used by this method − url − A string containing the URL to which the request is sent


JSON XMLHttpRequest, Use an array literal to declare an array of objects. Give each object two properties​: display and url. Name the array myArray: myArray. var myArray = [ json() - Lastly we have the method to that resolves the promise with JSON. Looking at all these methods the one we want is the JSON one because we want to handle our data as a JSON object so we add: fetch (url). then ((resp) => resp. json ()) // Transform the data into json. then (function (data) {// Create and append the li's to the ul})})


jQuery post() method, This tutorial shows how to send asynchronous http post request using jQuery. url: request url from which you want to submit & retrieve the data. data: json to submit in JSON format, where key is the name of a parameter and value is the  Using jQuery. As you can see, it's not too difficult to retrieve a JSON feed with plain JavaScript. However, it's even easier with jQuery, using the getJSON() function. If you don't know how jQuery works, you'll need to load the jQuery JavaScript library before any of this custom code.