Calling javascript Function from HTML with multiple parameters - javascript

I'm trying to call a javascript function called confirmRemove(title, id) to remove an element from a table. This function should be called when the user clicks on a link that looks like an "X". I attached my code below to show how I went about doing this, but I'm seeming to be having some errors and I'm not sure why. Most of the elements are able to be removed, but for a few when I click the link to call the function, nothing happens. Is there a better way of doing this? Not sure why this would happen.
<td><?php echo '<a onclick="confirmRemove(\'' . $title . '\',\'' . $id . '\')"
href="javascript:void(0)">X</a>';?></td>

You can try this code
<td> <a onclick="confirmRemove('<?php echo $title; ?>','<?php echo $id; ?>')"
href="javascript:void(0)">X</a></td>

You asked if there is a better way of doing this - I would suggest that there is and that it is to use an externally registered event handler bound to the specific HTML elements in question - notably a hyperlink in this example.
If you assign relevant attributes to the hyperlink ( dataset attributes are very useful for this sort of task ) you can process them within your event listener very easily. There is not need for complicated escaping for quotes by adopting this approach and best of all you can separate HTML from Javascript - the event handlers can be in another file
<td>
<a class='removal' href='javascript:void(0)' data-title="<?php echo $title;>" data-id="<?php echo $id;?>">X</a>
</td>
<script>
Array.from( document.querySelectorAll('a.removal') ).forEach( a=>{
a.addEventListener('click',function(e){
confirmRemove( this.dataset.title, this.dataset.id )
});
});
</script>

Related

Check a button has been clicked in JS and then do something in PHP

I'm working in PHP and I have this button, than when clicked, should print something.
I've (unsuccessfully) tried the following:
<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>';
?>
<script>
if(document.getElementById('enviarRecibos').clicked == true){
<?php
echo $listaDatos;
?>
}​;​
</script>
What am I doing wrong?
Note: $listaDatos is a variable that's already in the page with some content in JSON format.
I'm not sure i've well understand what you exactly want, but anyway your javascript script need improvement :
<?php
echo '<button type="submit" id="enviarRecibos" class="btn btn-primary float-end">Imprimir Lista</button>';
?>
<script>
document.getElementById('enviarRecibos').addEventListener('click', function (){
document.getElementById('enviarRecibos').insertAdjacentHTML('afterend', '<?php echo $listaDatos;?>') ;
}) ;
</script>
First the best way to track click on an element in javascript is with addEventListener.
Next, you want load content, ok, but you need to define the position / DOM element where the content need to be loaded. You can use "insertAdjacentHTML", an usefull function putting HTML content next to an existing element (here your button).
Take care "<?php echo $listaDatos;?>" doesn't contain a quote ' and return a valid HTML string.
AS #brombeer just told you, PHP is a server side language while Javascript is client side. PHP can only help you prepare the raw file code.

including html tag in a php code, specifically dealing with href function inside a php block

enter the html code once a condition is satisfied but then i aim to use php values and html tags together.
tried tag etc and got most of the part in running just unable to deal with href beacuse it is referencing to some values.
not sure where to use "" or ``.
<?php.....
echo `Yes`;
?>
"yes" should work as a hyperlink but at the moment the php values are not processed that`s why no result.
You are using wrong sequence of quote
<?php
...
?>
<?php
echo '<a href="limitdatabase.php?Dropdown=' .
$_GET['Dropdown'].
';&search='.
$search_name .
';&wise='.
$_GET['wise'].
';">Yes</a>';
?>
and you should use single quote and not backtics for string
You are using incorrect concatenation. Whenever you want to add any PHP variable then you need to close the braces and need to start after PHP variable as below:
<?php
echo 'Yes';
?>
Also you should wrap Dropdown and wise in braces as it will not work directly in get as you have used. Hope it helps you!
You can use combination of html with php inside:
<a href="limitdatabase.php?Dropdown=<?PHP echo $_GET[Dropdown] . "&search="
. $search_name . "&wise=" . $_GET[wise]; ?>">Yes</a>
Also, you can input whole link in string:
<?php
$mylink = "limitdatabase.php?Dropdown=" . $_GET[Dropdown] . "&search=" . $search_name . "&wise=" . $_GET[wise];
?>
YES

How to create function x times

I'm learning to code and i've come across a probably quite easy problem to solve.
I make a request from the database, that returns a number of users. For each user i create a few input fields like name, email etc.
Now what i want to do is use the same php variable (that contains the number of users), to create or repeat a function x times.
This is what i've tried so far.
var j = 0;
while (j <= i) { //i is the variable passed from php, containing the number of useres
j++;
$('#btnEdit'+j).click(function() {
$("#prename"+j).removeAttr('disabled');
$("#surname"+j).removeAttr('disabled');
$("#function"+j).removeAttr('disabled');
$("#prefix"+j).removeAttr('disabled');
$("#phone_number"+j).removeAttr('disabled');
$("#email"+j).removeAttr('disabled');
});
}
The HTML looks something like this:
Input
<label>Prename</label>
<input name="prename" id="prename<?php echo $i; ?>" value="<?php echo $row['db_prename_value']; ?>" maxlength="100" type="text" placeholder="Prename" disabled="disabled" />
Button
<input type="button" id="btnEdit<?php echo $i; ?>"
name="button<?php echo $i; ?>" value="Edit"></input>
To give a short explanation:
If the database returns 2 users, all the above fields are created for 2 users in php. User 1 will have prename1, surname1 etc. while user 2 will have prename2, surname2 and so on.
I won't know how many users get returned by the database so i can't just manually create the above snippet a set amount of times.
To clarify, i've already passed the variable from php to javascript (variable i). The question is how to repeat the javascript function x times, as the snippet i've posted is not working.
As far as my understanding goes, what my code does is iterate through the while loop x amount of times, but stops at this line, since the button is not being clicked.
$('#btnEdit'+j).click(function() {
Maybe i'm just confused about how to do what i'm trying to do.
Let's make an example. If the variable i is 2, i want the loop to create 2 functions, the first function has to be executed when the button with the id btnEdit1 is being clicked, the second function needs to execute when a button with the id btnEdit2 is being clicked etc.
Thanks
Instead of creating multiple function I would recommend you to create single function.
Use custom data-* attribute to persist php variable <?php echo $i; ?> with edit button which can later be fetched using .data(key).
To attach event handler Class Selector (“.class”) to target the elements and using Event Delegation create a single method.
<input type="button" class="btnEdit" data-id="<?php echo $i; ?>" name="button<?php echo $i; ?>" value="Edit"></input>
Script
$(document).on('click', '.btnEdit', function(){
var j = $(this).data('id');
$("#prename"+j).removeAttr('disabled');
$("#surname"+j).removeAttr('disabled');
$("#function"+j).removeAttr('disabled');
$("#prefix"+j).removeAttr('disabled');
$("#phone_number"+j).removeAttr('disabled');
$("#email"+j).removeAttr('disabled');
})
Why you need this?
You can directly write with an onClick event in input as well with the parameter of your id (which means your i value) .
Please take this answer as a key idea
<input type="button" id="btnEdit<?php echo $i; ?>"
name="button<?php echo $i; ?>" onClick="btnEdit(?php echo $i; ?)" value="Edit"></input>
function btnEdit(id)
{
$("#prename"+id).removeAttr('disabled');
$("#surname"+id).removeAttr('disabled');
$("#function"+id).removeAttr('disabled');
$("#prefix"+id).removeAttr('disabled');
$("#phone_number"+id).removeAttr('disabled');
$("#email"+id).removeAttr('disabled');
}
Note: I don't have experience in php . but this is common idea only

JS Not firing on click

I am trying to load the function call_ajax_add_to_quotelist via the button with the following code:
$cartlink .= '<a class="add_to_cart button alt" href="javascript:void(0);" onclick="call_ajax_add_to_quotelist(add_to_quotelist_ajax_url,'.$product->id.');" '.$style.'>'.$label.'</a>';
The code above is loading fine on the view source however when clicked it is showing dead with no console error I have loaded the js file in the function (It belongs to another plugin I am hacking a WP plugin with the same actions of another plugin)
Script Load:
$quotePluginJSUrl = site_url().'/wp-content/plugins/dvin-wcql/js/dvin_wcql.js';
?>
<script src="<?php echo $quotePluginJSUrl; ?>"></script>
<?php
I would a t first check, if call_ajax_add_to_quotelist is really a function in JavaScript Console, and if add_to_quotelist_ajax_url is a correct value.
Also, it is recommended to not use onclick. I recommend using jQuery event binder .on().
Expl.:
<?php
$cartlink .= "<a class='add_to_cart button' data-id='{$product->id}'
href='javascript:;' {$style}>{$label}</a>";
// ... more products
?>
// **one** <script> after all products
<script>
jQuery(window).on('click', '.add_to_cart.button', function() {
call_ajax_add_to_quotelist(add_to_quotelist_ajax_url, $(this).data('id');
}
</script>
Close the anchor
<a>...</a>
because you are adding the anchor dynamically, you need to use .addEventListener if you're using JS or Event Delegation if you're using jQuery
e.g.
$('.button').on('click',function(){
call_ajax_add_to_quotelist(add_to_quotelist_ajax_url,'.$product->id.');
});
Plus you haven't closed the anchor tag in your code which might cause you some problems:
$cartlink .= '<a class="add_to_cart button alt" href="javascript:void(0);" '.$style.'>'.$label.'</a>'

Assign html attribute to php variable using inline javascript

I'm trying to use the id attribute of a html link as a php variable. I am trying to do this using javascript as below:
<a data-toggle="modal" data-target="#profileModal" id="<?php echo $id; ?>" onclick="<?php $profile_id='<script> function(){ var pid = $(this).attr(\"id\")}; document.write(pid); }<\/script>';?>"><?php echo $first_name; ?></a>
I can document.write static text out of that function but there is no output when I add:
var id = $(this).attr(\"id\");
and try output that.
The links are on the first name in a table that will open a modal. How can I make this happen?
For inline event handlers, don't use <script> tags.
onclick="var pid = $(this).attr(\"id\")}; document.write(pid);"
Note document.write() overwrites the whole page content.
Unless you're just calling a function, inline handlers get ugly, as your code shows, so consider using unobtrusive JavaScript to assign the event handlers.
For example if you give the links a class:
$(function(){
$('.myClass').click(function(){
console.log( this.id );
});
});

Categories

Resources