Niqql
Niqql

Reputation: 430

Loading Json file in jquery fails in the following code

I got a huge problem!

I'm trying to load a Json file with Jquery but it always fails! I've tried many different things, but nothing worked for me . I am also not sure how to really debug it, what is wrong!

Here is my code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
    var url = "content.json";
    var outp = {
                    low         :   0,
                    high        :   99,
                    name        :   "Fritz",
                    rufnummer   :   "012",
                    faxnummer   :   "345",
                    mobil       :   "678",
                    mail        :   "[email protected]",  
                };

    $('#find').on("click", function(){

        var data = $.getJSON( url, function() {
          console.log( "success" );
        })
          .done(function() {
            console.log( "second success" );
          })
          .fail(function() {
            console.log( "error" );
          })
          .always(function() {
            console.log( "complete" );
          });

            console.log(data);      
            console.log(outp);
            console.log("Hi");

           data.complete(function() {
             console.log( "second complete" );
           });
        });
    });
//});
</script>
</head>
<body>
    <p>Postleitszahl:</p>
    <input type="number" autocomplete="on" name="inp" id="inp">
    <button type="button" id="find">Finden</button>
    <p class="output"></p>
</body>
</html>

Also here is my JSON:

{
    "low"         :   0,
    "high"        :   99,
    "name"        :   "Fritz",
    "rufnummer"   :   "012",
    "faxnummer"   :   "345",
    "mobil"       :   "678",
    "mail"        :   "[email protected]",  
}

Upvotes: 2

Views: 54

Answers (2)

pleinx
pleinx

Reputation: 626

You can do it like the answer from Roxoradev or try this:

data.complete(function() {
   console.log( data );
});

instead of

data.complete(function() {
   console.log( "second complete" );
});

Explain

Your deferred is now stored in data if you want do solve it call it with .complete(func) or .done(func)

From Docs:

The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.getJSON(), to chain multiple .done(), .always(), and .fail() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

So you can also write .done()

Upvotes: 0

Roxoradev
Roxoradev

Reputation: 893

Instead of:

var data = $.getJSON( url, function() {...})

Try with:

$.getJSON( url, function(data) {...})

Upvotes: 5

Related Questions