Syed Syed - 4 months ago 21
JSON Question

Call JSON data from External file using Ajax

I'm calling a external JS file having some sample JSON code, when I try to put sample json code in the file, it throws me error at ":", but when I validate that using online tools, it says as valid json. What is going wrong in this code?

Here is my code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>


<script>
$(document).ready(function() {

$('#click').click(function() {
$.ajax({
url: "json.js",
method: "GET",
dataType: 'application/json',
contentType: "application/json",
success: function(result){
console.log(result);
},
error:function() {
alert("Error")
}
});
});
});
</script>


My external json.js

{
"data": [{ ------> throwing error at ":" as Syntax error on token ":", ; expected
"Service": "INSTACC",

"Create Date": "30-Jul-2016"


}, {
"Service": "INSTACC",

"Create Date": "30-Jul-2016"


}]

}

Answer

Change your file type to json and dataType to "json"

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script>
$(document).ready(function() {

    $('#click').click(function() {
        $.ajax({
            url: "json.json",
            method: "GET",
            dataType: 'json',
             success: function(result){
                  console.log(result);
             },
             error:function() {
                 alert("Error")                  
             }
        });
    });
});
</script>