Welcome Guest, Not a member yet? Register   Sign In
base_url() and jQuery problem
#1

[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
#2

[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.
#3

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

Julio
#4

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




Theme © iAndrew 2016 - Forum software by © MyBB