0

i have this code, the alert works pefectly and returns the correct value grom the php file, but the Var is always undefined:

var NombreUrl;

function marck(id) {
  $.ajax({ 
    data: { id_propiedad: id },
    type: "GET",
    dataType: "json",  
    url: "/ajax/armarURL.php", 
    success: function(respuesta) {
      alert(respuesta);
      NombreUrl = respuesta;
    },
    error: function(respuesta) {
      NombreUrl = 'error';
      //alert('no');
    }                                       
  });
  $( "#listado" ).append( '<li id="marca'+id+'"><a href="'+NombreUrl+'">test</a></li>' );
}

The php file is returning this:

$nombreURL = 'test.php';
echo json_encode($nombreURL);

im having an alert whit "test.php" but the NombreUrl var is undefined. any ideas? Thanks!

Andy
  • 61,948
  • 13
  • 68
  • 95
Lort hand
  • 3
  • 3

1 Answers1

1

Ajax is asynchronous. You need to move your line that starts:

$( "#listado" ).append( '<li id="marca...

into your success function, like so:

success: function(respuesta) {
  alert(respuesta);
  NombreUrl = respuesta;
  $( "#listado" ).append( '<li id="marca...
},
Andy
  • 61,948
  • 13
  • 68
  • 95