newdev
newdev

Reputation: 13

How to update JSON call URL onclick

I need getJSON call to update the URL to the selected name as choosen by button clicked and to fetch the data associated with the choice.

It currently updates name, but does not fetch new data from new URL.

<a href="info.php?name=Name1" onclick="name1()">Name1</a>
<a href="info.php?name=Name2" onclick="name2()">Name2</a>
<a href="info.php?name=Name3" onclick="name3()">Name3</a>
let name_url = "name.com";

function name1() {
    name_url = "1.name.com";
};

function name2() {
    name_url = "2.name.com";
};

function name3() {
    name_url = "3.name.com";
};

$.getJSON('https://'+name_url+'/name-info?name-id=1&name=' + theName, function(data) {

        var loading = $('.loading');   
        var nameData = $('#nameResults'); 
        var avgBlockTime = (data['avg-block-time']/1000)

    $.ajaxSetup({
        async: true
    });

    $.ajaxSetup({
        async: false
    });

I expect different data to populate the refreshed webpage.

Upvotes: 0

Views: 1325

Answers (1)

charlietfl
charlietfl

Reputation: 171690

Simplest approach is to use jQuery event listener and get the href of element clicked when you click it.

You have already set the query params within the href attribute of each link so the whole url can be obtained very simply

HTML

<a class="ajax-link" href="info.php?name=Name1">Name1</a>
<a class="ajax-link" href="info.php?name=Name2">Name2</a>
<a class="ajax-link" href="info.php?name=Name3">Name3</a>

JS

$(function(){    
    $('.ajax-link').click(function(event){
       // prevent browser opening in new page
       event.preventDefault();
       // `this` is `<a>` instance and it has an `href` property that is full url needed
       $.getJSON( this.href, function(data) {
          // do stuff with response data
          ...
       });  
    });    
});

Upvotes: 2

Related Questions