Get php variable from url on reload without refresh - javascript

I'm working on a hobby project (usually working as a designer, so not all that familiar to php – please have oversight with all or any redundant code), trying to learn new things. Now I've bumped into a problem that I don't quite seem to get the hang of.
I have an index.php used to display random sentences from data.php, this works fine – however I want to be able to sort out specific types of sentences for different people if necessary. This is done with a dropdown containing Designer, Illustrator and Developer.
If for example you choose Developer from the dropdown menu, the page reloads with index.php?yrke=developer in the URL as a result. This is all fine and as expected, and when i echo $_GET['yrke']; from data.php it displays the text "developer" fine the first load, but upon clicking the randomizerButton button (note that the content is loaded from data.php without refreshing the page in the browser when clicking this button) $_GET['yrke']; does not seem to be able to get a read on the value in the url (putting $_GET['yrke']; in index.php obviously works regardless, but I need to access the url variable in data.php).
If there's a way to do this while maintaining the "update-content-without-browser-refresh" function that'd be awesome, the other easiest solution would perhaps be to remove said "update-content-without-browser-refresh" and go for good old refreshes and thus solving the problem – but why make it that easy right?
index.php (excerpt)
<button data-href="data.php" class="randomizerButton">Randomize sentences</button>
<form action="index.php" method="get">
<select name="yrke" onchange="this.form.submit()">
<option value="designer"<?=$_GET['yrke'] == 'designer' ? ' selected="selected"' : '';?>>Designer</option>
<option value="illustrator"<?=$_GET['yrke'] == 'illustrator' ? ' selected="selected"' : '';?>>Illustrator</option>
<option value="developer"<?=$_GET['yrke'] == 'developer' ? ' selected="selected"' : '';?>>Developer</option>
</select>
</form>
<?php include('data.php'); ?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button.randomizerButton').click(function(){
scriptUrl = $(this).attr('data-href');
$.post(scriptUrl, function(response){
$('#results').html(response);
});
});
});
</script>
data.php (excerpt)
echo $_GET['yrke'];

If you want $_GET['yrke'] on data.php you would have to use $.get() and just use the full URL, like:
$.get('data.php?yrke='+encodeURIComponent($('[name=yrke]').val()), function(response){
$('#results').html(response);
}
I would use
$.post('data.php', {yrke:encodeURIComponent($('[name=yrke]').val())}, function(response){
$('#results').html(response);
}
with $_POST['yrke'] on data.php. Usually, I would not have a form that submits in the traditional manner. It's all about the AJAX.

Not sure if this will help but you could do something like this...
<div id ="content">
<?php
$pages_dir ='pages';
if(!empty($_GET['p'])){
$pages =scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php', $pages)){
include($pages_dir.'/'.$p.'.inc.php');
}else {
echo'Page not found';
}
}else{
include($pages_dir.'/home.inc.php');
}
?>
HERE
</div>
Make a folder called pages then name the files within the folder "aboutus.inc.php" ect. the important part of the file extension is .inc.php , you can name anything before .inc.php anthing you like here is an example of how to write the navigation "About us"
IF need be I can send you a blank template

Related

Need help creating the php and/or javascript using a hyperlink to change the language on a webpage

I have previously used a dropdown selection box with options using a post method in order to change the language in a webpage that is saved on a separate file. I am now trying to create something similar but need help. Now I am trying to make the webpage for only 2 languages and when viewing the webpage on one language the option to switch to the other will appear. Essentially giving the viewer the option to change the session language to either English or Spanish only with showing the opposite language as a hyperlink on all pages. My language file is essentially as follows:
<?php
$lang = array(
'EN' => array(
'ABOUT' => 'About',
'HOME' => 'Home'
),
'SP' => array(
'ABOUT' => 'Acerca',
'HOME' => 'Casa'
)
)
?>
This PHP code that I have shown here is more extensive but this is how I set things up writing these lines of code on another file to be able to change the language. On my main page I have a short section of code before the html document is declared and that is as follows:
<?php
require("lang.php");
session_start();
$_SESSION['LANG'] = "EN";
if(#$_POST['lang-chooser']){
$_SESSION['LANG'] = $_POST['lang-chooser'];
}
?>
I am trying to make the portion of the page where I have the hyperlink to be located in the header or body of the document. The code I have currently for the option to choose a language is as follows:
<form method="post" action="" id="lang-form">
<select id="lang-chooser" class="lang-chooser" name="lang-chooser" onchange="window.lang(this);">
<option value="EN"<?php if($_SESSION['LANG'] == "EN") {?> selected="selected"<?php }?>>English</option>
<option value="SP"<?php if($_SESSION['LANG'] == "SP") {?> selected="selected"<?php }?>>Spanish</option>
</select>
</form>
Underneath my footer but still in the body portion I also have a little amount of script as follows:
<script type="text/javascript">
function lang(element){
var lang_name = element.value;
var e_form = document.getElementById("lang-form");
e_form.submit();
console.log(element);
}
window.lang = lang;
</script>
With all of these portions of code I was successfully able to change the language using the dropdown selection box while staying on the current page. The code I would use to have changeable text would be as follows:
<?php echo ($lang[$_SESSION['LANG']]['ABOUT']); ?>
Now I wish to have the option to change the session language on any page again but without the dropdown selection box. I wish to have it so that when the page is in English which it automatically should be when accessing the site there will be a hyperlink named Espanol which allows the viewer to change to Spanish and once the page is in Spanish the hyperlink will change to saying English which allows the viewer to change to English. From looking online I am lead to believe that I will still need the intro PHP code and javascript but will no longer need the "form" or "method" portion to change the session language. I believe all that I need now in replacement of the "form" and "posting-method" is as follows:
<?php echo($lang[$_SESSION['LANG']]['SPANISH']); ?>
I believe that my code is still lacking and this is why I still cant get it to work. Essentially I will need the hyperlink to change text according to the session and to also be used to change the session language from either Spanish or English. I am a little stumped here and would very much appreciate any kind of help. Thanks for taking the time to read this question.
You could replace your form with php if, else and get functions.
By using $_GET at the head of the page you can check if lang is set in the URL and set a session based on the result:
Edit
This section will replace everything after session_start(); in the second piece of php code you placed in the question.
<?php
if(!isset($_SESSION['LANG'])){
$_SESSION['LANG']='EN';
header('location: '.$_SERVER["REQUEST_URI"]);
}
if(isset($_GET['lang'])){
if($_GET['lang']=='sp'){
$_SESSION['LANG']='SP';
}else{
$_SESSION['LANG']='EN';
}
}
After you can check if the session is set then call out a href link to whichever language you want to change to.
This section will replace the html form
<?php
if(isset($_SESSION['LANG'])){
if($_SESSION['LANG']=='EN'){
echo 'Espanol';
}else{
echo 'English';
}
}else{
echo 'Espanol';
}
You don't need java to achieve this.
EDIT
If you want the URL not to show the ?lang= you can include another session and a header in the first section such as:
<?php
if(isset($_GET['lang'])){
if($_GET['lang']=='sp'){
$_SESSION['LANG']='SP';
header('location: '.$_SESSION['URI']);
}else{
$_SESSION['LANG']='EN';
header('location: '.$_SESSION['URI']);
}
}else{
$_SESSION['URI']=$_SERVER["REQUEST_URI"];
}
This will instantly redirect the user back to the page they were on, they shouldn't notice the refresh.
<?php
$allowed_langs = array('EN' => 'English', 'SP' => 'Espanol');
$site_lang = isset($_SESSION['LANG'])?$_SESSION['LANG']:'EN';
//Here you can set language according to link
if(isset($_GET['lang'] && in_array($_GET['lang'], $allowed_langs)){
$_SESSION['LANG'] = $_GET['lang'];
$site_lang = $_GET['lang'];
//Then you can refresh the page if you want to load new file or start
// including your language file after this language set.
}
//include your lang file
include_once( 'langs/' . $site_lang . '/text.php' );
?>
<ul>
<?php
foreach($allowed_langs as $langshort => $langlong){
$new_query_string = build_query_string($param, 'lang', $langshort);
$new_link = strtok($_SERVER["REQUEST_URI"],'?') . "?" . $new_query_string;
$class = ($_SESSION['LANG']==$langshort)?'selected':'';
?>
<li class="<?= $class ?>"><?= $langlong ?></li>
<?php } ?>
</ul>

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Auto filling a form and submitting based on a ajax search answer

This problem has been frustrating me for a few days, and as I have found some help here for other problems on my project, it seems that someone could provide insight that I am overlooking.
I admit I am very new to sql, javascript, jquery, ajax, css, and php. I did 3 years of Computer science in college (15 years ago) While coding and logic don't change much, its syntax and handshakes, and where the computing is happening that I have either forgotten, overlooked, or am ignorant.
I have completed an ajax based search submission.
this search displays the target php in a div labeled .Admin
this works excellently.
Its answer is a display of a tree and the nodes above and below the searched node.
I want to make each node in the tree a clickable link to the search results for its own node.
In the php result I coded it to write in a html call to a javascript function and it generates a unique id for each , as well as its own function call. (whether or not that is a good idea its what i tried) I would think that it is then easy to get javascript to fill out the form with the created link using information it knows and resubmit as no refresh is needed to search again. I tried having the php write this script so that it is developed with the page, and I have tried writing the script and including it in the parent page, so that it is already loaded... I'm not sure where it should go or how it should be written.
I may be missing an integral part, or I'm trying to do more than I am supposed to with the code or not completely grasping where the operation is happening and need to rethink it entirely.
I will try to include all relevant code, if its not enough, I will happily add. Thanks in advance.
CallSearch.js
$(document).ready(function() {
$('#Search').submit(function(event) {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : $( this ).serialize()
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
Menu.php (where my search form is)
<script src="/JS/CallSearch.js"></script>
...
<li><a>Search</a> <input type= "text" name="Search" id="search_name" class="search-group">
<ul>
<li><input type="radio" name="Table" id="TableRegion" value="R" class="search-group" checked><label for="TableRegion">Region</label></li>
<li><input type="radio" name="Table" id="TableGrape" value="G" class="search-group"><label for="TableGrape">Grape</label></li>
<li><input type="radio" name="Table" id="TableWine" value="W" class="search-group"><label for="TableWine">Wine</label></li>
<li><button type="submit" id="SubmitSearch">Submit</button></li>
</ul>
</li>
</form>
...
MenuSearch.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'Webpage');
define('DB_PASSWORD', 'Guest');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
...
$sqlp ="SELECT * FROM region a JOIN Regionclosure b ON a.idregion=b.parent WHERE b.child= $idReg ORDER BY b.Depth DESC;";
...
$resultp = mysqli_query($db, $sqlp);
$string ="";
while($row = mysqli_fetch_assoc($resultp)){
$Reg = $row["RegName"];
$Parent= $row["Parent"];
echo $string . "|___";
if($_SESSION["Level"] == 'A' or $_SESSION["Level"] == 'C')
echo $Parent . " - ";
echo "<a href='#' id='$Reg'>" . $Reg . "</a><br>";
echo "
<Script>
$('#$Reg').click(function(){ searchforReg('$Reg'); return false; });
</script>";
$string .= " ";
};
I have tried multiple iterations of a function for "searchforReg('$Reg'); to no avail... i feel like it should be something like :
function "searchforReg(Region){
SearchData= "Table=R&Search="+$(Region).val;
(function() {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
This however results in activating the "action" search failing to send the answer to the and opens the php (with no CSS... gasp.. its just not pretty) I feel like a simple javascript should be able to handle it, but i tried all of the different ways i could think of (or look up) to make it work to no avail.
I realize I am playing in the "deep end," and I'm in my "water wings" so if you could have mercy and push me to the edge, I would appreciate it.
First, the process of printing a click handler for each link is overkill. Instead, just give each link a class and set up a single handler for any link of that class. In menusearch.php:
echo "<a href='#' id='$Reg' class='reg_link'> $Reg </a><br>";
$string .= " ";
Side note - in PHP, if you echo with "double" quotes, variables will be rendered, so no need to concatenate. That's why $Reg is just hanging out. If you echo with 'single' quotes, the string is interpreted literally.
Then in menu.php, we have a bit of javascript:
<script>
/* This is a non-standard listener, bound to the body so that any
dynamically added elements pulled in via ajax, but not in the original document can still be found.
Also, this can be shortened to a single line, but I split it up for clarity.
The single-line version is commented out. */
$(document.body).on('click', '.reg_link', function(){
//searchforReg($(this).attr('id'));
var id = $(this).attr('id'); //get the id of clicked element
searchforReg(id); //trigger function
});
function searchforReg(Region){
var SearchData= "Table=R&Search="+Region;
//If you're not familiar with console.log, it's a huge help in debugging
//console.log('searchData = ', SearchData);
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
}
</script>
Finally, I'm guessing you have some $_POST handling in MenuSearch.php for that data, but I don't see that above so I'll assume it's working...

global variable not displayed in div

I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

Categories

Resources