Welcome Guest, Not a member yet? Register   Sign In
AJAX AND JSON
#1

[eluser]sico87[/eluser]
Hello,


I have a website where I am wanting to get some query results through AJAX and JSON, but I have absolutly no idea how to do it, I have this function,

Code:
public function category() {
        $table = $this->uri->segment(2);
        $content_id = $this->uri->segment(3);
        $data['content'] = $this->site_model->get_content($table, $content_id);
        $this->load->view('template/right-content', $data);
    }

Essintially the query that is run is dynamic depending on what url is being passed, what I need to is, for the user clicks a link something like

Code:
<a href="/category/blog/1" id="blog">Read the blog</a>

From this link I get blog and 1 passed to the query, but I need to load the results in a view that is loaded in to my main template and then everytime a link is clicked do the same thing without overwriting the previous data, does anyone have any idea how to do this?
#2

[eluser]Ben Edmunds[/eluser]
If you are using jQuery look up the ajax and post functions.

If not look up Javascript XmlHttpRequest.
#3

[eluser]Jamie Rumbelow[/eluser]
You'll also need to check that the request is being made through AJAX - create an AJAX helper (create a applications/helper/ajax_helper.php file) and put this code in it:

Code:
function is_ajax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') ? TRUE : FALSE;
}

Then in your controller you can use that function to check if it's an AJAX request, rendering the JSON response if it is and the entire HTML page if it isn't. If you want a more robust API, have a look at Phil Sturgeon's REST library to implement a full API that works nice with JavaScript and CodeIgniter Smile

Jamie
#4

[eluser]Krzemo[/eluser]
Some code below from top of my head (no warranty though Wink)
Code:
//in da controller
function blog()
{
    $id = $this->input->post('id');
    if($this->_is_ajax())
    {
        $json = null;
        $json->results = $this->model_blog->get_blog($id);
        $this->output->set_header('Content-type: application/x-json');
        $d['message'] = json_encode($json);
        $this->load->view('admin/vjson_response_wrapper', $d); //this simple view just doing &lt;?=$message?&gt;
    }
    else
    {
      //here you put regular code for loading view if its not ajax (usefull when browser JS is off or it google indexing)
    }
}

//after Jamie
function _is_ajax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') ? TRUE : FALSE;
}


and the rest is done by javascript (me like jQuery)
Code:
//this is to be used with an event
        $.post('/admin/blog', {'id': $('input#id').val()},
                function(data){
                    $('input#username').val(data.username);
                    $('input#first_name').val(data.first_name);
                }
            , 'json');
#5

[eluser]asylmottaket[/eluser]
Here is what im using in the controller:


Code:
if($this->input->post('submit'))
{
    if ($this->form_validation->run('some_definition_from_config_file') === TRUE)
    {
        $post_array = $this->_post_array( $_POST );

        if($this->personalia_model->save_post($post_array))
        {
            if($this->_is_ajax())
            {
                // SOME AJAX RETURN STUFF
                // Set header, return som json_encoded blah blah
            }
            else
            {
                // IF NOT JAVASCRIPT, DO SOME OTHER STUFF
            
                $this->session->set_flashdata('status', 'Submission successful!');

                redirect('/admin/blog/view/' . $id);

                exit;
            }
        }
    }
    else
    {
        if($this->_is_ajax())
        {
            // OPTIONAL RETURN CI FORM VALIDATION ERRORS FROM validation_errors()
        }
    }
}


// AND THE OTHER METHODS THAT RETURN POST VALUES AND CHECKS IF AJAX IS USED

function _post_array($post_vars)
{
    $this->load->helper('security');
    
    $post_array = array();
    
    foreach ($post_vars as $key => $value)
    {    
        $post_array[$key] = xss_clean($value);
        
        if(substr($key, 0, 6) == 'submit')
        {
            unset($post_array[$key]);
        }
    }
    
    return $post_array;
}

function _is_ajax()
{
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}



I also use jQuery, and with the jQuery form plugin, ajax form submission is quite easy




Theme © iAndrew 2016 - Forum software by © MyBB