简体   繁体   中英

url in jquery ajax post in codeigniter

I am trying to set jQuery Ajax post URL.But it is not working as I want. I searched a lot and I got many solution.But none of them indicate my problem. I set the base URL in var baseurl = "<?php print base_url(); ?>"; in js file and use it in $.ajax url concatenating it.It gives me

Disallowed Key Characters.php_print_base_url();_?>welcome/add_tag

I think the var baseurl is not working.

html

<script src="<?php echo base_url();?>js/my_js.js"></script>
<input type="text" id="add_tag" placeholder="add more tags"/>

js

var baseurl = "<?php print base_url(); ?>";
$('#add_tag').on('keyup paste', function () {
            tag_text=$(this).val();
            if(tag_text==='')
              return;
            $.ajax(
            {
             type: "POST",
             url: baseurl+"welcome/add_tag",
             data: {tag_textTo:tag_text},
             success: function(data){
             $('.tags_found').html(data);
            }
        });
        });

CI_Controller

class Welcome extends CI_Controller {
        public function add_tag() 
        {
            $tag_text=$this->input->post('tag_textTo');
            echo $tag_text;
        }
}

How to make it work?thanks in advance.

You should declare the baseurl like this

var baseurl = '<?=base_url()?>';

or

var baseurl = "<?php echo base_url(); ?>";

And inside the jquery ajax call

  url: baseurl+"welcome/add_tag",

Else totally

url: <?php echo base_url();?>"welcome/add_tag",

Note :

Don't forget to load the url helper

尝试使用site_url

url: "<?php echo site_url('welcome/add_tag');?>"

problem found

I am using an external js file for ajax call. Now I know codeIgniter url helper does not recognize my baseurl variable in external js file. That is line var baseurl = "<?php print base_url(); ?>"; in external file.

The answer given by @Sulthan Allaudeen and @saravanan n (thanks to them)all are working when I declare the baseurl var

in my php view file internally.

view file

<script type="text/javascript">var baseurl = "<?php print base_url(); ?>";</script>

The remaining js code can be stay on external file.

$('#add_tag').on('keyup paste', function () {
            tag_text=$(this).val();
            if(tag_text==='')
              return;
            $.ajax(
            {
             type: "POST",
             url: baseurl+"welcome/add_tag",
             data: {tag_textTo:tag_text},
             success: function(data){
             $('.tags_found').html(data);
            }
        });
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM