button of javascript is displaying but function is not working - javascript

I am trying to call a function in javascript by clicking a button but the problem is that when I used to click the button then it do nothing i.e it doesn't call the function...
The following is the code
<?php
function view_cat1()
{
$i=1;
include("inc/db.php");
$fetch_data=$con->prepare("select * from main_cat order by cat_name");
$fetch_data->setFetchMode(PDO::FETCH_ASSOC);
$fetch_data->execute();
while($row=$fetch_data->fetch())
{
echo"<tr><td>".$i++."</td>
<td>".$row['cat_id']."</td>
<td>".$row['cat_name']."</td>
<td><a href='index.php?edit_cat=".$row['cat_id']."'>Edit</td>
<td><input type='button' onclick='delete_category(<?php echo
".$row['cat_id'].")' name='delete' value='Delete'></td>
</tr> ";
}
}
?>
<script language="javascript'">;
function delete_category(delname)
{
if(confirm("are you sure"))
{
window.location.href='delete_cat.php?del_name='+delname+'';
return true;
}
</script>
<?php
The above code don't use to show the confirmation message .

Modify the JavaScript as below, it may works:
<script>
function delete_category(delname)
{
if(confirm("are you sure"))
{
window.location.href='delete_cat.php?del_name='+delname+'';
return true;
}
}
</script>

The language attribute has been deprecated for a long time, and should not be used. Also, you missed the closing brace } of the delete_category function.
<script>
function delete_category(delname) {
if (confirm("are you sure")) {
window.location.href = 'delete_cat.php?del_name=' + delname + '';
return true;
}
}
</script>
You can use the attribute type="text/javascript" if you are not using HTML5

To simplify your code and make fewer mistakes, you could use a single echo statement in your while loop. If you render HTML with JavaScript functions linked with events, don't forget to add quotation marks around the arguments of the function. In your case, the function delete_category takes in as argument $row['cat_id']. To do that escape the double quotes with a blackslash : \"
Here is an example:
<?php
$var = "hello";
echo "<input type='button' onclick='delete_category(\"".$var."\")' name='delete' value='Delete'>";

Related

Call javascript function (which accept parameters) from php loop and process the parameters in javascript function

I want to call a javascript function myfunction() from php code. the code is as follows:
<script>
function myfunction() {
var r = confirm("Are you sure ? ");
if (r == true) {
//delete file from database with id b_id
}
<?php header("Refresh:0"); ?>
}
</script>
I want to call the js function from this php code.
<?php
while(//fetched database elements one by one)
{
//$b_id fetched from database.
echo "<button class='w3-display-topright pe-7s-close-circle w3-xxlarge w3-button' onclick="myfunction($b_id);"></button>
}
?>
Write another PHP script that deletes an entry by ID and call it from your web page. I.e.,
<?
while (...) {
echo "<button onclick='deleteEntry($id)'></button>"
}
?>
With your JS being something like this:
function deleteEntry(id) {
if (confirm('Are you sure?')) {
fetch('myserver/delete_entry.php?id=' + id);
}
}
You have to write delete_entry.php, of course.

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>

PHP echo within a Javascript file

So the problem is as follows:
I want to dynamically echo a javascript thing with PHP. This echo needs to be (or work with) another javascript file where the echo'd value is used to call a function when the ID is clicked.
However when the page is loaded and the document.getElementById things are added (and they are correct) when the element is clicked, the console tells me that fplaying is undefined
PHP File
<?php
mysql_connect ("localhost", "root", "") or die ("We couldn't connect!");
mysql_select_db ("dr");
mysql_query ("SELECT * FROM songs");
$result = mysql_query ("SELECT * FROM songs");
while ($row=mysql_fetch_array($result)) {
$source = $row ['audiosource'];
echo "
document.getElementById('$source').onclick = fplaying
";
}
?>
JS File
$(function() {
console.log( "ready!" );
function fplaying () {
alert ("test");
}
});
I am not sure if this can be done with php and this is probably not the answer you are looking for.But long comments are not recommended so I just posted as an answer.
It is possible to do, I have done when I was new to Web Developments (With ASP.Net), but still this indicates an improper architecture. JavaScript, that you are using, is a client side script and thus should be accompanied with proper AJAX structure to do such thing. Server should only be responsible to send proper response based on request, not dictate how a page should behave on client side.
Some thing like -
var play = function(){
...//code to play
};
$.ajax({
url: ..//url to php page
type: ...
...,
success: function(data){
...//data responded by php page
play();
},
error: function(){
}
});
I used syntax for jQuery. There are other libraries too.
This is very simple. Try this.
echo " <script> ";
echo "document.getElementById('$source').onclick = fplaying ";
echo "</script>";
I don't think
document.getElementById('$source').onclick = fplaying
will find the function as fplaying is undefined.
Try:
var fplaying = function() {
alert ("test");
}
instead of
function fplaying () {
alert ("test");
}
As in the JS you are printing through PHP only sets the onclick event for an element with that ID which exists somewhere else on the page I think. So, much better way of doing this would be define a class in that clickable item
<button id='<?php echo $source; ?>' class='click-me'>Click Me</button>
Then in JS use this:
$('.click-me').on('click',function(){
alert($(this).attr('id'));
});
Let's suppose you have a collection, coming from a db query: $collection and consists of associative arrays, with a unique id
Now, you are obviously going to display these objects and ask for a user to do something with them, your fplay function. What you must do, is echo whichever parts of the items you need and somehow pass in the html the item id.
So, the php part which will construct your html would be something like:
echo "<ul>";
$id = $item['id'];
foreach ($collection as $item){
echo '<li><a onclick="return fplaying(' + $id + ')" href="#" class="btn"></li>';
}
echo "</ul>";
Then, your js function would use the id as a parameter and do whatever you need:
function fplaying (id) {
alert ("your id is " + id);
}
$source = $row ['audiosource'];
echo '<div id="'.$source['id'].'" class="sourceDiv">'.$source['name'].'</div>';
then go to your js file and add this --you don't have to do that in php
$(document).ready(function(){
$('.sourceDiv').click(function(){alert($(this).attr('id'))});
});
Obviously your declaration of fplaying() is delayed and in addition its locally defined, only.
$(function() {
console.log( "ready!" );
function fplaying () {
alert ("test");
}
});
In that code fplaying is dropped as soon as the outer function has finished. Try binding that fplaying to your window instead.
$(function() {
console.log( "ready!" );
window.fplaying = function() {
alert ("test");
};
});
To illustrate this additionally:
function a() {
function fplaying() {
alert("Hi");
}
fplaying();
}
a();
will display alert box.
function a() {
function fplaying() {
alert("Hi");
}
}
a();
fplaying();
won't show alert box for fplaying() is visible in scope of a(), only, and thus it's undefined as in your case.
function a() {
window.fplaying = function() {
alert("Hi");
};
}
a();
fplaying();
will show alert box for now fplaying() is declared as method of object window more or less serving as global scope, too.
For it's delayed using $(function() { ... }); make sure invoking code as rendered by PHP isn't running before document has loaded. But that doesn't seem to be an issue according to your spare information on context.
Okay, from what I understand of your problem:
Your php creates a html file that has an element with id="the value of $source" and you want it to play a sound on click.
If you want to create a piece of javascript like you did, you could try:
echo ""
while ($row=mysql_fetch_array($result)) {
$source = $row ['audiosource'];
echo "
document.getElementById('$source').onclick = fplaying()
";
}
echo "</script>"
That should make the browser recognize the script as javascript and execute it. Make sure this is printed to the html after the part of the page with the elements you're referring to is printed to the html. Otherwise the script might run before the relevant part of the page is loaded in the browser.

Javascript autoclick link to a function

I'm trying to auto click link which action is a javascript function. But it won't work..
if($submit)
{
echo '<body onload="setTimeout("autoClick();",1000);">';
echo "<a id='linkToClick' onclick='return confirmDialog($id);'>clickme</a>";
echo '</body>';
}
else
echo 'not set';
?>
<script type="text/javascript">
function autoClick(){
var myLink = document.getElementById('linkToClick');
myLink.click();
}
function confirmDialog (id, callback) {
confirmDialogCallback = callback;
$("#idConfirmDialog").modal ("show");
}
</script>
One problem here is that you're using double quotes as both your attribute delimeter and around the parameter you are passing to setTimeout (note how the syntax highlighting gets all messed up here):
<body onload="setTimeout("autoClick();",1000);">
should be:
<body onload="setTimeout('autoClick();',1000);">
And in your PHP code, this would equate to:
echo '<body onload="setTimeout(\'autoClick();\',1000);">';
Also, while this is not strictly necessary, passing a string value to setTimeout is not a recommended practice and should be avoided. You should pass the function itself instead:
<body onload="setTimeout(autoClick, 1000);">
And if you do that, you have one fewer pair of quotes to worry about.

Onload popup javascript

I am trying to make a pop up load as soon as the page loads. I've used this already on the site and it works. However now nothing pops up.
<script>
window.onload = function (<?php echo $name . "," . $club ;?>){
var txt = name + " has been deleted from this club";
$.prompt(txt,{
buttons:{Delete:true},
close: function(e,v,m,f){
if(v){
var uid = f.userid;
window.location = "manageclub.php?id=" + club;
}
else{}
}
});
}
</script>
First of all, I should say that this approach doesn't feel quite right; you're building a new page just so that you can show a JavaScript prompt which will then redirect to another page ... I'm sure that could be done in a better way.
That said, here's the answer. You can't pass arguments inside the function definition like that; define those variables inside the function body instead;
Secondly, you're not escaping club properly for use in a URL.
window.onload = function ()
{
var name = <?php echo json_encode($name) ?>,
club = <?php echo json_encode($club) ?>,
txt = name + " has been deleted from this club";
$.prompt(txt, {
buttons:{Delete:true},
close: function(e,v,m,f) {
if (v) {
var uid = f.userid;
window.location = "manageclub.php?id=" + encodeURIComponent(club);
}
}
});
}
I'm using encodeURIComponent() to escape club properly inside JavaScript at the redirect code, and json_encode() to escape the PHP variables to be used in JavaScript.

Categories

Resources