2

I am trying to pull json down from my server and parse it into a Javascript object. here is what my json looks like:

{
  "tour1": [
    {
      "title": "building1",
      "description": "Tour of building1",
      "image": "Icon.png",
      "video": "tour.mp4",
      "length": "0.00",
      "version": "1.0",
      "timestamp": "1111111111"
    }
  ]
}

Here is the requst to the server:

<!DOCTYPE html>
<html>
<body>
    <h2>Parse JSON from Server</h2>
    <p id="demo"></p>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">                      </script>
    <script>
        $.ajax({
            url: "mysite.com/videos/tour.json";
        var j = [];
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json',
        });
        window.alert(j.tour1[0].title);
    </script>
</body>
</html>

I cant understand why its not working. I am new to javascript. I appreciate any help with this issue.

3
  • 2
    Check ajax syntax Commented Dec 3, 2015 at 9:26
  • 1
    You have Syntax errors. I recomment you to use something like Visual Studio for this. Commented Dec 3, 2015 at 9:29
  • Please check the answers bellow upvote/downvote, comment, select the correct answer. Commented Dec 3, 2015 at 11:09

3 Answers 3

3

I think better if you use getJson when you want to load JSON-encoded data from the server using a GET HTTP request, check example bellow :

$.getJSON( "mysite.com/videos/tour.json", function( j ) {
     alert( j.tour1[0].title );
});

Hope this helps.

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

Comments

1

Ajax call is an asynchronous call, j is not populated as soon as your ajax statement ends.

Use success handler of Ajax to alert the j (didn't tested the code)

$.ajax({
  url: "mysite.com/videos/tour.json",
  method: "GET",
  dataType: "JSON",
  success: function( data ){
    window.alert(data.tour1[0].title);
  }
});

Comments

0

gurvinder give the best solution, because if you are firing the ajax-request then you must catch the response, but if you make the alert in your code your request is still working and j must be undefined because it is not a global variable. there a lot of mistakes:

  1. check your ajax-synthax , because the declaration of "var j.." is wrong,
  2. never use ";" in a object declaration, always use ","
  3. in your alert you try to find a variable "j", but j don't exist, it is undefined.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.