Good day all, I've two pages of php file and an external javascript file. I want to pass a selected radio button's value to a jquery global variable so that I can view the div element which has the same id as selected radio button's value. Whenever I click PLAY! button I don't see my div element on the next page. Here are my codes:
player-choose.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js script:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
It's a very simple thing but I don't know why it's not working. Am I doing something wrong here? Please if anyone finds a solution enlighten me. Tnx!
If you're moving to a new page (window.location = ...), you'll need some slightly more complicated way of transferring information between those pages - for the most part, HTTP/HTML is "stateless", with the exception of technologies like cookies. JavaScript variables get wiped out entirely - it's actually re-parsing the entire JQuery library on each new page (not to say that's something to avoid)
For a video game, as long as player information doesn't include server components (I could be wrong) my recommendation would be saving player information in sessionStorage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
However, if this is a server-based game in which your choice of player matters beyond the local computer, you'd likely want to send the player ID to the server, either by structuring the page request differently:
window.location.href = 'index.php?playerId=' + playerId;
Or by POSTing the data as a form; most easily accomplished by structuring your submit button as an <input type="submit">, and wrapping all your <input> elements in a <form method="POST"> object.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
From there, your server software could write the second page's response out differently based on the given information - you can even customize what JavaScript is written inside of a <script> tag using PHP directives.
var playerId = "<?php print($_POST['playerId']); ?>";
Hopefully that helps get you started.
global variables are not persistent across pages. Once you load your index.php , it will have the new global scope(window variable).
I suggest passing a parameter.
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
afterward, inside your index.php script , read the parameter and assign accordingly.
Alternative solution is you could you use JavaScript or jQuery cookie or localstorage. You can get/set values across page loads/redirects but these are not passed to server.
jQuery Cookie
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
LocalStorage
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);
Related
I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!
Apologies in advance if this question has been asked earlier. I did find some similar questions on web but I couldn't figure out the answer still. You can say I have never dealt with anything beyond basic HTML. So any help would be appreciated.
I have a HTML file (Say text.html) only for personal use. In the file, there will be an input box for entering text and a submit button. I want that if I clicks on submit, it opens a particular hyperlink from an external webpage based on the input text. I guess it's like "I am feeling Lucky" of Google.
Example: If the user enters "Test" and clicks on Submit, it should open the second result from the page "https://www.google.com/search?q=test"
Here is my HTML:
<!DOCTYPE html>
<html>
<body style="background-color:beige">
<h1 style="text-align:center"><font size="14">Test</font></h1>
<style type="text/css">
</style>
<form id="form">
<div align="center" style="vertical-align:bottom">
<input type="text"
value="Test"
id="input"
style="height:50px;width:200px;font-size:14pt;">
</div>
</form>
<TABLE BORDER="0">
<TD><button class="button" id="button01">SUBMIT</button></TD>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
</script>
Also, here is the example of the div element from the page on which the hyperlink I want to open is on:
<div id="XYZ" class="contentEditValue" style="float:left;width:180px;">
2nd Result
</div>
I have read that it can be achieved with PHP or Jquery and all but they are not something I have ever worked on. Thank you very much in advance for any help!
Appreciate any other alternatives as well.
You shouldn't be able to do that because of security. If that (reading content from iframes, other browser windows...) would be possible, an attacker could add JS keylogger to your internet banking login or read your messages on Facebook. CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is used to block these requests and if the website doesn't say explicitly that you are allowed to do something with its content, most browsers won't allow you that.
You have are missing a }); to close the ready() function
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
});
</script>
Here's a basic example of how to do this in PHP.
Taking JavaScript/JQuery out of the picture, let's just say you have a basic form:
<form>
<input type="text" value="Test" name="input">
<input type="submit">
</form>
Without specifying action or method attributes on the <form> tag, the form will make an HTTP GET request to the URL of the page it is on, so for this example the PHP code will be on the same page as the form. Here's a more detailed description of sending form data if you're interested.
Now that you have a way to pass the input to the PHP script*, there are three basic parts to this problem.
Make a request to the page you want with a query string including your input
http_build_query is an easy way to construct a properly encoded query string to use with your request. For this example we'll use file_get_contents to make the request. There are other ways to do it, including cURL, but let's keep it simple.
$query = http_build_query(['q' => $_GET['input']]);
$page = file_get_contents('http://www.example.com/?' . $query);
I'm not using Google for this example because it's a bit more complicated to find the right links in the response and follow them. (Partially because they don't really want you to do it that way.)
Find the link you want in the response
Don't try to find the link in the response with regex. You'll have problems with it, come back to Stack Overflow to try to solve them, and people will tell you that you shouldn't be using regex, so just skip that part and use a DOM parser.
$doc = new DomDocument;
$doc->loadHTML($page);
$links = $doc->getElementsByTagName('a');
$url = $links[0]->getAttribute('href');
I used getElementsByTagName() to find links, but if the page is more complex an xpath query will work better. Also, I used the first link ($links[0]) because example.com only has one link. $links[1] would get you the second link if it existed.
Follow the link
header("Location: $url");
exit;
If everything goes well, you'll end up where you want to be. But there are a lot of things that can go wrong. If you're requesting a resource that you have no control over, it can change at any time without any advance warning to you, so your code that finds the link may stop working. You may get blocked from making requests. Scraping links from sites like this violates the terms of service on many sites, so check that out beforehand. You may find that the site offers a web API, which should be a much better way to access its content than this.
*You don't really need a form for this; you can just pass the input parameter in the URL to your page.
I am trying to create a new HTML page from a form and some javascript. The form is much longer than this, but I figured that if I gave you guys 2 text inputs I can take it from there. I am running into a problem where I cannot retrieve the value of my forms and send it on to my new page. My new page won't show anything because it thinks that my forms are null, or that they don't exist possible. Which is probably why it returns undefined. I'm completely stuck here and I have no idea what to do as far as setting up the new page from my form goes.
I need help with getting newPage.html to display my title and subtitle.
Here is js:
var title = document.createElement("h1");
var titleForm = document.getElementById("title");
var subTitle = document.createElement("h3");
var subtitleForm = document.getElementById("subtitle");
var myDiv = document.getElementById("container");
function getElements() {
//set the title
var titleNode = document.createTextNode(titleForm.value);
title.appendChild(titleNode);
//set the subtitle optionally
var subtitleNode = document.createTextNode(subtitleForm.value);
subTitle.appendChild(subtitleNode);
}
Here is the original HTML page:
<body>
<h1>Create A New Webpage Using This Form</h1>
<form id="form">
<label>
Title:
<input type="text" name="title" id="title" value="title">
</label><br><br>
<label>
Subtitle:
<input type="text" name="subtitle" id="subtitle" value="subtitle">
</label><br><br>
<input type="button" value="Generate Page" onclick="window.open('newPage.html');">
</form>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>getElements();</script>
</body>
Here is the page that I want to create:
<body>
<div id="container">
<ul id="myList"></ul></div>
<script type="text/javascript" src="pageGenerator.js"></script>
<script>setElements();</script>
</body>
I'm not looking for you to complete this for me, but just a little bit of guidance. Thanks.
It sounds like you want JavaScript on one page to read from JavaScript on another page. That's not possible on its own. You can't define var a = 1 on somePage.html then read that variable when the user's browser loads newPage.html.
You'll need to involve something else, such as the URL or local storage: https://stackoverflow.com/a/35027577/5941574
Query Parameters
One option is to make a GET request to newPage.html with whatever values you want include as query parameters in the request. Then newPage.html will contain a script that parses the URL to get the parameters and builds and inserts HTML into the document based on the values it finds in the URL.
Local Storage or Cookies
This works in pretty much the same way as the other method except instead of getting your values from the URL, it is saved to the user's computer with either cookies or local storage.
Server Side
A third option of course is to send the user's selections to a server and have the server build and serve the resulting page.
i was working on a program that i wrote in php, all is fine, the problem is the html page:
it has 1 textbox and 1 button.
In the textbox i have to write a link
when i load the page it clicks the button automatically, so i can use the php program, then it return back to the html page..
$(document).ready(function(){$('#printbuttoncustomer').trigger('click');});
The links that i need to use are always the same, except the number, example:
http://www.wowhead.com/npc=56843 --- http://www.wowhead.com/npc=56844 etc..
the problem is that everytime the page is loaded, it start to use always the link and can't go on with the next link with the new value
how can i solve this problem?
I think that i could use a txt file to save the last link i used, so in the html i can check the last link in the txt file and set the next value in the textbox.. But don't know how to do.
the code to start is this
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="jquery-2.0.2.js"></script>
</head>
<body>
<form method="POST" action="parser.php">
<input type="text" id="testo" name="testo">
<input type="submit" id="button" >
</form>
<script>
$(document).ready(function(){
$('#button').trigger('click');
});
</script>
</body>
</html>
convert the html page to php. When returning to this page from "parser.php", send back a response with next link and save that in the text field.
You can save the link in a session and not a file :
$_SESSION['URL'] = "Your URL HERE"
next time you read it like this:
var $MyUrl = $_SESSION['URL'];
Please check this link for more on PHP Sessions.
Since you have to persist the information of your last clicked page so that next time you load the page it goes to next page.
You can do this by two ways:-
*Server Side Change:-
You can implement sessions to store the information, where you store the last URL.
*Client Side Change:-
After HTML5 there are a lot of browser storage is available. So you can use local storage, it stores site specific data in browsers persistent memory. Also there is session storage available.Check this page for HTML5 Web Storage.
This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 7 years ago.
I have shared js code like this in angus.js
var g_colour;
function getcolour() {
return g_colour;
}
function setcolour(colour) {
g_colour = colour;
}
Which is accessed by html pages 1 and 2 like this:
1.html:
<html>
<head>
<title>Global javascript example</title>
</head>
<body>
Page2
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
2.html:
<html>
<head>
<title>Global javascript example page 2</title>
</head>
<body>
Page1
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
If I set a colour in one page and navigate to page 2, and THEN access the colour, it returns undefined. ie I it seems that a new instance of g_colour is created on loading a new html page.
I want to be able to access a sort of top-level variable which I can set in page 1 and access in page 2. How can I do that in Javascript?
JS variables never have been persistent, but there are two ways around this:
Cookies
Storage
Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.
Instead, you should probably look at the Storage option.
Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname
These values are saved across pageloads, but not sent to the server.
Use localStorage:
localStorage.setItem('name', 'value');
var something = localStorage.getItem('name');
setItem on your first page, then getItem on your second.
The localStorage persists across pageloads, as opposed to "normal" JavaScript variables.
"Normal" variables are initialized as soon as the JS file is loaded (And runs), but are destroyed when the file unloads, so when the user leaves a page.
You could also use Cookies, but they're a bit of a pain to work with in JS, since they're stored in a string like:
'name=value; name1=value1; name2=value2';
Each page request will request the script and execute its copy of it, even if the request stops at the client because of the cache, the current page still executes it from scratch. They are working with the same code, yes, but different instances (i.e. you have two copies of that variable in two different contexts).
The problem is that your page 1 is loading the JavaScript file and your page 2 is loading it again therefore whatever you have set in a variable on that JS file will be lost when page 2 is loaded since page 2 will initialize again the JS file. If you want you can use cookie to store the value or if it simple to you combine page 1 and page 2 but put them in a different div and show/hide the div according to your logic.