Change href depending on php response - javascript

I want to change the href of morestorieslink depending on the data received from mysql database i.e. if there is no row returned from server then the href for DOM element morestorieslink should change
I am using this for changing the href value
if (mysql_num_rows($result) == 0) {
?>
<script type="text/javascript">
document.getElementById("morestorieslink").href="select.php?<?php echo $selecturl?>=<?php echo $select; ?>&select=Continue";
</script>
<?php
echo "Url Changed";
}
In this case javascript doesn't work but the echo is displayed, I also tried embedding javascript inside php echo.
Thankyou

if (mysql_num_rows($result) == 0) {
?>
<script type="text/javascript">
// wait for dom to finish loading properly.
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("morestorieslink").href="select.php?<?php echo $selecturl?>=<?php echo $select; ?>&select=Continue";
});
</script>
<?php
echo "Url Changed";
}
Put this at the last of your page make it a point that no java script is executed after this. Rest all looks good.
Hope that helps.
Note :
the href you mentioned will append to the exsisting url.
Also check that $selecturl or $select is not null and isset.
You can also check the page source to check wether the link is generating properly or not (using Firebug in mozilla)

you can use ternary operator. Something like:
<?php echo $select ? $selecturl.$select : $otherURL;?>
I assumed your url is changing based on value of $select

Related

Get Json_encode to a different jQuery page

I am working on a little project to learn more about JSON, but I am kinda stuck. I did a PHP query to get content from my database and I want to pass that data to a different jQuery page with JSON (optional).
Here is my process.php file:
<div id="msg" class="msg">
<?php
$query = "SELECT id, d_prijs, code, artikelNL FROM artikel";
$json = array();
$result= $conn->query($query);
while($row = $result->fetch_assoc()){
$json[]= $row;
}
echo json_encode($json);
?>
</div>
This echo works fine and it gives a result, but I want to pass that result to another page and show it on that page.
Here is my jQuery file:
<script>
$(document).ready(function(){
$("button").click(function(){
var mycontent = $('div.msg').text();
console.log(mycontent);
});
});
</script>
But this doesn't seem to work, it doesn't give an error either. Any ideas on how I can improve?
You need to make AJAX call to the process.php page. Try the following code:
`<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax( {
type : 'GET',
url:'process.php',
success:function(mycontent) {
console.log(mycontent);
}
});
});
});
</script>`
If you have a single page application and when you say page you mean hidden/displayed content, your code should work. But if you have actual pages, this will never work because your source div does not exist in the DOM once you have switched pages

How can I place a drop-down list made in php in a specific HTML form?

I have some php that connects to a database and creates a drop down list. I have a specific form in the HTML that I'd like to put the list in.
<body>
<form>
// some text inputs
// where i'd like the drop down to go
<?php makeList(parameter1, parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList(arg1, arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
The only languages I'm allowed to use (apart from the sql) are php, html and javascript. As it is right now, makeList() returns an empty list. When I include opening and closing form tags in the function it returns a fully functional list, but then it acts as it's own form and I need to to be a part of the original form. Thanks.
EDIT: Sorry, forgot to mention the makeList function works fine when called within the php tags. It's when I call it in the HTML that it returns an empty list.
Firstly, you have some syntax issues with your script. It's not a valid HTML file, not a valid PHP file, and not a valid JS file.
If it were up to me, I'd define the PHP function at the stop of my script. Be careful to balance your opening and closing PHP tags. Something like this:
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
?>
And only after that would I start to output my HTML.
Now there are a couple of important things to note about that script I just posted:
the database code is not in here...I don't see any connection or query getting run or anything
In your script, this function doesn't look valid. arg1 and arg2 need a $ in front of each to be a valid PHP function. If it's a JS function you want then well, you are very confused and probably need to go back and figure out why this is not a valid JS function.
Your function refers to a variable, $result, that you have not bothered to define. It is not mentioned anywhere else in your script. It is most certainly not mentioned anywhere inside your function. For $result to be defined inside your function, you either need to pass it in as an array or declare it as a global:
global $result
Your function doesn't return anything at all. It just echoes stuff. This doesn't mean you can't use it, but it does mean that the function has no return value. Echoing the result of makeList won't output anything at all
So after that script above, you might have something like this:
<body>
<form>
// some text inputs
<?php makeList($parameter1, $parameter2); ?>
// submit button
</form>
Depending on what your parameters ($parameter1 and $parameter2) are this should work.
<body>
<form>
// some text inputs
<?php echo makeList($parameter1, $parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option>";
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>

Passing a SESSION variable to JS

Okay, here's something that may seem rather trivial, but it's been giving me a headache, and I must have some sort of mental block now.
I want to pass a SESSION variable into JS, and then ultimately onto another page... It's only the first part that I'm worried about for now, because I can't even get a good "alert". The variable is blank... "the page at xxxxx says ____", even though the username shows up in the HTML span tag.
So, here's the applicable code on my page.
EDIT - For those asking why I would do this, I read it on (this) post...
EDIT: Solved. The method to do this is best done with:
var player = "<?php echo $_SESSION['username']; ?>";
Didn't need jQuery or other code. It is simple and direct, and shame on me for just sticking with one proposed solution from the other post.
In answer to some other questions: I did already have start session() at the top of the file. The script was after the HTML/PHP code. ***
... HTML stuff...
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
...more HTML...
<script>
function rollpublic()
{
... some declarations...
var player = document.getElementById("username").innerHTML;
alert (player);
more JS }
</script>
Edit
Sidenote: One reason which may be the cause of your session name not appearing, may be because session_start(); is not present in your pages, nor is there any mention of it in your posted code.
Without seeing FULL code, is hard to pinpoint it.
However, here is a successful test that I performed using the following codes: (page 1 & page 2)
Page 1:
<?php
session_start();
$_SESSION['username'] = "USERNAME";
?>
Check session name
Page 2: (sessions_check.php) which will echo and alert the session name.
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
var player = "<?php echo $_SESSION['username']; ?>";
alert (player);
});
</script>
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
Appearing in HTML source: var player = "USERNAME";
and You are <span id='username'>USERNAME</span></div>
N.B.: session_start(); needs to be inside all of the pages using sessions in order for this to work properly.
(Original answer) This worked for me:
<?php
session_start();
$_SESSION['username'] = "USERNAME";
?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
var player = "<?php echo $_SESSION['username']; ?>";
alert (player);
});
</script>
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
You may call session by ajax:
function getSession(){
var session;
$.get('someUrlThatReturnSession', function(sessionData) {
session = sessionData;
});
return session;
}
You can assign SESSION variable to javascrip variable..
<script>
function myFunction(){
var a = <?php echo $_SESSION['var'] ?>;
alert(a);
}
</script>
If you need more help let me know..
If you're using Angular JS, you can use this approach. (Provide the PHP var to the ng-init param of a hidden input)

How would I call a java script function using php if statement with $_SESSION

Hi I am creating a website with a login section this is working I am using HTML and PHP. What I am trying to do is one of my pages has a html button I want this to be disabled for certain users. at the moment this is what I have got.
this is the part that I use for the login details.
<?php
session_start();
$_SESSION["username"];
$_SESSION["password"];
$_SESSION["access"];
?>
I have got if statments that I am currently using which are
if($_SESSION["access"] == "Administrator"){
echo $Admin;
}
what I am trying to do is call a javascript function within a PHP if statement what i have got so far is
<?php
if($_SESSION["access"] == "Consumer")
{
echo '<script type="text/javascript">
Disable();
</script>';
}
if($_SESSION["access"] == "Administrator")
{
echo '<script type="text/javascript">
Enable();
</script>';
}
?>
the javascript functions that i am trying to call are
<script type="text/javascript">
function Enable() {
SubmitButton.disabled = false;
}
function Disable() {
SubmitButton.disabled = true;
}
</script>
I have also tryed
if($_SESSION["access"] == "Consumer")
{
echo "<script> Disable(); </script>";
}
Im just wondering if I have typed something in wrong or if I have forgotten to put something in.
any help would be much appreciated.
Looking at your code you have couple of issues:
Mixing your PHP logic and pure HTML is (usually) not a good idea.
Instead I would suggest you move your access checking logic fully on the server side and display the button accordingly (disabled or enabled) based on the user's access.
Example:
<?php if($_SESSION['access']): // Only show the button for users with access ?>
<button type="submit" value="Submit" <?php echo ($_SESSION['access'] != 'Administrator' ? 'disabled' : ''); // Button disabled for everyone but administrators ?> />
<?php endif; ?>
And let me point out the obvious (as mentioned by the other answers), that's not 100% bulletproof. The user can still manually submit the button even if he is not an administrator by editing the page's HTML on the fly. That's just a UI fix. The real check should be done on the server side once the button is submitted (e.g. is the user logged in, does he have a cookie on his computer that identifies him as an administrator, does he have a session cookie set, etc).
Calling JS in random places, e.g. in the header can have unexpected consequences.
You better wait for the page to be loaded fully before calling any JS functions. You can do that via jQuery easily, but make sure you include the jQuery library before that in your header like so.
Afterwards you can call any JS after the page is loaded by placing them within the following block:
$(function(){
// Place your JS calls here, e.g. call to Enable()
});
String concatenation in PHP is done with a dot . and strings can be multiline
This code which you used is just plain wrong.
echo '<script type="text/javascript">'
, 'Enable();'
, '</script>';
You should use something like:
echo '<script type="text/javascript">'
.'Enable();'
. '</script>';
or better:
echo '<script type="text/javascript">
Enable();
</script>';
PHP doesn't use , sign for joining. Use ..
But otherwise it should work, except that you should define SubmitButton in advance of using it.
<?php
echo "<script type='text/javascript'>";
// if the id of your element is "submitButton"
echo "var submitButton = document.getElementById('submitButton');";
echo " function disable(){ submitButton.disabled=true; }";
echo "</script>";
?>
After that you can use it as you did..
<script type='text/javascript'>
disable();
</script>
Just be advised that denying access to some elements/functionality on your webpage with JavaScript alone is not a good practice - JavaScript is executed locally on the user's computer and therefore the user can modify it to gain an advantage.
Well, the problem may be that you're trying to call the javascript function before the HTML is ready (or finally rendered), so the browser, when executes the function doesn't find the button.
You could solve this placing your javascript code at the end of your page, or using jQuery and doing:
$(document).ready(function() {
<%php if ($_SESSION['access'] == 'xxxxx') {%>
Enable();
<%php } else { %>
Disable();
<%php } %>
});
Anyway, ALWAYS check user permissions on the server side, because someone could enable the button using Firebug or something else...

Updating session variable using onclick in php

I am trying to update the $_SESSION['state'] whenever the user clicks on the anchor tag by firing the onclick event. The variable $state_names_array as all the names of the states of a specific country. But problem is that no matter whichever of the anchor tag I click on, the $_SESSION['state'] is always getting updated by the last element of the $state_names_array.
<?php
foreach($state_names_array as $value){
$temp = '<?php $_SESSION["state"]=$value;?>';
?>
<?php echo $value ?><br>
<?php
}
?>
I will not code whole code, I will just show you an example, how to do it:
<?php
foreach ($state_names_array as $value) {
echo ''.$value.'<br>';
}
?>
Then you will have javascript function change_value:
here you will send ajax call to some PHP file, where you will process $_SESSION["state"]=$value;
Also you didnt say, what you want after anchor is clicked, because you will be able to access new $_SESSION["state"] only after refreshing your site...
Also maybe you just want to redirect to index.php, after clicking on some anchor, and that will be enough for you, then just use value as $_GET parameter, f.e.:
<?php
foreach ($state_names_array as $value) {
echo ''.$value.'<br>';
}
?>
and add to you index.php file this lines:
if (isset($_GET['new_value'])) {
$_SESSION["state"] = $_GET['new_value'];
}

Categories

Resources