简体   繁体   中英

How to use jquery noconflict in Joomla

I am using a PHP, javascript Json to populate fields in a form. Everything was working fine until I upgraded my joomla from 3.1.5 to 3.2.2. I believe it is conflicting with jquery.

So here the code I am using. If I use this standalone it works absolutely fine, but does not work in Joomla.

Please help me resolve this jquery conflict.

<?php

try {

    $objDb = new PDO('mysql:host=localhost;dbname=prod', 'xxx', 'xxxx');
    $objDb->exec('SET CHARACTER SET utf8');

    $sql = "SELECT id, Master, Area, Rate1
            FROM `products`
            WHERE `Master` = 0";
    $statement = $objDb->query($sql);
    $list = $statement->fetchAll(PDO::FETCH_ASSOC);

} catch(PDOException $e) {
    echo 'There was a problem';
}

?>
<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <link href="/1/finished/css/core.css" rel="stylesheet" type="text/css" />
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>
<script>
function sendForm() {
    document.myform.submit()
}
</script>

<div id="wrapper">

    <form id="myform" action="/index.php/it-hardware-disposal-cost-upto-25-items" method="post">

        <select name="Area" id="Area" class="update">
            <option value="">Select Your Location</option>
            <?php if (!empty($list)) { ?>
                <?php foreach($list as $row) { ?>
                    <option value="<?php echo $row['id']; ?>">
                        <?php echo $row['Area']; ?>
                    </option>
                <?php } ?>
            <?php } ?>
        </select>

        <select name="County" id="County" class="update"
            disabled="disabled">
            <option value="">----</option>
        </select>

        <select name="City" id="City" class="update"
            disabled="disabled" onchange="this.form.submit()">
            <option value="">----</option>
        </select>


    </form>

</div>


<script src="/1/finished/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="/1/finished/js/core.js" type="text/javascript"></script>
</body>
</html>

See below is the core.js I strongly believe the problem is here, probably because some other code in joomla is conflicting.

var formObject = {
        run : function(obj) {
                if (obj.val() === '') {
                        obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
                } else {
                        var id = obj.attr('id');
                        var v = obj.val();
                        jQuery.getJSON('/1/finished/mod/update.php', { id : id, value : v }, function(data) {
                                if (!data.error) {
                                        obj.next('.update').html(data.list).removeAttr('disabled');
                                } else {
                                        obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
                                }
                        });
                }
        }
};
$(function() {

        $('.update').live('change', function() {
                formObject.run($(this));
        });

});

So Core.js uses Jquery.json to populate the data using update.php which has following code.

<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {

        $id = $_GET['id'];
        $value = $_GET['value'];

        try {

                $objDb = new PDO('mysql:host=localhost;dbname=xxxx', 'xxx', 'xxx');
                $objDb->exec('SET CHARACTER SET utf8');

                $sql = "SELECT id, Master, Area
                                FROM `products`
                                WHERE `master` = ?";
                $statement = $objDb->prepare($sql);
                $statement->execute(array($value));
                $list = $statement->fetchAll(PDO::FETCH_ASSOC);

                if (!empty($list)) {

                        $out = array('<option value="">Select Your Area, City</option>');

                        foreach($list as $row) {
                                $out[] = '<option value="'.$row['id'].'">'.$row['Area'].'</option>';
                        }

                        echo json_encode(array('error' => false, 'list' => implode('', $out)));

                } else {
                        echo json_encode(array('error' => true));
                }

        } catch(PDOException $e) {
                echo json_encode(array('error' => true));
        }

} else {
        echo json_encode(array('error' => true));
}
?>

When using jQuery in Joomla, its best to use jQuery() instead of the factory symbol $() . So you don't have a conflict. Joomla uses MooTools by default so MooTools takes ownership of the factory symbol.

Otherwise you need to use jQuery.noConflict()

For example.. So this:

$(function() {

    $('.update').live('change', function() {
            formObject.run($(this));
    });

});

Would become this:

jQuery(function() {

    jQuery('.update').live('change', function() {
            formObject.run(jQuery(this));
    });

});

An example of how to use jQuery.noConflict() , so you can use the $() factory symbol:

<!-- Another way to put jQuery into no-conflict mode. -->
<script src="mootools-core.js"></script>
<script src="jquery-min.js"></script>
<script>
jQuery.noConflict();
jQuery( document ).ready(function( $ ) {
       // You can use the locally-scoped $ in here as an alias to jQuery.
       $( "div" ).hide();
});

// The $ variable in the global scope has the mootools-core.js meaning.
window.onload = function(){
   var mainDiv = $( "main" );
}
</script>

Joomla also has plugins for jQuery noConflict so also using one of those plugins could help if you don't want to add it yourself.

Joomla Plugins to look at:

jQuery Easy

jQuery Scripts Joomla Plugins

Either you have to use jQuery.noConflict() before your custom jQuery code, or you always have to use jQuery() , instead of $() .

See if that helps!

UPDATE

If you open up your browser console you will see that you have like 5 JavaScript errors.. like jQuery not being defined, and other errors depending on jQuery. Also if you look at the order your scripts are being loaded, you will see that jQuery is loaded after other scripts that are dependent on jQuery. You will have to make sure jQuery is being loaded correctly in Joomla, and all errors are fixed to get your code to work.

I believe the jQuery live method is deprecated in the version of jQuery included in Joomla. It works in the sample code because you're loading jQuery 1.6.4. In the Joomla code try chainging this:

$(function() {

        $('.update').live('change', function() {
                formObject.run($(this));
        });

});

To this:

jQuery(function() {

        jQuery('.update').on('change', function() {
                formObject.run(jQuery(this));
        });

});

and see if it works.

EDIT

I attached a screen capture from the link, which has two errors we should address first.

在此处输入图片说明

  1. The script tabs-state.js throws the error jQuery not defined. This most likely means you haven't loaded the jQuery library yet, resulting in the error.
  2. bootsrap.min.js is throwing an error stating there is no method 'on' indicating jQuery has been loaded but an older version. Joomla 3.x comes with 1.8.23, but a review of the DOM on your webpage shows version 1.6 is being loaded.

The proper way to load jQuery and Bootstrap using the Joomla core is as follows:

JHtml::_('jquery.framework');
JHtml::_('bootstrap.framework');

You should remove any lines manually loading either of those frameworks and if possible, place these methods at the top of your template's index.php to ensure they are loaded before any other embedded scripts run.

Try addressing those items and lets see if those errors are removed from the console and if your code executes as expected once they are loaded properly.

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