Link doesn't call JS function - php

Interesting. I have 2 links calling 2 JS functions - the first works , the second - doesn't. It only calls function addns() when the argument is empty. Otherwise nope...
PHP:
while ($row_mem = mysqli_fetch_array($mem)) {
$membs[] = $row_mem['username'];
$membs_id[] = $row_mem['user_id'];
}
}
//FIRST FOREACH CALL PROPERLY
foreach($membs_id as $val_id) {
echo"<a href='javascript:addms($val_id)'><img src='$pcheck' width='66' height='68'
border='1' class='currmem'/></a> ";
}
//THIS ONE DOESN'T
foreach($membs as $mes_id) {
echo"<a href='javascript:addns($mes_id)'>$mes_id</a> ";
}
JS:
function addms(msid) {
var addm = msid;
alert(addm);
}
function addns(nsid) {
var addn = nsid;
alert(addn);
}
I cannot see any error - thanks for comments !

Update to match new answer:
you need to put quotes around your variables. ($val_id) probably works because you're retrieving an id which I'm guessing is an integer, so it's a valid JavaScript literal.
($mes_id) probably doesn't work because you're getting strings back but not wrapped with quotes, so they aren't valid JavaScript literals.
so usernames will be joe and shmoe, javascript becoems
addns(joe) and addns(shmoe), which is probably not what you want. You want addns("joe") and addns("shmoe").
Also note once you fix this is an XSS vulnerability if users can choose their username.

See here: http://us2.php.net/manual/en/function.echo.php
Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo
I can't see how you're using the wrong quotes to be honest, other than if the JavaScript function requires them, so just to make everything simple, try this:
//FIRST FOREACH CALL PROPERLY
foreach($membs_id as $val_id) {
echo "<a href='javascript:addms(\"".$val_id."\")'><img src='".$pcheck."' width='66' height='68'
border='1' class='currmem'/></a> ";
}
//THIS ONE DOESN'T
foreach($membs as $mes_id) {
echo "<a href='javascript:addns(\"".$mes_id."\")'>".$mes_id."</a> ";
}

Related

output value of json array and then sent another get request with the values

i am really new to stackoverflow and actually dont have any clue about php.
I have a json array which looks like
[{"betreff":"h"},{"betreff":"VS Code fehlt"}]
i´ve created (copied :D) a foreach loop
to output the "h" and "VS Code fehlt"
function display_array_recursive($json_rec){
if($json_rec){
foreach($json_rec as $key=> $value){
if(is_array($value)){
display_array_recursive($value);
}else{
echo '<a href="#" onClick="test("'.$value.'")">';
}
}
}
As we can see now the "h" and "VS Code fehlt" parts are being outputted as links. I want to make it so that whenever I click on the link a new get requests should be sent out with the giving value.
function test($value){when pressed = send new file_get_contents request to localhost/api/ticket/{$value}}
i hope i could describe good enough what i want.
Thanks in advance, please inform me if anything is unclear
You can't use PHP to make GET requests like that (unless you use a hidden IFRAME, as far as I know). You need to use JavaScript for that, using any of those APIs (if you're using vanilla JavaScript):
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Example:
<script>
function test(url)
{
fetch(url);
}
</script>
<?php
function display_array_recursive($json_rec)
{
if (!$json_rec) {
return;
}
foreach($json_rec as $key=> $value){
if (is_array($value)) {
display_array_recursive($value);
continue;
}
echo '<a href="#" onClick="test(\''
. htmlspecialchars(
$value,
ENT_QUOTES|ENT_HTML5,
'UTF-8'
)
. '\')">Text</a>';
}
}
Notice the function display_array_recursive is escaping the HTML. It's also using ' (single quote) for the test arguments. It's already using " (double quote) for the element attribute values.
I suggest you to read:
How do I run PHP code when a user clicks on a link?
https://www.delftstack.com/howto/php/onclick-php/
https://johnmorrisonline.com/prevent-xss-attacks-escape-strings-in-php/
https://stackoverflow.com/a/3996696/4067232
https://betterprogramming.pub/refactoring-guard-clauses-2ceeaa1a9da

PHP variable Syntax using _GET

I have a redirectURL that currently redirects to a default page and works great
$WA_redirectURL = "mypage.php";
I want to insert a _GET value that is available but am getting a syntax error. Here is what I am trying. I thought the periods would allow me to get the value into the URL?
$WA_redirectURL = "mypage.php?EmpNumber=". echo $_GET['EmpNumber'] .";
You don't use echo when concatenating strings:
$WA_redirectURL = "mypage.php?EmpNumber=". echo $_GET['EmpNumber'] .";
should be:
$WA_redirectURL = "mypage.php?EmpNumber=". $_GET['EmpNumber'];
(The last quote is also an error).
You use echo to send text to the user.
If you want to join strings together use the period to join things.
For example:
echo "hello"; // this will print hello to the screen
$testing = "hello "."world!";
echo $testing; // this will print hello world! to the screen.

HREF to call a PHP function and pass a variable?

Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4

I have a variable with another variable within its name. How do I change it into a session variable?

Basically what the title says. I know how to make a normal variable into a session variable ($_SESSION['var']), but not when it contains another var
This is my code:
<?php
session_start();
$_SESSION["uname"] = "Tyler";
if (isset($_SESSION["coins{$uname}"]))
{
echo "$_SESSION["uname"] : $_SESSION["coins{$uname}"]";
}
elseif ($_SESSION["uname"] == "LOut")
{
$_SESSION["coins{$uname}"] = "0";
echo "Log In";
}
else
{
$_SESSION["coins{$uname}"] = 500;
echo "$_SESSION["uname"] : $_SESSION["coins{$uname}"]";
}
?>
I've tried the following:
$_SESSION['{coins.$uname}']
$_SESSION['coins.$uname']
$_SESSION['coins.$_SESSION['uname']']
And I don't remember if I've tried anything else.
Double-quotes are the ones you want.
$_SESSION["coins.$uname"]
Or
$_SESSION["coins.{$_SESSION['uname']}"]
Either of those should work just fine.
Explanation:
Single quotes will encapsulate a string as-is. Double quotes will actually parse the string and replace any variables contained within. Sometimes, a variable will not be clearly identifiable within the string, for example:
print "This is the $numberth time";
// Expected: 'This is the 50th time'
// Actual: 'This is the time'
In this case you can use curly braces to clearly separate a variable, ie:
print "This is the {$number}th time";
As a rule of thumb, I usually wrap any object attribute or array value within curly braces, ie:
print "This is the {$this->number}th time";
print "This is the {$time['number']}th time";
You say that it's not working, but you haven't specified if setting it or echoing it is the problem: Based on your original, unedited question, there are two problems:
Setting the session variable
This should work:
$_SESSION["coins{$uname}"] = 500;
If you can't get it to work, try breaking it down into a couple of steps.
$tempname = 'coins'.$uname;
$_SESSION[$tempname] = 500;
Now test it.
Outputting the session variable
echo $_SESSION["coins{$uname}"]; or echo $_SESSION[$tempname];
Edit
There is a syntax error in your code:
echo "$_SESSION["uname"] : $_SESSION["coins{$uname}"]";
You are closing your starting quote (") by mistake when you try to open quotes for ["uname"]. Try:
echo "$_SESSION['uname'] : ".$_SESSION["coins{$uname}"];
Try
$_SESSION["coins{$uname}"]
The difference is...
1) Double quotes when using the brace syntax
2) I'm assuming your using the dot . character for concatenation here? You dont need it if you use the brace syntax...
can you try this?
$$coins = "Tyler";
if (isset($$coins))
{
echo "uname : {$$coins}";
}
elseif ($$coins == "LOut")
{
$$coins = "0";
echo "Log In";
}
else
{
$$coins = 500;
echo "$uname : $$coins";
}
?>
<br>
Test
</div>
<div id="footer">
</div>
so your session will be
$_SESSION['$$coins']
This is the way i handle variable variables...
Dins

Display personal messages list

I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
    $(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.

Categories