0

I have a php file saven on a different domain, and Im using this piece of code to send the username and with that get the info of the user.

Im trying to do something like this, but this is not working is there a way to do it.

var dataString = "username="+username+"";
    var url = "";

    $.ajax({
        type: "POST",
        url: url,
        data: dataString,
        crossDomain: true,
        cache: false,   
        success: $.getJSON(url, function(result)
        {
            console.log(result);
            $.each(result, function(i, field)
            {
                var id       = field.id;
                var username = field.username;
                var email    = field.email;

                $('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>"); 
            });
        })
    });
Pedro
  • 1,440
  • 2
  • 15
  • 36

1 Answers1

2

Replace the $.getJSON() function you have for the success calback provided by the jQuery ajax function, and you can pass directly the username through the data parameter as { username : username }, because it's already defined.

Then when you receive successfully your data you can iterate over each result using the jQuery $.each function.

Do you really need to set the cache parameter to false?, just to know.

Also if you want use let instead of var, those variables will be just within the $.each "block".

<script>
  var url = '';

  $.ajax({
    type: "POST",
    url: url,
    data: { username: username },
    crossDomain: true,
    cache: false,   
    success: function(result) {
      console.log(result);
      $.each(result, function(i, field) {
        let id = field.id,
          username = field.username,
          email = field.email;

        $('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>"); 
      });
    }
  });
</script>
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59