Mohammed Badr Alabsi
Mohammed Badr Alabsi

Reputation: 52

how to send data via ajax from view to controller on codeigniter?

i tried to send data from view to controller , but nothing work "ajax return error" i try all ways those i see in other similar question My view:

var pdata ={
    "latitude": lat,
    "longitude": log
};
latlog = "/"+1;
$.ajax({
    url: "<?php echo base_url(); ?>index.php/users/search"+CityINP+distINPx+CategoryINP+textINP+latlog,
    type: "POST",
    data: pdata,
    dataType: "JSON",
    success: function (data) {
        // if success reload ajax table
         alert("success");
        // reload_table();
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('Error adding / update data');
    }
});

my controller:

public function search($city=null,$dist=null,$cate=null,$text=null,$latlon=null)
{
}

Upvotes: 1

Views: 101

Answers (2)

Rishi
Rishi

Reputation: 483

At first, I will suggest you to make a js variable in header section like this

<script type="text/javascript">
        var BASE_URL = "<?php echo base_url(); ?>";
</script>

In this way, you won't have to write echo baseurl everytime in the URL.

$.ajax({
    type: 'POST',
    url: BASE_URL + "controllerName/search",
    data: {'CityINP': distINPx,'CategoryINP':latlog },
    success: function (data) {
    data = JSON.parse(data);
    if(data.response == "response")
    {
        //do anything you want from the response you get
    }
 }
});

To get the parameters in the controller function you can get it by the following code

$this->input->post('CityINP');
$this->input->post('CategoryINP');

Upvotes: 2

Divya Patel
Divya Patel

Reputation: 69

change your url url: "index.php/users/search"+CityINP+distINPx+CategoryINP+textINP+latlog,

to url: "index.php/users/search/"+CityINP+distINPx+CategoryINP+textINP+latlog,

"/" after search function name, in your url all variables are concat with search funaction name.

Upvotes: 0

Related Questions