This is quite a complicated one but I'll try and explain it as best as I can.
I am developing a wordpress site that utilises quite a few jQuery plugins (plupload, jCrop etc).
On some pages there are multiple instances of plupload and some of these instances require the user to be able to crop an image.
To save me writing the same code out multiple times I just use the same jQuery but with variables appended by a php variable.
I created a class that 'writes' the required jQuery into the dom and then it can pass in a variable to be used to append the jQuery variables to make them unique.
I then just instantiate multiple objects of that class at different parts on the web page as and when I need that functionality.
For instance (example simplified for clarity)...
On a web page..
<div>
<?php
$thisUploader = new reqJqueryClass("firstUploader");
$thisUploader->implementMainUploadPicture;
?>
</div>
<div>
<?php
$anotherUploader = new reqJqueryClass("secondUploader");
$anotherUploader->implementSecondaryUploadPicture; // This also has crop functionality
?>
</div>
And then the Class takes the parameter passed to it (firstUploader / secondUploader in this case) and writes it to $this->dynamicPartOfVar.
Inside the class I have...
public function implementMainUploadPicture() {
$this->start_Javascript();
$this->set_Up_Object_Specfic_Vars();
$this->run_Plupload_jQuery();
$this->end_Javascript();
}
public function implementSecondaryUploadPicture() {
$this->start_Javascript();
$this->set_Up_Object_Specfic_Vars();
$this->run_Jcrop_jQuery();
$this->run_Plupload_jQuery();
$this->end_Javascript();
}
etc .. etc.. (this is actually more functionality included other than just an upload and crop library)
Then I have methods that simply look like this...
protected function start_Javascript() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
<?php
}
protected function end_Javascript() {
?>
});
</script>
<?php
}
protected function set_Up_Object_Specfic_Vars() {
?>
var dynamicPartOfVar = "<?php echo $this->dynamicPartOfVar; ?>";
// $this->dynamicPartOfVar is firstUploader or secondUploader (or whatever was passed in)
var imageManipulationObject = ();
<?php
}
public function run_Jcrop_jQuery() {
?>
imageManipulationObject["myVariable"+dynamicPartOfVar];
// rest of vars set up the same way
// so that I can have multiple instances of this jquery
// on the same page without conflict ....
<?
}
public function run_Plupload_jQuery() {
?>
imageManipulationObject["anotherVar"+dynamicPartOfVar];
// rest of vars set up the same way
// so that I can have multiple instances of this jquery
// on the same page without conflict ....
<?
}
Even though this is a bit of a code smell it seems to work a treat. My only concern is whether this system will be scalable (I need quite a few upload/jcrop etc objects on one page) or whether it will bog the browser down doing it this way?
I thought that once the site is tested and working then I would copy all the jQuery from the browser, paste it into it's own file, minify it and then just call it via the header (or footer) as normal?
However, I wondered if there was a "correct" way of achieving the same thing that I'm trying to do here?
I'm self-taught in everything that I'm doing so rarely implement the 'best practice' and I don't know of any other way to achieve what I'm trying to do here?
Thanks for any help you can give me. :-)
The code is really hard to maintain.
First of all, if you're using multiple jQuery versions, then you should use jQuery.noConflict():
http://api.jquery.com/jquery.noconflict/
Second of all, I didn't understand the following code:
protected function start_Javascript() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
<?php
}
Why not load the code in "header.php" or "index.php" or any other view file ?!
This function doesn't work, because it doesn't return anything or echo anything.
Third of all, if you really want to mix Javascript and PHP together, then you should do the following:
<script type="text/javascript">
var js_arr = new Array();
jQuery(document).ready(function(){
<?php
$arr = array('test1', 'test2');
for($i=0; $i<sizeof($arr); $i++){
?>
js_arr.push('<?php echo $arr[$i]; ?>');
<?php } ?>
});
</script>
It will fill the PHP array in the JS array.
Related
I have been looking at answers to this across the web for about an hour now, and trying things based on those answers (I know this kind of issue comes up often). However, nothing I am trying is working. So an explanation first:
I am looping through a table in PHP (in a while loop), and need to call a JavaScript function for each record in the row set returned for my table. To try to get started, I have a super basic function that just lets me know I called it ... it's not working. Here's the PHP code (the reason for the DIV tag is that I eventually want to replace the innerHTML of the DIV from the JS code I know how to do that and have done so elsewhere ...):
// the loop:
while( $row = mysqli_fetch_array( $heralds_result ) )
{
$herald_id = $row["roster_id"];
$sca_name = $row["sca_name"];
// create a div for each herald as we go with its' own name (using id ...)
echo " <div id='" . $herald_id . "'>\n";
echo " " . $sca_name . "\n";
echo " <script type='text/javascript'>test();</script>\n";
echo " </div>\n";
}
This is the JavaScript code (at the bottom of the file):
<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>
However, I get no "alert" dialog, just the text streamed out. So for the first row I get:
<div id='1'>
Aasa Thorvaldsdoittr
<script type='text/javascript'>test();</script>
</div>
As the alert dialog is not displayed, it tells me the Javascript function is not being called, or there is some error that is truly not obvious to me after staring at it for a long time. This is something that shouldn't be this difficult, I am sure I have some really obvious error that someone will see as soon as they look at the code, but it's evading me completely.
"JavaScript code at the bottom of the file"
is the problem. Scripts are run as soon as they are added to the DOM. Things are added to the DOM in the order they are given in the HTML.
Therefore the script tags which try to call your function are added - and executed - before the script tag which actually contains the function gets added. So they try to execute a function which doesn't yet exist. If you look in your browser's Console (in the Developer Tools) you probably have some errors complaining about this.
The simple solution is to declare the script tag containing the function somewhere in your HTML before the code which tries to use it.
As an aside, it would be interesting to know what you plan to do with this function in reality - consider whether you could achieve the same effect directly by creating some markup using PHP, rather than firing off lots of JS while the page is loading.
You should move the function declaration upper than it used. For example:
<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>
..
<?php
..
// your loop
..
?>
or
<?php
..
echo '<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>';
..
// your loop
..
?>
I have checked several other threads on here related to masked input plugins not working and was unable to find any answers:
Masked Input Plugin not working
jQuery Masked Input plugin not working on form input?
JQuery Masked Input plugin doesn't work
I should preface this by saying that my programming knowledge is rather limited. I have help, but that help isn't always available.
I am attempting to use this plugin
My Version #: SuiteCRM Version 7.2.1, Sugar Version 6.5.20 (Build 1001)
So I added the jQuery javascript library file and the jQuery plugin from digitalbrushes website and put them both in /admin/custom/include/javascript/
Then under the module I am currently working on which in this case is the Contracts module, the file I am working on is here:
/admin/custom/modules/AOS_Contracts/views/view.edit.php
Below is the file:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/MVC/View/views/view.edit.php');
class AOS_ContractsViewEdit extends ViewEdit {
// function displaySubPanels() {
// return '';
// }
function display(){
$js = <<<JS
<script src="/admin/custom/include/javascript/jquery.min.js" type="text/javascript">
<script src="/admin/custom/include/javascript/jquery.maskedinput.min.js" type="text/javascript">
var \$j = jQuery.noConflict();
\$j("#home_phone_c").mask("(999) 999-9999");
\$j("#work_phone_c").mask("(999) 999-9999");
\$j("#mobile_phone_c").mask("(999) 999-9999");
\$j("#inital_deposit_amount_c").mask("999,999,999,999,999.99");
});
</script>
JS;
parent::display();
echo $js;
}
}
When I load the page and click in the fields, there is no masks present, in my chrome console I am only getting an unrelated error in my style.js file that says:
"Uncaught TypeError: $.cookie is not a function"
I have already tried wrapping this in {literal} tags as suggested by this answer: Adding custom jQuery validation in SugarCRM editview, nothing changed. I'm not really certain how or if the .ready(function() is applied to this if it is necessary. I didn't think it was because of parent::display();.
I have tried this same page in Chrome, Firefox, Safari, and IE.... nothing. I also cleared my cache and cookies after I made the changes to ensure I was getting fresh results. I have also done a quick repair and rebuild on SuiteCRM everytime (although that should be completely unnecessary) just to cover my bases.
I was able to get help on SuiteCRM's forum.
-I needed this cookie plugin
-In my syntax above src="jquery.maskedinput.min.js" needed to be omitted.
-In my syntax above, \$j was creating an infinite error in the chrome console that only appeared once the above syntax was removed, I omitted the j and then that cleared it up!
The corrected code looks like this:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/MVC/View/views/view.edit.php');
class AOS_ContractsViewEdit extends ViewEdit {
// function displaySubPanels() {
// return '';
// }
function display(){
$js = <<<JS
<script src="custom/include/javascript/js.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
var \$ = jQuery.noConflict();
\$("#home_phone_c").mask("(999) 999-9999");
\$("#work_number_c").mask("(999) 999-9999");
\$("#mobile_number_c").mask("(999) 999-9999");
\$("#inital_deposit_amount_c").mask("");
</script>
JS;
parent::display();
echo $js;
}
}
?>
You need to add JS file in metadata using "include". Then write your code in that file. Writing java-script code inside PHP view is not suggested by Sugar.
If you only need view.edit for this purpose then at the end this file will not be needed and hence get deleted. Let me know if you need further details.
I have a webpage that uses PHP that must be output before any code is called. In another part of my PHP I need to call a JavaScript function for displaying a message on certain user actions. Is there a way I can call my JavaScript function at the top of my page? I'd rather keep all the PHP together as currently it looks like this;
<?php
...Code that must be called first...
?>
...<head></head>....
<?php
if (PHPFunction()){
echo "<script>MyJSFunction();</script>";
}
?>
To me it looks messy having it this way. How can I avoid this?
EDIT:
To make my intentions more clear. The JavaScript function I'm using will display a pop up message, giving the user feedback on actions they are performing. For example, if they upload a file, if move_uploaded_file() is successful, this message gets called. The browser complained when I had my bottom code in the top part saying that my JavaScript function was not defined. When I moved it under it was all good, apart from now looking messy.
Are you using jQuery ?
if you are, have you try this code:
<?
move_uploaded_file(source, destination);
echo "<script>
$(document).ready(function () {
alert ('file successfullu uploaded');
});
</script>";
?>
I've checked out all the related questions I could find and still cannot get this to work so am reaching out to you lovely folk!
I wish my site to have a random color background (one of multiple pre-selected colors) each time someone visits.
There are various times people have asked for it to call up a random image but I just wish to have a block color, assuming using bold background.
The two options I have seen used in similar ways, but to no avail, are:
jQuery (link: taken from a Tumblr query):
1) Creating a new 'background.js' file in /js/ with the code:
<script>
var bgcolorlist=new Array("background: #ff871b", "background: #15efa1", "background: #51ddff", "background: #ff1b6c", "background: #000000");
var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
$('body').css('backgroundColor', color);
</script>
2) Adding to function.php:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'your-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
& PHP and CSS (link):
I put this whole string in the style.css file:
<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
body {
background: <?php echo $color; ?>;
}
Unfortunately neither of these solutions seem to work for me and both threads are outdated so cannot get further answers hence starting a new thread.
Any ideas for where I might be going wrong for either?
Any other ways around this you think would be a better way to solve the problem?
Further info: I'm using the super simple Less theme, which only comes with 3 files: functions.php, index.php and style.css - which I'm using as a bare bones theme to completely customise my own theme.
Many thanks in advance!
The issue with your JavaScript implementation is that you have the whole CSS declaration in your array indexes. Also, since you are including the script in the head, you need to wrap the code in a document.ready handler, and take care of the noConflict mode WordPress puts jQuery in.
Try something like this:
jQuery(function($) {
var bgcolorlist=["#ff871b", "#15efa1", "#51ddff", "#ff1b6c", "#000000"];
var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
$('body').css('backgroundColor', color);
});
The reason your PHP did not work in the CSS file is because .css files do not normally run PHP code. You would need to put it in a separate .php file and enqueue it, or put the code in the head with header.php or an action.
<style>
<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_key = array_rand($input);
$color = $input[$rand_key];
?>
body {
background: <?php echo $color; ?>;
}
?>
</style>
You cannot put PHP in the CSS file, so if you want to use a PHP approach, you would want to echo a local CSS block in the header.
For example, in your functions.php file:
function getBgColor() {
$input = array("#000080", "#00CED1", "#191970");
return $input[rand(0, count($input) - 1)];
}
Then in your header.php:
<style>
body {
background: <?php echo getBgColor(); ?>;
}
</style>
I'm trying to call my JS function which is in a file called Scripts.js. I have a php function, but I'm unsure as to whether I need to come out the php function or not as I can't get it to work either way and nothing I've googled is giving a definitive answer as to which it should be so any help would be appreciated!
<?php if(isset($_REQUEST['renameFile']))
{
//uses checkboxes from table
if(isset($_POST['checkbox']))
{
$checkedboxes = $_POST['checkbox'];
$count = count($checkedboxes);
//echo ("$count");
/*if($count == 0)
{
throw error that something needs to be selected. If implement checkbox hidden then no need to implement
}*/
if($count == 1)
{?>
<script type="text/javascript">
showUpload();
</script>
<?php
}
?>
So I'm calling the function showUpload() in my Scripts.js file which I have defined in my main screen using
<script src ="Scripts.js"> </script>
Which I know works as I've used it elsewhere.
function showUpload()
{
document.getElementById('fileUpload').style.display = "block";
}
And then this goes on to call a pop up form which I can get to work on a button click so it's just calling it without a button which seems to be an issue. Thanks!
check following things.
include your js file at the top of the file
write the script tag out side the php mode.
make sure the if conditions are true/false as you expect
then the code should work fine