Assign html attribute to php variable using inline javascript - 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 );
});
});

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.

Calling javascript Function from HTML with multiple parameters

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>

How to write jquery append $("#id").append() statement if element id is defined as a php function?

I am building a website and a webpage contains same elements with element id which is created by a php function so that element id will be unique.
I want to use a jquery append statement to add div element with id created by a php function.How to write jquery append statement?
HTML PART:
<div id="q2s<?php the_ID(); ?>">
<span class="t2"><input type="text" class="t2" id="t2s<?php the_ID(); ?>">
</span> <span id="star2s<?php the_ID(); ?>" class="rating2"></span>
<hr></div>
In html part <?php the_ID();?> is the php function used for getting unique id
JAVASCRIPT PART:
<script>
var getstarid="<?php the_ID();?>";//php function for getting unique id
$(document).ready(function() {
var q2 = $("#q2s"+getstarid);//This is the part i am asking
//about.How to write this statement?
$(q2).append('<div id="q2s<?php the_ID(); ?>"<span class="t2"><input
type="text" class="t2" id="t2s<?php the_ID(); ?>"></span> <span
id="star2s<?php the_ID(); ?>" class="rating2"></span><hr></div>');
});
</script>
in javascript part var getstarid="<?php the_ID();?>";is used for getting unique id.
How to write var q2 = $("#q2"+getstarid);in jquery so that element id can change and jquery append can work according to change in value of php function <?php the_ID();?>?
Thanking you in advance.
With something like this, I usually embed the code/id/whatever in a data attribute in an element on the page.
HTML:
<div id="q2s" data-id = "q2s<?php the_ID ?>">
Then I retrieve it in my javascript using the jquery "data" method:
JAVASCRIPT:
var getstarid=$("#q2s").data("id");
...
var q2 = $("#q2s"+getstarid);//This is the part i am asking
//about.How to write this statement?
$(q2).append('<div id='+getstarid+'><span class="t2"><input
type="text" class="t2" id="t2s"'+getstarid+'></span> <span
id="star2s'+getstarid+'>" class="rating2"></span><hr></div>');
});
This benefits you in two ways, potentially: 1 - It's cleaner. You shouldn't be putting PHP code mixed in with your javascript. 2 - It might save you some database access. I don't know if PHP hits the database every time it hits "". This way, it only calls that function once and then lets jQuery do the heavy lifting.

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>'

How to insert script tag and execute response via src?

I have a script tag which calls a remote JavaScript snippet through src, and writes it on the page, thus rendering a banner in the process.
I'm looking for a way to call the script, or insert the script via JavaScript. Right now it looks like this:
<div id="<?php print $banner_id; ?>" class="banner-responsive <?php print $breakpoints; ?>">
<script src="<?php print $url; ?>"></script>
</div>
This is the preferred method supplied by the banner vendor. I'm looking for a way to implement it more like this:
<div class="banner">
<div id="<?php print $banner_id; ?>">
<script type="text/javascript">
function banner_load(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = '<?php print $url; ?>';
var x = document.getElementById('<?php print $banner_id; ?>');
x.parentNode.appendChild(s);
}
if (window.attachEvent)
window.attachEvent('onload', banner_load);
else
window.addEventListener('load', banner_load, false);
</script>
</div>
</div>
This sort of works. It inserts the script tag, and calls the remote URL, but it does not execute the JS snippet received like it does in example 1, and because of that the banners do not appear. Is there a way for me to execute the script src at will?
What the src response could look like:
document.write("<a target='_blank' href='http://domain/?options'><img src='http://domain/whateever-930x180px.jpg' alt='Click here' /></a>");
I want to do this, so I can switch banners at specific moments, based on pre-defined break points. How would you go about this? Any thoughts?
Update: I don't have any control over the output. It's an external banner supplier. I take it that this is impossible?
You cannot dynamically load javascript that uses document.write() and get the result you want.
Dynamically loaded javascript runs AFTER the DOM has been loaded. When document.write() is used after the DOM has been loaded, it clears the entire document and starts a new empty document. As such, it will not do what you want.
If you want to dynamically load the Javascript, then you will need to use DOM manipulations (e.g. document.createElement() and elem.appendChild()) to insert your banner into the existing DOM and not use document.write(). document.write() is only useful for this type of problem when it is done inline with sequentially loaded javascript either inline or via <script> tags in the markup (not via dynamically loaded javascript).
There are several ways you can do this:
Instead of returning a document.write, you could return a HTML snippet and then use appendChild to write your banners. Generally using document.write is a bad javascript practice.
If you must use document.write, then rather than inserting the script tags url insert the response from the url directly into your banner_load function.

Categories

Resources