Stevin George
Stevin George

Reputation: 27

How i call controller function from below javascript code in view page(Codeigniter)

This is the javascript code that which used in core PHP for saving data entered in google map. I want to pass the values in the variable 'url' to controller function in Codeigniter. what should i do?

function saveData() {
            var name = escape(document.getElementById('name').value);
            var address = escape(document.getElementById('address').value);
            var type = document.getElementById('type').value;
            var latlng = marker.getPosition();
            var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address +
                      '&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();      

            downloadUrl(url, function(data, responseCode) {

              if (responseCode == 200 && data.length <= 1) {
                infowindow.close();
                messagewindow.open(map, marker);
              }
            });
          }

          function downloadUrl(url, callback) {
            var request = window.ActiveXObject ?
                new ActiveXObject('Microsoft.XMLHTTP') :
                new XMLHttpRequest;

            request.onreadystatechange = function() {
              if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request.responseText, request.status);
              }
            };

            request.open('GET', url, true);
            request.send(null);
          }

          function doNothing () {
          }

Upvotes: 0

Views: 1199

Answers (2)

ramin ashrafimanesh
ramin ashrafimanesh

Reputation: 1062

Just try use and replace {controllerName} into your controller name and replace {functionName} into controller method name:

var url = '<?php echo base_url(); ?>{controllerName}/{functionName}?name=' + name + '&address=' + address +
                  '&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();

Upvotes: 0

DFriend
DFriend

Reputation: 8964

To fetch the parameters from a GET request use the CI library input. Documentation HERE.

Here's a simplified version for demonstration purposes starting with the view file viewMap.php

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <button value="test" id='mapsave'>Click Me</button>
        <div id="response"></div>

        <script>
            var el = document.getElementById("mapsave");
            el.addEventListener("click", saveData, false);

            function saveData() {
                var res = document.getElementById("response");
                var request = new XMLHttpRequest();
                var name, url;
                name = "Stevin";
                url = "<?= base_url('maps/insert_church_details?name='); ?>" + name;    

                request.onreadystatechange = function () {
                    if (request.readyState == 4) {
                        res.innerHTML = request.responseText;
                    }
                };
                request.open('GET', url, true);
                request.send();
                }
        </script>       
    </body>
</html>

Here is the controller. I've renamed it simply Maps instead of mapController because it simplifies URLs. Who want's to go http://example.com/mapController ? Also, mapController violates CodeIgniter class naming conventions. (Better explained HERE)

class Maps extends CI_Controller
{

    public function index()
    {
        $this->load->view('viewMap');
    }

    public function insert_church_details()
    {
        echo $this->input->get('name');
        //exit; <- Bad idea for CodeIgniter
    }
}

In this example we only have the one item in the query string and we use input->get('name') to fetch it. The parameter passed to get() is the name of item. If we have several items we can fetch them one at a time or use get() without a parameter and capture all the items in an array. (See the docs if that doesn't make sense.)

Calling exit or die in CodeIgniter is a bad habit - not recommended. We're not doing procedural programming here. Using them will short-circuit the framework's normal execution path and, in this case, bypass several "hook" points that might be defined. Let functions return and have CI follow its normal execution path.

It's important to know that the call to base_url() only works because the JavaScript is included inline. If you load the js from an external file (e.g. <script src="assets/js/maps.js"></script>) it will not evaluate correctly.

You'll have to find another way to create a full URL, or use a relative URL.

Here's how to use an external js file, send and fetch a couple of parameters, use a relative URL, and respond with and utilize json.

The view

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <button value="test" id='mapsave'>Click Me</button>
        <div id="response"></div>

        <script src="assets/js/maps.js"></script>       
    </body>
</html>

The Controller

class Maps extends CI_Controller
{

    public function index()
    {
        $this->load->view('viewMap');
    }

    public function insert_church_details()
    {
        $name = $this->input->get('name');
        $addr = $this->input->get('address');
        echo json_encode(['name' => $name, 'addr' => $addr]);
    }
}

The javascript

var el = document.getElementById("mapsave");
el.addEventListener("click", saveData, false);

function saveData() {
    var res = document.getElementById("response");
    var request = new XMLHttpRequest();
    var name, url, address;
    name = "Stevin";
    address = 'Home';
    url = '/maps/insert_church_details?name=' + name + '&address=' + address;

    request.onreadystatechange = function () {
        var out;
        if (request.readyState == 4) {
            out = JSON.parse(request.responseText);
            res.innerHTML = out.name + ", " + out.addr;
        }
    };

    request.open('GET', url, true);
    request.send();
}

Upvotes: 1

Related Questions