This might be a simple question to many of you but any help would be actually appreciated
<li>rpsgame</li>
I am trying to link a tab to a cool simple game I made on Javascript, but it is opening in code instead of the actual program
My program name is rpsgame.js
Why is this happening ? what wrong did I do ?
Thank you so much
P.S: I'm new here!
What you need to do is link the js file using the script tag.
Here's how to do it:
<script src="rpsgame.js" type="text/javascript"></script>
After you do that, when the user clicks on the tab, load using ajax the view you created above and thats it!
Javascript files are actually plain text, so you're only linking to a page of text. A few solutions follow:
Put the contents in a function in that file, add that file in a <script tag in the header, and call the function onclick
Or call in the file with AJAX and eval it, or maybe JSON.parse it, or whatever
make a function that adds a <script> tag to the header with that file as a src
Related
I'm building a site with Pjax, so I have to reload some scripts every time open a new page. These page may contain/need different JavaScript, I hope to write the script this page needed in somewhere like <script id="balabala">alert("hello");</script>, and when pjax reload, it get the script text and run as JavaScript. Is this possible and how to make it work?
Answer myself:
Using eval() Function function, see: https://www.w3schools.com/jsref/jsref_eval.asp
****THIS IS AN UPDATE!!! ORIGINAL POST IS DOWN BELOW.****
From the answers provided I've now changed the code a little. Now I have this....
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script>
<script>
var coinToss = Math.random();
function runScript()
{
if (coinToss >= 0.5) {
$.get( "http://splittestpro.com/splittestonepage.php?test=1&member=4&result=1" );
}
else
{
$.get( "http://splittestpro.com/splittestonepage.php?test=1&member=4&result=2" );
}
}
</script>
And this is my onclick command in my link.
click here
This code follows the link but it does not run the code. However, if I change the href to href="#" it does run the code, but not follow the link. So the same as before!!!
The suggestion given in one of the answers is to have the redirect inside the function. But this is code that is going into other peoples websites. So the onclick to activate the function could be on a form submit button, or a link, or an image or on whatever they want to track and I don't know the URL they are linking to with the click (They might not want to link to a URL at all!)
Is there any way I can tweak this code so that it forces the $.get command to run the PHP script before it triggers the link? I thought that this happened automatically using an onclick inside a link.
I've also tried $.post in place of $.get but that's not working either.
Thanks for your help
****ORIGINAL POST BELOW HERE******
The script I need to run is a PHP script on another server. I do not need any information back from the script at all, I just need it to run when a person clicks on a link, then to follow the link.
This code is not for my own site, I am providing it to members, so the page must be basic HTML code, I know I can do this from a PHP page but I need it to work from HTML and Javascript.
What I'm doing now...
At the moment I'm using innerHTML to change a DIV tag inside a javascript function like this...
function runScript()
{
document.getElementById('thetrigger').innerHTML = "<img src='http://splittestpro.com/splittestonepage.php?test=1&member=4&result=2' style='height: 1px; width: 1px; visibility: hidden;' />";
}
With this DIV tag on the page....
<div id="thetrigger"></div>
I am using an onclick command to trigger the function like this...
click here to order
What I've tried...
If I run the script without the link the PHP executes fine, so I know the PHP is all OK
If I add 'return false' into the link the PHP works as I would expect it to
I have tried various combinations of return false and return true, as well as using onclick="return runScript();" then having return true inside the function.
I've tried lots of ways to do this but everything I try either will not run the PHP code but will follow the link, OR it does run the code but it doesn't follow the link
PLEASE NOTE....
My main problem is that I am in a basic HTML page using Javascript and I want to run a PHP script that's on another server. None of that can change, so please don't offer solutions that involve changing the page to a PHP page. The page is not mine, I'm giving this code to members of my business, and their pages are basic HTML pages.
Also... Please note that I don't need any data back from the PHP script. It only needs to make the script run then follow the link.
A POSSIBLE SOLUTION....
At the moment I'm triggering the PHP script by having it hidden in an IMG tag that is inserted into a DIV on the page.
I have searched for alternative ways to run a remote PHP script from javascript and can't find any solutions that work.
I imagine my solution should be something like this....
<script>
function runScript()
{
**RUN PHP SCRIPT**
}
</script>
click here to order
BUT.... what do I put in the RUN PHP SCRIPT section?
It seems that using AJAX or cURL might be a possible way to do this. I have no idea about that though, so would need it explaining. Also, if I use AJAX will it work fine inside a basic HTML page.
I want to give my members the code without them having to change or add anything on their server etc. They should be able to just copy and paste the code snippet into their basic HTML page.
Thank you for your help :)
Use AJAX. That way your PHP script will be run "in the background" and you'll be able to redirect your user to a new page on success. Below is a simple jQuery example.
<script>
function runScript() {
$.get( "file.php", function() {
window.location = "http://www.pagetoredirectto.com/"
});
}
</script>
I would suggest learning AJAX. This will allow you to send a request when the button is clicked, then when the request completes you can relocate the browser to wherever you want.
Your problem is likely that both the PHP script and the relocate are trying to happen at the same time, so only one of them is succeeding.
AJAX is pretty easy to learn, just Google it or check out W3Schools tutorial on it.
I was wondering if there is a way to execute script within a ajax dynamically loaded content.
I've searched the web and this forum also an find a lot of answers, like
[Running scripts in an ajax-loaded page fragment
[1]: Running scripts in an ajax-loaded page fragment [1]
But none of this seems to work fine for me.
I'm not experienced as the author of the quoted post, so maybe we can find a solution more simple and quite for everyone.
For now i've implemented a tricky turnaround that smell to much of an hard-coded solution that is:
//EXECUTE AJAX REQUEST LET'S SAY SUCCESSFULLY,
$ajax([..]) //THEN
.ajaxSuccess(function(){
// LOCATE ANY OBJECT PRE-MARKED WITH A SPECIFIC CLASS
$(".script_target").each(function()
{
//DO SOMETHING BASED ON A PRESET ATTRIBUTE OF THIS SPECIFIC ELEMENT
//EXAMPLE: <div class=".script_target" transition="drop_down">...</div>
//WILL FIRE A SCRIPT RELATED TO drop_down CASE.
});
});
I know this is an ugly solution but i didn't came up with nothing better than this.
Can you help to improve this method?
Maybe there's a way to let the browser fire script within the loaded page automatically?
PS. I'm not going to use the eval() method if it's not the last solution, cause both security leak and global slowdown, AND be aware that the script launched need to modify objects loaded in the same fragment of the script.
Thanks in advance.
If I understand you correctly :
you use "load" to retrieve html content from the server, and you add it to the page.
later, you do an ajax call, and on the return of the ajax call, you want to act on the markup you added earlier
but, depending on the markup retrieved, you want to do something different in the ajax callback
So another question : before you load the markup, do you know what logic will be behind it, or do you actually need to "read" the returned HTML to understand what it will be used for ?
Otherwise maybe something like this would work :
In the callback of the "$.load" function, use $.data() to attach more information to created dom object
In the ajax callback, you should be able to access the "added" markup (with a class like you did, or with an id if possible), and read to "data" to known which behavior you should have ?
Hopefully I got your problem right, it could help if you were able to create a jsfiddle or something, just to make sure we understand it.
Hoping this helps.
EDIT : After your comment, it might be related to the selector you use when calling $.load().
There is a "Script Execution" section in the $.load documentation : http://api.jquery.com/load/ , that explains that the scripts are not executed if you add a selector in the url, like this :
$('#b').load('article.html #target');
Could this be your issue ?
Also, if possible, you could try and change your site so that instead of having the js code of each "page" of the gallery inside the page, you put it inside a separate javascript file, that you load at runtime (for example with require js).
This way, "loading" a page would be something along the lines of :
$.load("url_of_a_page_markup.html", function () {
require(["url_of_the_javascript_module.js"], function (TheJsModuleForThePage) {
TheJsModuleForThePage.doSomething();
});
});
If you structure your JS modules in a consistent way, and you define a convention for the name of markup and js files, you can generalize things so that a "gallery" manager deals with all this code loading, and you'll end up with well isolated js modules for each page.
Hoping this helps.
If you want to run a script in a ajax loaded page fragment you can use try to use jQuery.load function.
Have you considered a module loader like require.js or Lab.js?
There are many other people asking similar questions:
does anyone knows good ajax script loader
Where are scripts loaded after an ajax call?
getting jQuery scripts and content through ajax dynamically
dynamic script loader in JS
Edit: I think I misread your question. Will try and come up with a better answer. Sorry!
Best of luck to you!
I came across this same issue when I dynamically loaded some HTML to use inside a JQuery UI dialog (a help function for my application).
$('#helpMessage')
.load('./help/' + helpFile, function () {...do stuff after loading});
To make things simple I wanted to combine the unique script related to the help page within the HTML fragment that I load. Using the examples on the JQuery UI page I created a dialog with a Jquery UI button element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Icons</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
(function() {
$('#myButton') // My button element
.button() // Initialize it as a JQuery UI button object
.click(function (){ // Hook up the button click event
$('#correct')[0].play(); // to play a sound in an <audio> tag
});
});
</script>
</head>
<body>
This is my help file, this is my code. This is for reading, this is for fun.
<button id="myButton">Button Text</button>
</body>
</html>
The dialog would load and the HTML displayed, but the embedded script did not execute.
I realized that one simple change would fix it. The script is embedded in an anonymous function (a best practice and part of the JQuery UI demo code). By immediately invoking the anonymous function the script executed when I loaded the HTML fragment into my main page.
This:
<script>
(function() {
...
});
</script>
Became:
<script>
(function() {
...
})(); // Immediately invoke
</script>
Niceness.
i have a vb.net GUIform that will display an AxWebBrowser to show a html table which have some interactive controls that required javascript to work.
I already prepared the javascript with the valid functions.
Example:
Inside AxWebBrowser have a button, when i pressed the button, it will display the current time inside the AxWebBrowswer.
Is that possible to do this? and how? Just place the .js file in the same place and set the src equals to the .js file path? but it seems not work.
And after several tried, i found maybe JScriptCodeProvider can do this. but i no idea how to point the src to the jscript running in memory.
Please help
The easiest way to do this is to include the javascript with the html via a <script> tag, paste the entire script inline rather than using src="..." if you need to.
I have searched this web looking for an answer, but it seems that this time I'm not so lucky, so I am forced to ask. I apologize if it's already answered (could not find it). And yes, English is not my first language, so I also apologize for my spelling mistakes, I try my best.
This is my problem, using Tomcat 5.5, Struts 1.3, JRE 1.5 and I'm using firefox 3.5.6.
In my jsp page I cannot seem to put any src="path/path" in my <script> I have tried deleting the src and all works well, but my project is going to need a lot of use from jquery and I do not want to copy/paste all the js file in every jsp.
This is my code:
<script type="text/javascript" src="js/jquery-1.3.2.js">
function showMySelf(){
alert("Hello World!");
}
(... plus other stuff code that actually uses jquery functions)
</script>
and the submit button:
<input type="submit" onclick="showMySelf()">
When I click the button, nothing happens (well it actually repaints the page) and when I delete the "src" tag from the script and add all the jquery code to the page it all works well.
I have tried putting another slash in the path as "/js/jquery-1.3.2.js" and returns an error.
I have tried using ResolveURL and it doesn't seem to give me better results.
I have also tried changing the js file to another file ("generics.js" and "js.js"), I also tried with "js/*.js".
Any of theese solutions have archived anything.
I have also tried using the struts tags (like html:submit) but it also did not work.
The path is actually right, since looking the code in my web browser gives me a link to the js file. So I suposse the browser knows were to look for my js file, it does not give me an error or a broken link to the file.
Any ideas of why this is happening?
Thank you all.
Random.
You can not use a script element to load an external file and put code in it at the same time. You need to use two script elements:
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
function showMySelf(){
alert("Hello World!");
}
(... plus other stuff code that actually uses jquery functions)
</script>
I think Gumbo solved it.
As a sidenote, a very good way to find out whether a browser can load a JS file is the "Net tab" in Firebug in Firefox. It shows all loaded (and failed) requests of the current page.
The two most likely options are:
a) You are including HTML in your JS file (i.e. <script> tags)
Take it out.
b) You have the wrong URI and when you attempt to resolve your relative URI manually you do so incorrectly
Look at your server access logs to see what is actually being requested (or use a tool such as Firebug)
The first thing to do in such case. Install Firebug and look at the "Console" panel (for possible syntax errors) and the "Net" panel to see whether your jQuery sources are being fetched correctly. The 2nd column there shows the request status code.
alt text http://img46.imageshack.us/img46/6224/jqueryfirebugtmp.jpg
(full size image)