My Function Call Doesn't Work Inside A echo [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is my php code:
<div class="box-body" id="chosen-tags">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++){
echo "<a id='abcd$cnt' style='float:left;'>abcd".$cnt." </a>";
}
?>
</div>
<div class="box-body" id="tags-toggle-content" style="display: none">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++){
$idd = "abcd".$cnt;
echo "<a id='abc$cnt' style='float:left' onclick='add_tagss($idd)'>abc".$cnt." </a>";
}
?>
</div>
Here is my Javascript Code:
<script type="text/javascript">
function toggle_visibility(id)
{
var f = document.getElementById(id)
if(f.style.display == 'block')
f.style.display = 'none';
else
f.style.display = 'block';
}
function add_tagss()
{
var f = document.getElementById("id");
f.style.display = 'none';
}
</script>
I really think that my error is on my function call inside a echo. Is there any rule on how to execute a function call inside a echo such as the proper usage of single and double quote.

You are messing up with single and double quotes.
Whenever you think you are messing up with javascript and PHP, break the string.
Its not mandatory to echo a string within double quotes at one go.
You can do several concatenations to achieve the same.
Best practice while writing javascript code in PHP is:
1) View source code to find out whether javascript code is properly coded. Of course, view source will not display AJAX generated code. Use Firefox's Inspect Element in this case.
2) Check if parameters of javascript functions are passed properly with single quotes.
3) In Firefox, check in console tab if PHP written javascript code is generating some errors.
4) In javascript function, use console.log() to check if proper variable is passed.
Some modifications:
Change
echo "<a id='abc$cnt' style='float:left' onclick='add_tagss($idd)'>abc".$cnt." </a>";
To:
echo "<a id='".$idd."' style='float:left'" . "onclick=add_tagss('".$idd."')>abc".$cnt." </a>";
And in function you are not receiving any parameter:
Change it to:
function add_tagss(id)
{
var f = document.getElementById(id);
f.style.display = 'none';
}

you are calling pa parameterised function but its defination doesn't have the parameter, look for this add_tagss('param');
call add_tagss(".$idd."); instead onclick='add_tagss($idd)' and definition should accept parameter. Hope this might help you.

Try this, in second for lop - where you add function call in anchor tag - try below script - it will successfully call function :
for($cnt=1;$cnt<=20;$cnt++)
{
$idd = "abcd".$cnt;
echo "<a href='#' id='abc$cnt' style='float:left;' onclick='add_tagss(\"".$idd."\")'>abc".$cnt." </a>";
}

<div class="box-body" id="chosen-tags">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++)
{
echo "<a id='abcd$cnt' style='float:left;'>abcd".$cnt." </a>";
}
?>
</div>
<hr />
<div class="box-body" id="tags-toggle-content" style="display: block">
<?php
$cnt = 1;
for($cnt=1;$cnt<=20;$cnt++)
{
$idd = "abcd".$cnt;
echo "<a id='abcd$cnt' style='float:left' onclick='add_tagss(\"$idd\")'>abc".$cnt." </a>";
}
?>
</div>
<script type="text/javascript">
function toggle_visibility(id)
{
var f = document.getElementById(id)
if(f.style.display == 'block')
f.style.display = 'none';
else
f.style.display = 'block';
}
function add_tagss(idd)
{
var f = document.getElementById(idd);
f.style.display = 'none';
}
</script>

Related

php ja javascript links and encoding

With scandinavian letters and when encoding them, I have a problem. With code below, javascript add some extra encoding to variable
<script>
function doit(params) {
var url = "/linkto/code.php" + params;
window.open(url,"Doit","width=750, height=600");
}
</script>
<?php
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
echo 'Do it!'; // link to page
?>
When changing code above to php, changed does not happened and problem go away.
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
// link to page
echo '<a href="/linkto/code.php"'.$param.'>Do it!</a>';
Hi all again,
I cannot make it work, no difference between utf-8 or iso-8859-1.
Result is something else, when using javascript-function or direct link.
You can try it here:
http://www.ajl.fi/tmp/test.php
Here is codes:
test.php:
<script type="text/javascript">
function doIt(params) {
var url = "doit.php" + params;
window.open(url,"doit");
}
</script>
<?php
$var1 = 'pähkinä';
$var1 = urlencode($var1);
echo sprintf("Do it - call",$var1)."<br>";
echo sprintf("Do it - link",$var1);
?>
and here is doit.php:
<?php
var_dump($_GET);
?>
In ist code, you have two issues in this code
1) Short tag will not work inside the <?php ?> here:
echo 'Do it!'; // link to page
2) You forgot to add quotes here:
window.open(url,"Doit",width=750, height=600"); //missing quote here
Modified Code:
<?php
$var1 = 'p%E4hkin%E4';
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
?>
Do it!
<script type="text/javascript">
function doit(params) {
var url = "/linkto/code.php" + params;
console.log(url);
window.open(url,"Doit","width=750, height=600");
}
</script>
I answer to myself - Solved.
IE, Edge and Chrome, all working ok on both cases. Firefox has a problem. When using
Do it!
result is not correct, but when using
Do it!
seems to work on all browsers

On click suggestions don't replace the good value in text box

Basically, I have a search box that suggests results from a database as user types. It looks like this :
Example
.
I use ajax in a file to make a live search as user types :
<input name="estab" id="estab" type="text" class="estab" />
<div id="result"></div>
<script>
$("#estab").on("input", function(){
$estab = $("#estab").val();
if ($estab.length > 0){
$('#result').show();
$.get("res.php", {"estab":$estab},function($data){
$("#result").html($data);
})
}
});
<script>
Then in another file (res.php) I have a sql request and I display results. I also have my 'onclick' function to replace suggestion in text box :
while($result=$data->fetch_assoc()){
$sortie[] = $result['school'];
}
$sortie2=array_unique($sortie);
echo '<ul>';
foreach($sortie2 as $value){
echo "<script>
function fill(){
document.getElementById('estab').value = '$value';
$('#result').hide();
}
</script>";
echo "<li onclick='fill()'><b>$value</b></li>";
}
echo '</ul>';
My problem is : when i click on any of the suggestion, it is always the last option that is replaced in the text box, in this case "University of Washington".
I have been trying to solve that problem for 2 days now and I can't find the solution.
Any help would be greatly appreciated. Thanks
UPDATE
Found the solution, if someone is interested, here's what I did in res.php:
while($result=$data->fetch_assoc()){
?>
<li onclick='fill("<?php echo $result['school']; ?>")'><?php echo $result['school'];?></li>
<?php
}
?>
</ul>
and in the first file :
<script>
function fill(val){
$('#estab').val(val);
$('#result').hide();
}
$("#estab").on("input", function(){
$estab = $("#estab").val();
if ($estab.length > 0){
$('#result').show();
$.get("res.php", {"estab":$estab},function($data){
$("#result").html($data);
})
}
});
</script>
echo "<script>
function fill(newValue){
document.getElementById('estab').value = '" + newValue + "'" + ;
" $('#result').hide();
}
</script>";
echo '<ul>';
foreach($sortie2 as $value){
echo "<li onclick='fill($value)'><b>$value</b></li>";
}
echo '</ul>';
I wouldn't use the onclick method here. I would use jQuery to assign the events to your list items. But if you must, in your onclick method, try passing this.value like so:
<li onclick="fill(this.value)"><b>$value</b></li>
Then your fill() method could be something like so:
function fill(val){
$('#estab').val(val);
$('#result').hide();
}
EDIT: You are mixing plain JavaScript and jQuery code. I replaced your plain JS line with the jQuery equivalent.
Also, if you are adding the fill() method in the same loop that adds the LIs, then you are adding multiple fill methods, which is incorrect. Just add it once in the same script tag like below.
<script>
function fill(val){
$('#estab').val(val);
$('#result').hide();
}
$("#estab").on("input", function(){
$estab = $("#estab").val();
if ($estab.length > 0){
$('#result').show();
$.get("res.php", {"estab":$estab},function($data){
$("#result").html($data);
})
}
});
<script>

How to run if statement from PHP to run JS function

I have a PHP Session variable which can be 0 or 1 and this JS function:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
I would like this function to be run AUTOMATICALLY as soon as the page is opened only if the PHP Session Variable is = 0.
How and where can I create my If statement?
One of the simpliest is just handle it like any normal code block. Add your condition in the if statement.
Basic idea:
<!-- head -->
<?php if($_SESSION['whatever'] === 0): ?>
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
toggle_visibility('body');
</script>
<?php endif; ?>
<!-- your HTML content, etc. -->
<!-- footer, etc. -->
If $_SESSION['whatever'] is not 0, after all is loaded, then you'll not see this JS code block in the page because remember PHP runs first.
Note: Don't forget to start the session.
Additional Note: Of course, another way would be to create an XMLHttpRequest. You'd need another PHP script that responds to this request. Just respond with a json_encoded response. This answer (vanilla) should give a better illustration.
You could let PHP generate the JS code, you'd then get something like this
<script>
<?php
session_start();
if($_SESSION["name"]=="value"){
echo"document.getElementById('id').style.display='none';";
}
?>
</script>
<?php
$execJs = "false";
session_start();
if (isset($_SESSION['variable']) && $_SESSION['variable'] === 0) {
$execJs = "true";
}
?>
<script>
var id = 'whatever';
var execJs = "<?php echo $execJs ?>";
if (execJs === 'true') {
toggle_visibility(id);
}
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
You could use the following technique :
<?php
if($_SESSION['shouldbezero'] === 0) {
echo '<script src="shouldbezero.js"></script>';
}
?>
The echo statement would run only if the value of $_SESSION['shouldbezero'] is equal to 0, and thus the <script> tag will only be added to your HTML code in that specific situation.
If you use this technique, you should also create a file named shouldbezero.js, which should contain all the JavaScript code you only want to run if the value of $_SESSION['shouldbezero'] is equal to 0.
Note :
If you only want to load CSS based on a certain value in your PHP code, could do the same thing with that CSS code.
For example, you could add echo <link rel="stylesheet" type="text/css" href="shouldbezero.css">'; right beneath the echo '<script src="shouldbezero.js"></script>';, as demonstrated in the code example below :
<?php
if($_SESSION['shouldbezero'] === 0) {
echo '<script src="shouldbezero.js"></script>';
echo '<link rel="stylesheet" type="text/css" href="shouldbezero.css">';
}
?>
If you do this, you should also create a file named shouldbezero.css, which should contain all the CSS code you only want to process if the value of $_SESSION['shouldbezero'] is equal to 0.

onclick function in php variable [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
How to add onClick event on <a> tag which contains php variables
$delete = "<a onclick='return confirmDelete('deleterecord.php?chkid=$sl&table=$getid&path=$validURL');'><img src='images/dustbin.png' width='43px' height='30px'></a>"; // link not pass
//script
<script>
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
window.location = delUrl;
}
}
</script>
1.
$link = "deleterecord.php?chkid=$sl&table=$getid&path=$validURL";
and use
return confirmDelete(\"<?=$link?>\")
2.
Escape single quotes by using black slash before single quote:
<img src=\'images/dustbin.png\' width=\'43px\' height=\'30px\'>
Use php's echo to return html/css/js stuff:
http://php.net/manual/de/function.echo.php
<?php
$delete = "
<a onclick='confirm_(\"deleterecord.php?chkid=$sl&table=$getid&path=$validURL'\")'; class='link'>
<img src='images/dustbin.png' width='43px' height='30px'>
</a>";
echo($delete);
?>
<script>
function confirm_(url){
console.log(url);
if (confirm("Are you sure you want to delete")){
window.location = url;
}
}
</script>
Like Rayon Dabre sayed, you have to escape string.
Maurize's casual/smart/lazy solution:
You should echo a link with a path like delete.php?action=delete&id=2
and on php side
if (isset($_GET["action"]) && $_GET["action"] == "delete"){ echo $_GET["id"]; }
Will looks like:
<?php
if (isset($_GET["action"]) && $_GET["action"] == "delete"){
echo $_GET["id"];
}
?>
Lazy Casual?
or
<?php
echo("
<a href='deleterecord.php?chkid=$sl&table=$getid&path=$validURL'>
<img src='images/dustbin.png' width='43px' height='30px'>
</a>
");
?>
Tested and works like mexican.
The masterpiece of deletion would be using AJAX + JS - Maurize

how to get next element by java script

I would like to get next element:
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextElementSibling.id);
}
</script>
<?php
$x = 1;
echo "<ol>";
while($x <= 5)
{
echo "<li id={$x}> item {$x} </li>";
$x++;
?>
<button onclick="editMediaInfo('<?php echo $x; ?>')">Click</button>
<?php
}
echo "</ol>";
?>
When i click it gives me an alert without nothing. I would like to get the id of the next element.
It appears you are using an incorrect Javascript function. Use nextSibling function. Replace nextElementSibling with nextSibling. I provided a sample below.
<script>
function editMediaInfo(mediaID){
var x = document.getElementById(mediaID);
alert(x.nextSibling.id);
}
</script>
Where I found and tried the solution was here. I would recommend using this site for help on Javascript in the future.
Simply Use :
document.getElementById(mediaID).nextElementSibling.nextElementSibling.id

Categories

Resources