article

Sunday, March 23, 2014

Making AJAX request with JSON

Making AJAX request with JSON


 testjson.js
 
$.post("http://localhost/demo/controller/function", {'name1' : value1, 'name2' : value2}, //name1 is the name of the parameter that send, something similar to name1=val1&name2=val2
    function(data)
    {
        $.each(data.items, function(i,item){
            alert("value: "+item.value+" name: "+item.name); //item.value e item.name because in the data object the information is set in this way: [{value:name},{value:name}...]
        });
    }, "json"
 );

Controller
 
function funcion()
 {
   $data["my_data"] = $this->example_model->get_examples($this->input->post('name1'),$this->input->post('name2'));
   //$data["my_data"] will contain an array like Array("0" => Array("value" => value1, "name" => name1), "1" => Array("value" => value2, "name" => name2)...)
   $this->load->view('json/json_example_view',$data);
 }

View
 
<?php echo json_encode($datos); ?>

Related Post