vellai durai
vellai durai

Reputation: 1011

How to pass data-index value of anchor tag to controller in code igniter

I need to pass the data-index value of an anchor tag to controller in CodeIgniter.

Here is my view:

<?php for ($i=0; $i<5; $i++){?>
<a href="#" class='testing' data-index="<?= $i;?>" >testlink</a>
 //need to display the json data i am recieving from jquery here 
<?php }? >
}

Here is JQuery:

$('.testing').click(function() {

    $.ajax({
        url : "path_to_your_controller",
        data: {
            id: $(this).data("index")
        },
        type: "POST"
        success: function(data, textStatus, jqXHR)
        {
            console.log('success');
            console.log(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
          console.log('we are in error');
        }
    });

here is my controller

         $data= array('value' =>22,
                        'value2'       => 32,
                        'value3'       => 'foo',
                        'value4'       =>  'bar',
                        'value5'       => '122',


                );



echo json_encode($data);

How to display the json data from ajax request in php

Upvotes: 1

Views: 2062

Answers (2)

Ranjeet Singh
Ranjeet Singh

Reputation: 924

Instead of calling function over id, you must have to use of class

view file code

<?php
for ($i=0;$i<5;$i++){
?>
    <a href="#"  id="testing_<?php echo $i;?>" class="testing" data-index="<?php echo $i;?>">testlink</a>
<?php
}
?>

your script // pass dataType as json

$('.testing').click(function() {
        var a = $(this).data("index"); 
        $.ajax({
            type: "POST",
            dataType: "json",
            url: 'url to controller',
            data: {id:a},
            success: function(result) {
                // you can get here the result the result of ajax request.
                // get each value as key.value( of controller ).
                alert(result.value);
            },
            error: function(a,s,d) {
                console.log('error');
            } 
        });
    });

in your controller get this id as

// in controller function get id as like
$this->input->post('id');

Upvotes: 0

Petko Kostov
Petko Kostov

Reputation: 367

You could try something like this:

<?php for ($i=0; $i<5; $i++){?>
    <a href="#" class='testing' data-index="<?= $i;?>" >testlink</a>
<?php }? >

And then tha AJAX:

 $('.testing').click(function() {

        $.ajax({
            url : "path_to_your_controller",
            data: {
                id: $(this).data("index")
            },
            type: "POST"
            success: function(data, textStatus, jqXHR)
            {
                console.log('success');
                console.log(data);
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
              console.log('we are in error');
            }
        });

Upvotes: 1

Related Questions