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
Related
I am stuck with this issue. I have a js function into a scripts.js file:
var userLoggedIn;
function openPage(url) {
if(url.indexOf("?") == -1) {
url = url + "?";
}
var encodedUrl = encodeURI(url + "&userLoggedIn=" + userLoggedIn);
$('#mainContent').load(encodedUrl);
}
I call the javascript function from a php file like this:
<?php
//This file should check if the requested url is sended by AJAX or it's manaually typed by the user into the browser
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
include 'includes/config.php';
include 'classes/Artist.php';
include 'classes/Album.php';
include 'classes/Song.php';
} else {
include 'includes/header.php';
include 'includes/footer.php';
$url = $_SERVER['REQUEST_URI'];
echo "<script>openPage('$url')</script>";
exit();
}
?>
It works fine when it's called from an onclick event into the HTML document, but it doesn't works when I enter manually the url. It prints a string into the screen. However this code is taken from some sample coding pages and it seems to work this way. What am I missing here?
Thanks in advance for the help and be patient... i'm a beginner on this!!
First of all you need to have the mentioned above js code loaded somewhere. Do you have it loaded in header or footer? (Directly or by loading your scripts.js?)
Be sure to have:
<script type="text/javascript" src="scripts.js">
Somewhere printed in your code. Do you have it in your footer or header?
Assuming that you have your js code in scripts.js now you can execute after page loads, but be sure print the <script> part WITHIN your <html>...</html>. So if you print out </html> in your footer.php then be sure to print:
echo "<script type="text/javascript">openPage('$url')</script>";
BEFORE loading of footer (but after loading of scripts.js);
While you learn a bit more you will get to know that actually it is a bad thing to execute code parts like that: you should separate your markup from code which executes things directly from it.
Modern frameworks will assist you with that, there is also defer attribute of the script element (https://www.w3schools.com/tags/att_script_defer.asp) which helps to execute the code after the page actually loads.
So, after reviewing all the code i found the problem. There was a missing ">" in the html closing tab. Now it works!! Thank you for your help!
I have a php file which is part of a basic Content Management System. Inside this file I have a table which contains a "Delete" link in every row.
What I am trying to do is create a choice popup in a javascript function of which I call when the link is clicked.
My function code (which appears in the head part of my php file) is below:
<script type="text/javascript">
function delete(skillID)
{
var answer = confirm("Are you sure you want to delete this record?");
if(answer == true)
{
window.location.href = "process/deleteRecord.php?skillID=" + skillID;
}
}
The code which calls this function is below:
echo "<td>Delete</td>";
The problem is that the box doesn't even popup, so the function isn't called properly.
Can anyone help?
If there are any other details you need to know please let me know.
You can try something else :
echo "<td>Delete</td>";
You need to use the "onClick" attribute, try that :
echo "<td>Delete</td>";
Hope it'll help!
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>";
?>
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.
The purpose of this code was to populate a div from a PHP file when a button is clicked.
Also to pre populate a div when page loads - I have completed this task.
Now I want to load a second div at the same time and I'm unsure how to go about this.
function loadpage(clicked_id) {
if (clicked_id != 0 || clicked_id != null || clicked_id !="") {
$("#Table").load("marshfight1.php?action=fight&id="+ clicked_id);
$("#mobs").load("marshtab.php");
}
}
$(document).ready(function() {
// initial
$('#mobs').load('marshtab.php');
});
Echo "<div id=Table></div>";
Echo "<div id=mobs></div>";
$selem = mysql_query("SELECT * FROM senemies WHERE userid='$playerinfo[id]' && arena='10'");
while($enem = mysql_fetch_array($selem)) {
Echo "<button><type=button id=\"$enem[id]\" onclick=\"loadpage(this.id)\" name=\"$enem[id]\">$enem[name]<br>Level: $enem[level]<br> HP: $enem[hp]</a></button>";
}
Everything works fine except for the second .load to update #mobs.
The problem appears to be the inclusion of PHP in your javascript. Remember that though PHP will throw a compile error, IE will do its best and FF will do its best up to the point of the error then very quietly quit. Thus it will appear to be working but actually half your code never gets executed. ctrl-shift-k in FF will give you a rundown of errors.
What you need is ajax. This is easy to implement in both jquery and 'straight' javascript.
Forgive me if you already know this, but others use this forum so a brief summary of the process would be:
Button is clicked triggering JS onclick function.
onclick function sends appropriate data (which button for instance and/or usernumber etc) to php file.
onclick function puts whatever the php returns in the div as desired.
You need to get your js and php organised and separated.
A good overview and basic tutorial can be found at http://www.w3schools.com/ajax/