PHP link written into page not being retrieved by a JAVASCRIPT function - javascript

I'm writing on a page the following code with PHP. This code creates a A HREF link with the ID equal to $intIdType, which is the value of the PRIMARY KEY in a database, and $count gets the amount of records per category on the database. All of this is inside a WHILE that reads each record and writes on the PAGE the results
echo "<a href='#' id='$intIdType'>";//Starts creating the link
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "(";
echo " $count1 )"."</a>";
Now, after the results are on the page it will look like this:
$intIdType $arrBusinessTypes $count
--------------------------------------------
1 -Auto Sales ( 1 )
2 -Auto Repair ( 1 )
5 -Web Desig & I.T. Services( 2 )
6 -Computer Shop ( 1 )
The above result displays each rown as a link where I can click on it, but nothing happens. Even just a simple Alert in javascript does not show up. It seems that it never reaches even the Javascript at all.
What I need now is to retrieve that PHP generated code on the page by a Javascript file, that will allow me to use the hiperlink generated by PHP into the .HTML page
It works if I write directly into the page what PHP is suppose to write. I wonder if this happens because Javascript can not read posted data from PHP into the page.
The Javascript File looks like this:
window.onload=post_result
function post_result() {
$("#1").click(function() { //This is the HREF ID that is written by PHP into the page
$('#list_results').load("results.php");//This seeks to run a PHP file in a DIV
$('.title').text('Listing Categories');//This just replaces the Title in the page
})
I'm just a beginner trying. Thanks for any help.

echo "<a id='$intIdType'>";//Starts creating the link echo "$intIdType -";
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "("; echo " $count1 )"."</a>";
just remove href attribute and try

Remark #1: quote custom data when outputs it to HTML:
echo $arrBusinessTypes["business_Description"]; must be
echo htmlspecialchars($arrBusinessTypes["business_Description"]);
Remark #2: you don't need window.onload handler here. In this piece of code you select complex way to do simple thing. Why do not write direct onclick handler? Write function loading some data depending of parameter and do something like:
$htmlspecialchars = function($s){return htmlspecialchars($s);};
echo <<<HTML
<a href='#' id='$intIdType' onclick='loadInfo($intIdType)'>
$intIdType -{$htmlspecialchars($arrBusinessTypes["business_Description"])} ( $count1 )
</a>
HTML;
(converted to heredoc to make HTML more clean)

Related

PHP code in innerHTML

I'm trying to have my code add this 2 fields to a form (quantities and products) on a click of a button.
How do I format my script so the innerHTML can include php code?
Or is there another way to add a select element via JS?
newdiv.innerHTML = "<input type='text' name='quantities[]'> <select name='products[]'>
<?php
$sql = mysqli_query($link, "SELECT name FROM inventory");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"".$row['name']."\">" . $row['name'] . "</option>";
}
?>
</select>";
PHP code is interpreted by your server before the page is even sent to the browser. The server then sends a completed html page (no PHP code) across the internet to your browser, which then loads it and then executes the JavaScript in the browser. The PHP interpreter would have no way of reading what the JavaScript changes on the finished page.
You might want to look into making an Ajax call to a PHP page, your PHP page can then contain the sql query and return data the JavaScript can use to add the options.

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>

sending value with link with javascript

I am viewing the content of mysql inbox_messages table and view every message as link to reply the message or delete . so i have to send the message id with the link to specify the message in the editing page the code was
<a href="sompage.php?m_id=<? echo $m_id; ?>" >
and it's working.
But when I tried to make it with javascript to make the reply like chat box i dont know how to send the message id while opening and to get the id with php and i am opening the message in a div with this code
<a href = "javascript:void(0)"
class="display"
onclick = "document.getElementById('responsecontainer').style.display='block';document.getElementById('fade').style.display='block'"
style="font-weight:normal;">
<a href="sompage.php?m_id=<? echo $m_id; ?>" >
can be replaced by appending ?m_id= and a variable equal to whatever $m_id is.
Example:
var m_id = <?php $M_id ?>;
var yourLink = document.getElementById("replyLink");
yourLink.href = yourLink.href+"?m_id="+m_id;
That said, getting $m_id into the javascript without inline PHP in a synchronous manner would probably require the use of GET parameters, which is another topic, so I'll just give you a helpful link to get started:
http://javascriptproductivity.blogspot.com/2013/02/get-url-variables-with-javascript.html

How set id from database to php session on link click

but lets talk from the begin. I am creating website similar like wordpres blog index page (can't show picture bescause dont have enough reputation). And then I click read more link in the intro article I want save that article id from the database to php sesions. Here is the code.
while($row = mysqli_fetch_array($result))
{
echo '<div class="img">
<img src="img/smiley.gif" alt="Smiley face" width="250" height="250">
</div>';
echo "<h2>".$row['Name'] . "</h2> " ;
$string = strip_tags($row['Content']);
if (strlen($string) > 500) {
$stringCut = substr($string, 0, 500);
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... Read more';
}
//echo $string;
if(isset($_GET['link']) /*you can validate the link here*/){
$_SESSION['link']= true;
}
echo $string;
echo "<br>";
echo '<div class="content dashboard clearfix"></div>';
echo '<hr>';
}
mysqli_close($con);
?>
So I have 3 intro articles in index.php file and I whant read one, so I press READ MORE (then I should write article id to session) and go to other page, were I think I should get articles id from session. I am tryyng do it with
if(isset($_GET['link']) ){ /*you can validate the link here*/
$_SESSION['link']= true;
}
But it always write number 5 the last ID from database, so I think I should use maybe AJAX, javascript?? Maybe some one can give me the example?
Thank you.
You could set a SESSION variable through ajax but... that'd get pretty insane, making things overly complicated and not very SEO friendly
There's a better method: Make your "read more" actual links to your content. So you've got a "read more" link to http://example.com/page.php?id=5, then inside "page.php" you simply do:
$Id = intval($_GET['id']);
You can make this more pretty after reading how to create friendly URL in php? so they look like http://example.com/page/5.
From your code, you automatically go to the desired page when clicking on the link. Therefore, you only need to create the page post.php and retrieve a single row from the database, in a similar fashion as I indicated above but with the proper name:
$Id = intval($_GET['link']);

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