Get data from ajax

0

I'm trying to get data through ajax and php. What I'm trying to do is have a list of several ids and that ajax shows them to me dynamically. My client wants to see a list of messages by clicking on each one, something like the icloud inbox.

JQuery:

$(document).ready(function(){
$('.enlaceajax').click(function(){
    $.ajax({
        type: 'GET',
        url: 'pagina-lenta.php',
        dataType: 'html',
        success: function (data) {
            $('.destino').html(data);
        }
    });
});
});

HTML:

<a href="<?=$fila['id'];?>">class="enlaceajax"></a>
<div class="destino"></div>

PHP:

$ide = $_GET['id'];

if($ide == 1) {
   echo 'Texto de ID 1';
}else {
   echo 'Error';
}

The error is that it does not give me any results. I do not know what I'm doing wrong, I hope you help me. Thanks.

    
asked by Benjamín Guzmán 07.01.2018 в 05:34
source

1 answer

1

You have several errors, I correct the code and I explain:

The first thing is the HTML , that you have a syntax error since you close the tag before adding the class, besides you do not select the parameter that we sent by Ajax , I recommend adding a data-id parameter, which you must fill in the ID ( PHP ):

<a href="#" data-id="<?=$fila['id'];?>" class="enlaceajax">Enlace</a>
<div class="destino"></div>

Next, the JS . You do not collect or pass the value, you must also make a preventDefault() of the event, so that the link is not executed:

$(document).ready(function(){
    $('.enlaceajax').click(function(e){
        e.preventDefault();
        $.ajax({
            type: 'GET',
            data: {'id' : $(this).data('id')},
            url: 'pagina-lenta.php',
            dataType: 'html',
            success: function (data) {
                $('.destino').html(data);
            }
        });
    });
});

As you can see, I have added the event stop to the function(e) function by assigning a parameter to the function (I personally use a e ) that will be the one that collects the event and passes it to the function, and also a parameter to the ajax function that is data, which collects and sends the data that interests us.

The% co_of% that you sample to test is correct, so it will work without modifying it.

Greetings,

    
answered by 08.01.2018 / 15:16
source