Want to pass php variable as argument in javascript function? - php

i want to pass my php variable in one javascript function.
i know it seems simple but i don't know where am i missing something?
<?php
while($gg=mysql_fetch_array($lg))
{
?>
<td id="add_td">
<?php
$id = $gg['p_id'];
echo "<a onclick=cnf('Are you sure you want to delete that?',$id)>"; ?>Delete</a>
</td>
<?php
}
?>
and in my javascript function
function cnf(msg,id)
{
cnf = confirm(msg);
if(cnf) {
parent.location.href = 'p_update.php?d=' + id;
}
}
so i need to know on which id that user had clicked so that i will only delete that id from database.
if i try this thing then it showing error on "cnf" function and its saying like "unterminated string literal"?

if $id is not numeric you should write
<?php
while($gg=mysql_fetch_array($lg))
{
?>
<td id="add_td">
<?php
$id = $gg['p_id'];
echo "<a onclick=cnf('Are you sure you want to delete that?','".$id."')>"; ?>Delete</a>
</td>
<?php
}
?>

Use quotes around php variable '$id'.
echo "<a onclick=cnf('Are you sure you want to delete that?','$id')>";
Another example,
$p is some php variable,
echo "<input type=button value='update' onclick=myfunc('$p')>"

Check your syntax
<?php
while($gg=mysql_fetch_array($lg))
{
?>
<td id="add_td">
<?php
$id = $gg['p_id'];
?>
<a onclick="cnf('Are you sure you want to delete that?',<?=$id?>);">Delete</a>
</td>
<?php
}
?>

I would do something like this instead. HREF is mandatory if you want the "hand" pointer
A unique ID is also mandatory on tags and you need to quote the ID if you pass it in the function instead of what I suggest and give the link the id
function cnf(link,id) {
if (confirm("Are you sure you want to delete "+id) {
link.href = "p_update.php?d=" + id;
return true;
}
return false;
}
<?php
while($gg=mysql_fetch_array($lg)) {
$id = $gg['p_id'];
?>
<td id="add_td<?php echo $id; ?>"><a target="_parent" href="#" id="<?php echo $id; ?>" onclick="return cnf(this)">Delete</a></td>
<?php } ?>

foreach($mas as $k=>$v) {
//echo $k.' = '.$v.'<br>';
echo("
<input type=\"button\" id=\"delete_id".$k."\" value=\"Blablabla\" onclick=\"alert('".$v."');\"/>
");
}
If I put there $k (index) it works but if string (value is string), I get an error
unterminated string literal
In HTML tags this works but not as the function argument!

If $id is a string literal, you should put it into quotes when you are passing it as a parameter to cnf() function in <a ... > tag:
echo "<a onclick=cnf('Are you sure you want to delete that?', '$id')>";

Related

How to add GET and remove

I have more GET variables. I want the variables to be added after clicking. And after clicking again I want them to be removed from GET. I am a beginner and I don't know how to do it.
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url=$_SERVER[QUERY_STRING];
if(!empty($url)){
$url="&".$url;
}
?>
<form action="" method="GET">
<?php
foreach($tab_array as $key => $val){
?>
<?php echo $key;?>
<?php
}
?>
</form>
Someone will help?
Sorry for my bad English...
Code
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url='?'; // this will call the current url
// $_GET is the array your submitted data will be strored in - initially empty []
?>
<form method='GET'><!-- you actually don't need a form, since only input, textarea, etc get submitted -->
<?php
// save current state, so you can modify it for every possible click
$current_get = $_GET;
foreach($tab_array as $key => $value) {
$new_get = $current_get;
// check if the current key is already in your set ($new_get)
if (array_key_exists($key, $new_get)) { // it is, so remove
unset($new_get[$key]);
} else { // it is not, so add
$new_get[$key] = $value;
}
// build your query_string (from $new_get array)
$query_string = http_build_query($new_get);
// you can use variables in string when its encapsulated in double quotes: "text $var"
echo "<a href='$url$query_string'>$key</a>";
// more readable:
// echo "<a href='{$url}{$query_string}'>{$key}</a>";
// not need but looks better :P
echo '<br />' . PHP_EOL;
}
?>
</form>
A little more
there is a shortcut for <php echo $var ?> which is just <?= $var ?>
Links
array_key_exists
unset
http_build_query

hello! I am new in php could please you tell me the answer. I am not getting Output for this PHP Program

why I am not getting output as a uid ?
this is my index.
<a href='my_posts.php?u_id=$user_id' class='list-group-item'>My Posts(<?php echo $post_count; ?>)</a>`
and this is my my_posts.php
<?php
include('function.php');
user_posts();
?>
and this is my function.php
<?PHP
function user_posts(){
global $con;
if(isset($_GET['u_id'])){
$u_id = $_GET['u_id'];
echo $u_id;
}
}
?>`
Maybe you should change you code like this:
<a href='my_posts.php?u_id=<?php echo $user_id;?>' class='list-group-item'>My Posts(<?php echo $post_count; ?>)</a>
`
Here's how your index should look:
<?php
$user_id = 12; // Example value
$post_count = 3; // Example value
echo "<a href='my_posts.php?u_id=$user_id' class='list-group-item'>My Posts($post_count)</a>";
You can remove the $user_id=12 and $post_count=3 in your implementation.
Your my_posts.php and function.php can stay as they are.
Edit: in your function.php you could additionally check if $_GET['u_id'] is of type integer using is_int()
There are several errors in your provided code
$user_id is not initialized anywhere, the function user_posts() echoes $u_id and not $user_id which you are printing.
Echoing inside a function is incorrect if you want to access its output, return should be used instead. Read more about return in php manual
<a href='my_posts.php?u_id=**$user_id**' class='list-group-item'>
This syntax is also incorrect as it is, php variables need to be present inside <?php ?> tags else they will be treated like simple text.
Solution:
<?php
include('function.php');
$user_id = user_posts(); // You can now use $user_id to print the output of user_posts()
echo "<a href='my_posts.php?u_id={$user_id}' class='list-group-item'>My Posts({$post_count})</a>";
?>
function.php
<?PHP
function user_posts(){
global $con;
if(isset($_GET['u_id'])){
$u_id = $_GET['u_id'];
return $u_id; // echo changed to return
}
}
?>
simply change single quotes to double quotes in anchor tag. In single quotes you can't put php variables.
<a href="my_posts.php?u_id=$user_id" class='list-group-item'>My Posts(<?=$post_count?>)</a>

Pass href onclick variable to function in PHP

I am trying to pass variables stored in href links to a function. Im able to define the variables from the query results. My problem is passing it to the function once the hyperlink is clicked. This is my code:
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
{
echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
}
?>
This is the function:
<script>
function hrefClick($course){
$newCourse=$course;
}
</script>
PHP Code :
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
{
echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
}
?>
Function should be as:
<script>
function hrefClick(course){
// You can't define php variables in java script as $course etc.
var newCourse=course;
alert(newCourse);
}
</script>
We will be using two file here. From file1.php onclicking the link we will send the data via Ajax to file2.php. It is a Jquery based solution.
//file1.php
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
echo '<a href="javascript:void()" data-href="'.$row['courseID'].'"/>'.$row['courseID'].'</a><br>';
}
?>
<script>
$('a').click(function(){
var hrefData = $(this).attr('data-href');
if (typeof hrefData !== typeof undefined && hrefData !== false) {
alert(hrefData);
//or You can post the data
$.post( "file2.php", { courseid:hrefData} );
}
});
</script>
You can retrieve the result on file2.php
//file2.php
<?php
if(isset($_POST['courseid'])){
$newCourse = $_POST['courseid'];
}
?>
I was able to find a way to get it done? It seems pretty straightforward. This is what I came up with.
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
echo "<form name='course".$row['courseID']."' action='index.php' method='GET'/>";
echo "<a href='javascript: document.course".$row['courseID'].".submit();'/>".$row['courseID']."</a>";
echo "<input type='hidden' name='courseID' value='".$row['courseID']."'/><br>";
echo "</form>";
}
?>

Paginating mysql data using PHP

I borrow this code from this video: https://www.youtube.com/watch?v=takddjxhWT0
But when I run this code manually, the data that I get into the database doesn't change when I click the other page number. What do you think is the best code in order to run code this manually?
Any comment will help, thanks.
<html>
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("steer");
$page=(isset($_GET["page"]));
if($page=="" || $page=="1")
{
$page1=0;
}
else
{
$page1=($page*12)-5;
}
$res=mysql_query("select * from studtut LIMIT $page1,5");
while($row=mysql_fetch_array($res))
{
echo $row["id"]." ".$row["name"];
echo "<br>";
}
$res1=mysql_query("select * from studtut");
$cou=mysql_num_rows($res1);
$a=$cou/5;
$a=ceil($a);
echo "<br>";
echo "<br>";
for($b=1;$b<=$a;$b++){
?><?php echo $b; " " ?> <?php
}
?>
</body>
</html>
You need to set the page variable. This:
<a href="paging.php?=<?php echo $b; ?>"
Must be changed to this:
<a href="paging.php?page=<?php echo $b; ?>"
Also when you get the variable, you must assign it's value. And not the value, returned by isset function:
$page= isset($_GET["page"]) ? $_GET["page"] : 1;
Use <a href="paging.php?page=<?php echo $b; ?>" .Why ?
Because you access $_GET["page"] as Query string in PHP file . So it should be set in Link so that it doesnt become Blank in PHP file.
In your case $page is always Blank as its not defined . Turn error_reporting(E_ALL) always in Development mode to see errors,warnings,notices.

undefined ID in javascript when ID is passed from PHP variable

I've done some searches and I've come up with no clear answer. I'm not a javascript person at all and am pretty clueless. PHP I understand however, and to me this should work. I should also note, that this script used to use document.all for it's javascript, which I've tried to update to getElementById() when possible (since document.all was throwing an error in firebug).
Now for the most part, the page displays fine, albeit without the javascript changes that are supposed to happen.
I must also apologize for the archaic nature of the code, I inherited this code when I took over as internet guy for our gaming club. This code is for the purchase of fictional items using fictional credits.
When I click an item to "buy" it (or maybe not whichever) The background of that row is supposed to turn green, and the credits are supposed to be subtracted from my total account (or reverse if I uncheck the box). Clicking the submit button adds this stuff I clicked to another sheet, and subtracts the actual amount from my account.
Currently I get a "tr615 is undefined" error This is the PHP generated code for the element as shown below.
If someone can help me figure this out it would fantastic. I just can't seem to find an answer after a few days of searching google and here.
PHP Snippet of relevent code: (we use custom functions on our site ie: entry)
For instance say $id=615
<?php
while (list ($id, $name, $class, $desc, $range, $damage, $cost,$hide) = entry ($items) )
{
if ($hide =='0')
{
$JavaScriptArrayParms .= '"' . $id . '",';
$list .= $id . ',';
?>
<tr id="tr<?php echo $id; ?>"> //Thus tr615 for this example
<td>
<input type="checkbox" name="chk<?php echo $id; ?>" onclick="updateStoreTable(this.form, this, <?php echo $id; ?>)" />
<input type="hidden" name="cost<?php echo $id; ?>" value="<?php echo $cost; ?>" />
</td>
<td><?php echo $name; ?></td>
<?php if (! in_array($catid, $noclass)){ echo "<td>$class</td>";}?>
<td><?php echo $desc; ?></td>
<?php if (! in_array($catid, $norange)){ echo "<td>$range</td>";}?>
<td><?php echo $damage; ?></td>
<td><?php echo $cost; ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="hidden" name="list" value="<?php echo $list; ?>" />
<input type="button" value="Purchase!" onclick='validatePurchase(this)' />
<input type="reset">
</form>
Relevant JS: (which used to be document.all.store... or just document.all.. in some cases. I hope I fixed it the right way)
<script language="javascript">
var startmoney = <?php echo $currMoney; ?>;
function canAfford(t,id)
{
if(t.checked) return;// don't touch if checked for buying.
//alert("canAfford("+t+","+id+");");
//t.disabled = false;
eval("document.store.getElementByID(foo).disabled = false;");
eval("document.store.getElementByID(foo).checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
}
function cantAfford(t,id)
{
//alert("cantAfford("+t.disabled+","+id+")-- "+t+";");
//alert("before disable");
//t.disabled = true;
eval("document.store.getElementByID(chk"+id+").disabled = "+true+";");
//alert("After disable");
eval("document.store.getElementByID(chk"+id+").checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#555555';");
}
function getCost(id)
{
return eval("document.store.getElementByID(cost"+id+").value");
}
function buying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = 'green';");
document.store.credits.value -= getCost(id);
}
function notbuying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
var creds = new Number(document.store.credits.value);
var cost = new Number(getCost(id));
document.store.credits.value = (creds + cost);
}
function updateStoreTable(f,t,id)
{
var ids = new Array(<?php echo $JavaScriptArrayParms; ?>);
if(t.checked)
buying(t,id);
else
notbuying(t,id);
for(i = 0; i<ids.length; i++)
{
cost = new Number(getCost(ids[i]));
creds = new Number(f.credits.value);
//alert("COST: " +(cost)+"\nCREDITS: "+creds+"\nID: "+ids[i]);
// alert("'"+ (cost) + "' > '" + (creds) +"'\n"+(eval(cost > creds)));
// alert("f.chk"+ids[i]+".checked");
if(eval("f.chk"+ids[i]+".checked")) { continue; } //ignore already carted items
if(eval(cost > creds))
cantAfford(eval("f.chk"+id),ids[i]);
else
canAfford(eval("f.chk"+id),ids[i]);
}
}
1st issue:
it has to be getElementById()
(a lower-case d at the end)
2nd:
When using eval, the code will be evaluated as:
document.getElementById(tr615).style.background = '#000000';
..what will force the error, because the tr615 is not enclosed by quotes, so javascript expects a variable tr615.
the line must look like this:
eval("document.getElementById('tr"+id+"').style.background = '#000000';");
But: Why do you use eval here, this can be done without eval:
document.getElementById('tr'+id).style.background = '#000000';

Categories