1

I have a code javascript

$(document).ready(function() {

            //datatables
            table_pertanyaan = $('#table_pertanyaan').DataTable({ 

                "processing": true, //Feature control the processing indicator.
                "serverSide": true, //Feature control DataTables' server-side processing mode.
                "order": [], //Initial no order.

                // Load data for the table's content from an Ajax source
                "ajax": {
                    "url": "<?php echo site_url('pertanyaan/ajax_list/')?>/" + id,
                    "type": "POST"
                },

                //Set column definition initialisation properties.
                "columnDefs": [
                { 
                    "targets": [ -1 ], //last column
                    "orderable": false, //set not orderable
                },
                ],

            });

And I have a parameter in URL localhost/ci/edit/87 87 is id.

How to I get variable from URL to use Javascript code?.

  • Have you tried something like `window.location.pathname.split("/").pop();` url ends with a `/` then it will return blank so be careful if you use that method. – NewToJS Oct 29 '17 at 10:32

2 Answers2

0

Due to this link,

So as an example if you had the following url with the javascript at the bottom in place.

http://papermashup.com/index.php?id=123&page=home

All you’d need to do to get the parameters id and page are to call this:

var first = getUrlVars()["id"];
var second = getUrlVars()["page"];

alert(first);
alert(second);

The Code

function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}

you can also visit these links:

https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters

https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript

https://www.sitepoint.com/get-url-parameters-with-javascript/
Fatemeh Abdollahei
  • 3,040
  • 1
  • 20
  • 25
0

There is a much better way to do this if you are using CodeIgniter.

This is an answer specific to your question which requires a JavaScript answer.

Assuming the url will always be having edit before id.

var url_parts = window.location.pathname.split('/');
var id =  url_parts[url_parts.indexOf("edit")+1];

If you want the CodeIgniter solution, I suggest you search for it because its already answered or comment and I'll tell you.

Paul K
  • 76
  • 2