Welcome Guest, Not a member yet? Register   Sign In
Controller is firing but I can't get the $_GET
#17

(This post was last modified: 03-27-2018, 08:34 AM by jreklund.)

Here's how you do it.

References:
https://developer.mozilla.org/en-US/docs...ng_Started
https://zqzhang.github.io/blog/2016/04/1...-ajax.html
https://www.w3schools.com/xml/ajax_xmlht...create.asp
https://www.w3schools.com/js/js_json_parse.asp
https://www.codeigniter.com/user_guide/l...ntent_type

PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Json extends CI_Controller {
    
    public function 
register()
    {
        if( 
$this->input->is_ajax_request() )
        {
            
$json $this->input->raw_input_stream;
            
$json json_decode($json);
            
/**
            $json now looks like
                stdClass Object
                (
                    [lat] => 41.058304899999996
                    [long] => -74.0711244
                    [email] => [email protected]
                )
                
            Access it like
            echo $json->lat;
            **/
            
            // Process json...
            
            // Data to send back
            
$data = array('success' => 'true');
            
            
// Send back json
            
$this->output
                    
->set_content_type('application/json')
                    ->
set_output(json_encode($data));
        }
    }


Code:
<script type="text/javascript">
    var data = {"lat":41.058304899999996,"long":-74.0711244,"email":"[email protected]"};
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/json/register', true);
    
    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.setRequestHeader("X-Requested-With",'xmlhttprequest');

    xhr.onload = function () {
        // Request finished. Do processing here.
        if(xhr.status === 200) {
            var jsonResponse = JSON.parse(xhr.responseText);
            // Log the whole json object
            console.log(jsonResponse);
            // Access 'success' from the object
            console.log(jsonResponse.success);
        }
    };
    
    xhr.send(JSON.stringify(data));
    </script>
Reply


Messages In This Thread
RE: Controller is firing but I can't get the $_GET - by jreklund - 03-27-2018, 08:32 AM



Theme © iAndrew 2016 - Forum software by © MyBB