Corona
Corona

Reputation: 374

How to make jQuery JSON request and use response data to change html element values?

I'm not good at JQuery at all, in fact this is my first encounter due to Shopify. In other words I'm completely lost.

This is what I was able to do so far.

function FindPlayer()
{

    var playerid = $('input[id=playerId]').val();
    var clubname = $('input[id=teamname]').val();


    $("#searchBar").attr('data-user-input', value);
    $.ajax({
        url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            response(data);
        }
    });

}

The json response is going to look like this:

  [{"playerFound":"true","tradeid":"123456"}]

I want to then check if playerFound is true or false before setting this element:

  <input id="tradeId" type="hidden" name="attributes[tradeid]" />

This is probably pretty basic for JQuery users but not for me any help would be appericiated.

Upvotes: 2

Views: 136

Answers (2)

ssilas777
ssilas777

Reputation: 9804

Since content type is JSON you can simply use like this

   success: function (data) {               
            if(data.playerFound == "true"){
                $('#tradeId').attr('name',data.tradeid) // if you want to change name
                $('#tradeId').val(data.tradeid)// if you want to change value
            }          
   }

Upvotes: 0

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Try This:-

$.ajax({
    url: "http://website.com/index.php?player=" + playerid + "&club=" + clubname,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if(data[0].playerFound == "true")
        {
           $('#tradeId').val(data[0].tradeid);
        }
    }
 });

Upvotes: 1

Related Questions