1

I'm new to javascript which should be really simple to solve, but I am lost as of now.

I have a url: http:getall.json Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.

user3316454
  • 89
  • 2
  • 7
  • 1
    it may helpful for you, http://stackoverflow.com/questions/20743186/get-json-array-with-pure-js – Suman Bogati Feb 16 '14 at 17:34
  • The url you have provided throws an error and doesn't return any JSON string. Some PHP Session stuff crash. Also if you want to be able to make cross domain AJAX calls the remote server should explicitly allow CORS or support JSONP. Is this the case? – Darin Dimitrov Feb 16 '14 at 17:39
  • @DarinDimitrov why is that so? i can access the url. – user3316454 Feb 16 '14 at 17:42
  • Yes, me too, except that it doesn't return JSON but some PHP error. Maybe you need to be authenticated in order to be able to call it. It this the case? Try opening it in a new private browser tab and you will see the error. – Darin Dimitrov Feb 16 '14 at 17:42
  • @DarinDimitrov i've edited my question and paste the json that im getting from the url – user3316454 Feb 16 '14 at 17:44
  • Unfortunately you seem to be the only one not getting an error when calling this url. Anyway, does this endpoint support CORS? If it doesn't you will not be able to make a cross domain AJAX call to it. In this case you might need to call it from your server side script. – Darin Dimitrov Feb 16 '14 at 17:46
  • @DarinDimitrov will you show me how to get that json when i test the code in jsfiddle.net using purely javascript only? by the way thanks for your reply! :) – user3316454 Feb 16 '14 at 17:47
  • 1
    I cannot show you because this url doesn't work for me. It crashes with a PHP error. Besides you are not answering my question whether this endpoint supports CORS. Because if it doesn't you cannot make an AJAX call to it. As far as making an AJAX call is concerned, then MamaWalter already provided you an answer. But it won't work if the endpoint doesn't support CORS. – Darin Dimitrov Feb 16 '14 at 17:48
  • i can't contact the server now. and honestly i dont know what CORS is. if i try to upload this json to a free server for testing will u be able to help me? thanks! – user3316454 Feb 16 '14 at 17:52
  • If you don't know what CORS is then I very strongly recommend you read about it: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing Otherwise you will not be able to make cross domain AJAX requests. And of course that we will help you if you provide an endpoint that works and which supports CORS. – Darin Dimitrov Feb 16 '14 at 17:53
  • @DarinDimitrov i know how to parse json, my only problem is i dont know how to get a json from URL. do you have any sample code that i can test? thanks! – user3316454 Feb 16 '14 at 17:55
  • Yes, there are already 2 answers to your questions showing how to make an AJAX request. Except that they won't work if the endpoint you are calling doesn't support CORS. So the first thing that should be done is to ensure that the server side script that is returning this JSON sets the proper CORS response headers in order to allow cross domain calls. I very strongly suggest you reading about CORS first. – Darin Dimitrov Feb 16 '14 at 17:55
  • thanks @DarinDimitrov but i dont need ajax request, i need a purely javascript request – user3316454 Feb 16 '14 at 18:04
  • thanks @DarinDimitrov but i dont need ajax request, i need a purely javascript request – user3316454 Feb 16 '14 at 18:05
  • AJAX is pure javascript. The 2 answers that were provided use the native `XMLHttpRequest` object and do not rely on any framework such as jQuery. – Darin Dimitrov Feb 16 '14 at 18:05

3 Answers3

3

access to your url doesn't work, you should show the JSON result. In javascript to get JSON object with AJAX request you can do something like this:

request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Success!
    data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

your result will be in the data variable.

MamaWalter
  • 2,073
  • 1
  • 18
  • 27
  • thanks for the answer! but i tested this code in jsfiddle.net but it doesn't give me the result? what should i do? thanks! – user3316454 Feb 16 '14 at 17:37
  • all i want is to see the json result if i paste it in jsfiddle? – user3316454 Feb 16 '14 at 17:38
  • 2
    It doesn't work because the url you provided doesn't return JSON but it returns some PHP error. Also you cannot make cross domain AJAX calls unless the remote server explicitly allows it. – Darin Dimitrov Feb 16 '14 at 17:40
1

JSONP calls:

function getJSONP(url, callback) {
    var script = document.createElement('script');
    var callbackName = "jsonpcallback_" + new Date().getTime();
    window[callbackName] = function (json) {
        callback(json);
    };
    script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;

    document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
    //jsonObject is what you want
});

Regular ajax ajax call:

function getXHR() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    try {
        return new ActiveXObject('MSXML2.XMLHTTP.6.0');
    } catch (e) {
        try {
            // The fallback.
            return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        } catch (e) {
            throw new Error("This browser does not support XMLHttpRequest.");
        }
    }
}

function getJSON(url, callback) {
    req = getXHR();
    req.open("GET", url);
    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var jsonObject = null,
                status;
            try {
                jsonObject = JSON.parse(req.responseText);
                status = "success";
            } catch (e) {
                status = "Invalid JSON string[" + e + "]";
            }
            callback(jsonObject, status, this);
        }
    };
    req.onerror = function () {
        callback(null, "error", null);
    };
    req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
    //jsonObject is what you want
});

I tested these with your url and it seems like you should get the data with a jsonp call, because with regular ajax call it returns:

No 'Access-Control-Allow-Origin' header is present on the requested resource

with jsonp it gets the data but the data is not a valid json, it seems your server side has some php errors:

A PHP Error was encountered

...
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
  • hi @Mehran Hatami i tested your code in jsfiddle.net but it wont give me the result and i also edited this part getJSON("yourjsonurl.json", function (jsonObject, status, xhr) { alert (jsonObject); }); – user3316454 Feb 16 '14 at 18:02
1

In your HTML include your json file and a js code as modules

<script src="/locales/tshared.js"  type="module"  ></script>
<script src="/scripts/shared.js" type="module"  ></script>

file content of tshared

export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;

Adapt path and names as needed, use locale at will.

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42