2

I'm trying to get JSON string from an URL:

http://megarkarsa.com/gpsjson.php

The URL echoes JSON location value to be shown as string, with this result for example:

{"BMS":[{"id":"PR01","type":"prajurit","lat":"-6.253310","long":"107.156219"},{"id":"PR02","type":"prajurit","lat":"-6.224084","long":"106.653069"},{"id":"PR03","type":"kendaraan","lat":"-6.244316","long":"106.649734"}]}

I need to get this string from javascript, so i can parse it later with JSON.parse(string).

I have tried to use getJson, but seems it can't be done since it's not real Json value, but string.

How can i do that? Every suggestion will be appreciated.

3
  • 2
    JSON.stringify($yourJSONhere); Commented Sep 21, 2015 at 1:23
  • @aldrin27 the main problem here, is contrary of your suggestion. Because the JSON object is already in string form, and i need to get that string, so i can parse it later. Commented Sep 21, 2015 at 2:02
  • Then use $.parseJSON($jsonObj); after use $.each(); Commented Sep 21, 2015 at 2:21

3 Answers 3

4

Why not just jQuery ?

$.get('http://megarkarsa.com/gpsjson.php',function(data){
    console.log(data);
},'json');

or use php :

<?php
$json=file_get_contents('http://megarkarsa.com/gpsjson.php');
$json=json_decode($json,true);
?>

if you already did all and still not working, try :

$.get('http://megarkarsa.com/gpsjson.php',function(data){
    data = eval ("(" + data + ")");
    console.log(data);
});

The last solution is dangerous, use it if you trust the API you working with

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

6 Comments

Thank you for your answer, i tried it but didn't show any result. Do $.get({}, 'json') works same like $.getJson({})?
+1, the php file_get_contents does the job to get the string, and it is json_encode not json_decode. But, if i use php, i need to pass the value from php to javascript, and for some reason, i am not be able to do that (got a bit confused about the work). Or, can you point me an explanation, so i can pass the value from php to javascript (from different file)? Thank you
why cannot pass php to javascript ? @splim92
Simple reason, because I was kinda a bit unlucky before, every explanation i found, just made me confused. But i already found it out while ago before. To pass the value from json_encode, i just need to generate javascript global var and feed it with echo $json after the php code. Am i right?
+1, A big thank you. Those two jquery get function can only work at same domain or with a given permission. I prefer the php file_get_contents. Thank you again.
|
2

As Michael Antonio pointed out, using Ajax would be the way to do it. Heres my code

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON</title>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
    $(function() {
        $.ajax({
            url: 'http://megarkarsa.com/gpsjson.php',
            type: 'GET',
            dataType: 'html',
            success: function(data, status, xhr)
            {
                $("#json").html(data);
            },
            error: function(xhr, status, error)
            {
                $("#json").html("Error: " + status + " " + error);
            }
        });
    });
    </script>
</head>
<body>
    <div id="json"></div>
</body>
</html>

However, an error keeps cropping up. Here are the request/response headers, notice the response is force closing the connection.

Request

Host: megarkarsa.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://testsites.kalebklein.com/json1/json.html
Origin: http://testsites.kalebklein.com
Connection: keep-alive

Response

Connection: close
Content-Type: text/html
Date: Mon, 21 Sep 2015 01:52:56 GMT
Server: Apache
Transfer-Encoding: chunked
x-powered-by: PHP/5.4.36

Also notice that the content-type of the response is HTML, and should be JSON if you wish to parse the JSON using the above Ajax function I provided. The error coming back is not helpful whatsoever, meaning that the connection is being cut off or refused by making the Ajax call, and no data is being sent back.

5 Comments

+1, thank you for such a nice work and explanation. Yes, i tried it, and clearly, it's because cross-domain prevention. That means, you can only do your GET function at same domain with the json file. Am i right?
That would be the case. It's easily fixed if you have access to the server, and you can allow outside access through a simple .htaccess file
Thank you. Sorry if i am asking you too much, but can you point me any explanation link about how to set .htaccess permission? Thank you
I actually have an .htaccess that lets me do this on my server, add this to the .htaccess file in the root directory of your site Header set Access-Control-Allow-Origin "*"
Noted! I will add that. A big thank you! You saved my life.
1

You can do this as well :

str='{"BMS":[{"id":"PR01","type":"prajurit","lat":"-6.253310","long":"107.156219"},{"id":"PR02","type":"prajurit","lat":"-6.224084","long":"106.653069"},{"id":"PR03","type":"kendaraan","lat":"-6.244316","long":"106.649734"}]}'; //example string
obj=jQuery.parseJSON( (str)); //parse as json
$.each(obj, function (i, item) { //loop through each item in main obj
     $.each(item, function (i, y) { loop through each prop in item
         alert(y.id) //you can access the values like this others can be accessed via the dot notation such as y. prajurit
     });
});

2 Comments

Thank you for your answer, but the main problem for me now, how to get the string {"BMS":[{"id":...}]} from URL i've mentioned before. How to get the string from the URL?
Michael solution is relevant if you have access to the source code of that url as it does't allow access through ajax. In case if its not your source code then you can get the contents on server side

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.