how to run a php code on clicking a hyperlink - javascript

I am working on a module, "who viewed your profile" in a social networking site project. When a logged in user clicks on hyperlink of a user, he must be directed to a dummy page called view.Information of user who has clicked link of other user and username of user whose link has been clicked is stored in a database table, views. I tried doing this by calling a function updatetable on click of the hyperlink and using this function, I want to send variables viewername and viewedname to view.php, which inserts a record into views table.
while($row=mysqli_fetch_array($res))
{
?>
<?php echo $row['username']; ?>
<?php
}
The above code displays links of all users and if a link is clicked, view.php page is opened where some php code has to be run.
My updatetable function is as follows:
<script type="text/javascript">
var viewedname,viewername;
function updatetable(viewedname,viewername)
{
$.post('view.php' { viewer_name:viewername, viewed_name:viewedname } );
alert(viewedname);
}
</script>
view.php code:
if ($_POST && isset($_POST['viewer_name']) && isset($_POST['viewed_name'])) {
$viewer_name = ($_POST['viewer_name']);
$viewed_name = mysql_real_escape_string($_POST['viewed_name']);
$con=new mysqli('localhost','root','','test');
if($con->connect_error) echo $con->connect_error;
$r=mysqli_query($con,"insert into views(viewer,viewed) values('$viewer_name','$viewed_name')");
}
Problems that I am facing:
alert is not being shown and insertion is not happening after view.php code.
Is there a mistake in the way I'm sending the viewer_name and viewed_name variables?
I am new to php. Please help me out! Thank you :)

Missing a (,) in your javascript post:
Replace with:
$.post('view.php', { viewer_name:viewername, viewed_name:viewedname });
PHP:
Its better doing it this way:
if ($_POST){
if(isset($_POST['viewer_name']) && isset($_POST['viewed_name'])) {
//Do your stuff
}
}

Related

Submit form and then after the form is processed open a new page

I'am trying to delete an entry/offer from the database and then get back to all the entries/offer overview page. I tried to do it with Javascript but unfortunately it does not open the overview page. It does the deleting but then stays on the page.
Is that the correct way anyways with javascript?
Here the two links Overview and delete Offer
<a id="overview" href="/mbm-kalkulation">Overview</a>
<form method="post" action="/?id='.$_REQUEST["id"].'" name="delOffer"><button type="submit">delete Offer</button>
Here the javascript which should click the overview page after the form got submitted.
((isset($_REQUEST["delOffer"]))?'
setTimeout(function(){
jQuery("a#overview").click();
}, 1000);
':'')
Normally such redirects are done using the header function from php. This is only possible, when the headers weren't already send. In this case you will have to use a JavaScript fallback. The code could look something like this:
if (isset($_REQUEST["delOffer"])) {
if (!headers_sent()) {
header("Content-Type: text/plain");
header("Location: {$url}");
} else {
print "<script>window.location = '" . addslashes($url) . "';</script>";
}
exit;
}

External php file that is loaded into index.php with .load() method not recognising $_SESSION variables

So my main page loads other php pages into it with click of a button so it can be a single page website without having to load all the content at once.
index.php
<?php
session_start();
?>
<head>
$('#btnPetShop').one( "click", function(){
$( "#page_shop" ).load( "shop.php" );
});
</head>
<body>
<?php
echo session_status();/----Always returns 1, no matter if logged in or not----/
if(isset($_SESSION['admin']))
{
if($_SESSION['admin']==1)
{
/----this part works, I am logged in as admin----/
}
}
?>
<div id="page_shop"></div>
</body>
shop.php
<?php
if(isset($_SESSION['admin']))
{
if($_SESSION['admin']==1)
{
}
else{}
}
else{} <----I end up here as if $_SESSION['admin'] is not set----/
/----code entered here loads fine----/
?>
The idea is to make a delete and edit button (if you are logged in as admin) on every article in shop.php.
Problem is that $_SESSION['admin'] is recognized on index.php, but not inside shop.php
I tried typing the content of shop.php directly into and it works, the problem is that i want it to load with a click of a button.
Where ever ( in any PHP page) if you want to use any Session variable then you have to first declare session_start(); so, in your case if you have $_SESSION['admin']="User1234" on index.php and if you want to use value of $_SESSION['admin'] in shop.php then you have to again declare session_satart(); and then use it. For example, If let consider that index.php has session variable $_SESSION['admin']="User1234" and now you want to print "Welcome User1234" on shop.php then you can do it as shown below.
index.php
<?php
session_start();
$_SESSION['admin'] = "User1234";
?>
Shop.php
<?php
session_start();
echo "Welcome, ". $_SESSION['admin']
?>
Output:
Welcome, User1234
You need to add session_start(); in each page that needs access to the session data.
See: http://php.net/manual/en/function.session-start.php
EDIT
Since the solution mentioned in my original answer does not work for you and session_status() returns 1 in your code, it means sessions are enabled on your server. There is only one thing left which could explain that your sessions are lost:
You are loading shop.php with an AJAX request, is the URL exactly in the same domain as index.php? Try to add the full path before shop.php to see if this solves the issue.
Just to be clear, if your index.php runs on http://localhost/test/index.php, your new code will be:
$( "#page_shop" ).load( "http://localhost/test/shop.php" );
Well okay, I feel dumb... I found the solution.
I had this as a script
$('#btn_logout').click(function(){
<?php session_destroy();?>
});
This is a big no no and if you do this you should be ashamed

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>

Looking for a better way to show/hide an element

I'd like to know if someone could please show me a better way to show/hide an element on my page. This is how I am currently doing it.
At the very top of my index.php file, I have the code for my application. Here is the function which determines whether the form has been submitted and populates $_SESSION['prompt'] with data.
private function validateForm() {
if (isset($_POST['submit'])) {
$_SESSION['prompt'] = 'Form submitted';
}
}
And here is the element which I would like to show/hide depending on whether the form has been submitted located towards the bottom of my index.php file.
<p id="dialog">
<?php
if (!empty($_SESSION['prompt'])) {
echo $_SESSION['prompt'];
}
else {
echo '<script>document.getElementById("dialog").style.display="none";</script>';
}
?>
</p>
It's hardly a great leap in creative logic to work that one out
<?php
if (!empty($_SESSION['prompt'])) {
echo '<p id="dialog">'.$_SESSION['prompt'].'</p>';
}
else {
// nothing
}
?>
Why are you setting $_SESSION variables that you then use in the same file, as opposed to just variables? Are you using that data later?

href call in javascript

I have a problem with using , during
click of the link, I need to update a field in the database and redirect to another page after.
I have this code:
<a href="#" onclick="<?php
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."'
WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
$logger->debug('OK');
}
else
{
$logger->debug( 'NOt OK');
}
?>"> </a>
After the php end tag '?>' can I add my path to be directed to? like:
<a href="#" onclick="<?php
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."'
WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
$logger->debug('OK');
}
else
{
$logger->debug( 'NOt OK');
}
?> ../index.php"></a>
Is that even possible?
What is the right thing to do it?
Thanks a lot!
this is not the right way.
There can be multiple ways you could take to do this. But I'd suggest you to place the DB update code in the target page (that I assume you mentioned as index.php). If you only want to trigger the DB update code on clicking of the link, use a page in middle to redirect the flow.
So, your page flow will be:
Current Page (Link Clicked, simple href to middleman.php) ==> middleman.php (just run the DB update code here and use header Location syntax to index.php) ==> index.php
codes:
page in which you have the link
source.php
<.... html contents ....>
<a href='middleman.php'>Visit the page</a>
<.... more html contents ....>
middleman.php
<?php  
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."' WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
 $logger->debug('OK');
}
else
{
 $logger->debug( 'NOt OK');
}
header("Location: index.php"); //redirects to index.php
?>
index.php
do whatever you want
When a page is rendered, php code will run once. Whenever you see a webpage, it's only html, always, with no live access to the php code. So, you cannot execute php blocks directly from for example a javascript event. In your case the sql query would execute once, when you load the page.
kishu27 just posted one of the proper ways to do it, and the best option for you in this case. If you only wanted to update the database, without being redirected to another page, an ajax call to a php page with the database code would be a good alternative.
Using location.pathname

Categories

Resources