CodeIgniter, PHP, jQuery and AJAX

I am wondering how people use CodeIgniter and jQuery for AJAX.

In an AJAX request you have

{ url : ???, data : {a:1,b:2}, success: .... } 

So how do you create the url?

You

  • you have all your javascript in your view files and just use site_url() to create the url
  • You have all your JavaScript in external js files, you have a header that has something like <script>var base_url = '<?php echo site_url(); ?>';</script> <script>var base_url = '<?php echo site_url(); ?>';</script> . Then in your external js files there is url: base_url+'rest/of/path/';
  • any other method?
+4
source share
4 answers

I have all my js in an external file and load it into my template.

For specific ajax requests, just call the page as usual.

 $.ajax({ type: 'POST', url: '/ajax/login', data: blabla, success: function(data) { // do something }, dataType: 'json'); }); 

In response to your question, I did not need to specify the base url, since put '/' before the controller name automatically sets the root of the site. You can also use ../ etc

+4
source

if you write your ajax in an external file, then you can define your base url in a view file, for example

 <script> var base_url = '<?php echo base_url(); ?>'; </script> 

Then on your external ajax file write

 url : base_url+'controllerName/functionName', 
+2
source

You can also do this by loading a view containing your JavaScript.

I am currently loading JavaScript from the view at the end of the displayed page. Since it has a PHP file with html <script> , you can use helper URL functions like site_url() to create the URLs needed for each function.

An example may contain:

 <script> $.ajax{ url : "<?=site_url("controller/function")?>", data : {a:1,b:2}, } </script> 

This will give you codes created using CodeIgniter for your JavaScript. You can even pass variables to the view for more control over js.

0
source

Usually I create a little javascript in my header, in which I create the base_url and site_url variables (usually these are properties of an object that I call CI, but this is a personal guess). I fill in these values, repeating the values ​​using PHP. If you make the first script loaded, you will always have site_url available in JS.

Since I am on a mobile device, I cannot publish the source code now.

0
source

Source: https://habr.com/ru/post/1347462/


All Articles