0

I have json file to store a number. I also have JS file to grab json data to be display in HTML.

As manual way to display is by put a number in XXX as below HTML code. So I want the data is dynamically get from back-end.

HTML

<span id="num"> XXX </span> number of users

JS

$(document).ready(function() {

    var ajaxRequest;

    console.log();

    ajaxRequest= $.ajax({
        url: "result/total.json",
        type: "post",
        dataType: 'json',
        data: {'num':num},
    });
});

JSON

{
  "data": [
    {
      "num": "100"
    }
  ]
}
2
  • 1
    Add a success function and append the backend data by id selector in it Commented Jun 20, 2019 at 8:25
  • are you getting or posting to this endpoint? What's num? Commented Jun 20, 2019 at 8:27

2 Answers 2

2

If I get your question right, you also want to read from that JSON file. For that you need another AJAX Call that gets the data from your file, and on the succes callback changes the HTML of that span.

Here's a quick example of how your callback should look like:

 $.ajax({
    url: "result/total.json",
    type: "get",
    dataType: 'json',
    success: function(data){
        //here you have access to your response object and you can use anything you want
        $("#num").html(data.responseText);
    }
});

If you want a better version, you can use a complete callback in case your call fails. This way you will have access to the error object also.

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

2 Comments

I already apply your code by insert additional code but nothing happen.
Dont assign jquery ajax to any variable
0

I found my answer by write this code.

$(document).ready(function() {

    var ajaxRequest;

    console.log();

    ajaxRequest= $.ajax({
        url: "result/total.json",
        type: "post",
        dataType: 'json',
        // data: {'num':num},

        success: function(data){
            console.log(data["data"][0]["num"]);
            //here you have access to your response object and you can use anything you want
            $("#num").html(data["data"][0]["num"]);
        }
    });    

});

Comments

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.