CodeIgniter Forums
base_url() and jQuery problem - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: base_url() and jQuery problem (/showthread.php?tid=13284)



base_url() and jQuery problem - El Forum - 11-17-2008

[eluser]kidego32[/eluser]
Hi everyone,

I'm trying to use the base_url() function inside a jQuery script, but it appears that the function is not being evaluated.

My code is as follows:
Code:
$.ajax({
            type: "POST",
            url: "<?=base_url()?>quotes/glass",
            data: dataString,
            dataType: 'text',
            success: function(text) { $('#quote-result').html(text); }
                
        }); // close of .ajax section

When I hardcode the url ("http:localhost/quotes/glass"), everything works. Can anyone guide me in the right direction?

Thanks,

Julio


base_url() and jQuery problem - El Forum - 11-17-2008

[eluser]Nick Husher[/eluser]
That would indicate that your jQuery script is not being parsed by the PHP hypertext processor. You can either move your ajax script into a view and call it via a controller, or you can add a way for your script to know what the root url is for your site. To accomplish the second, you can do this:

Code:
// .../system/application/views/main_template.php
<head>
    // Set up a root directory global variable that all scripts will have access to
    <JAVASCRIPT type="text/javascript">
        CI_ROOT = "&lt;?=base_url() ?&gt;";
    </JAVASCRIPT>
    // Include jquery script files
    <JAVASCRIPT src="&lt;?=base_url() ?&gt;assets/jquery/jquery.js" type="text/javascript"></JAVASCRIPT>
    <JAVASCRIPT src="&lt;?=base_url() ?&gt;assets/jquery/script.js" type="text/javascript"></JAVASCRIPT>

    // ... Other header stuff ...
&lt;/head&gt;

Code:
// .../assets/jquery/script.js
$.ajax({
    type: "POST",
    url: CI_ROOT+"quotes/glass",
    data: dataString,
    dataType: 'text',
    success: function(text) { $('#quote-result').html(text); }
}); // close of .ajax section

The forum XSS filter removes script tags, so I used a fictional "javascript" tag instead.


base_url() and jQuery problem - El Forum - 11-17-2008

[eluser]kidego32[/eluser]
Thanks so much for your reply Nick. That did the trick!

Julio


base_url() and jQuery problem - El Forum - 01-25-2014

[eluser]Unknown[/eluser]
Thanks so much, Nick!