Getting DOM elements after div updated from load php file - javascript

I have an html file with a div that gets updated by a php file. The php file puts a single book's title and author into the div, that works.
I am trying to use getElementById to get the book's title getElementById('btitle') and author name getElementById('authr') when I click a button because I need to use that information. I am not getting the value of the btitle or authr ids. If I assign the whole div to a variable I get all of the div but I want them separate and the getElementByID() is not working.
Any help is appreciated.
a.html
'<div id='books'> </div>
addbooks.php
echo <stitle id='btitle'>Foundation</stitle>
echo <author id='authr'>Asimov</author>

Try putting your javascript just before the closing </body> tag. Otherwise, if your javascript is in the head, it is looking for an element that has yet to be rendered to the DOM.
I tested the following and it returns the elements as you would expect.
<?php
echo "<stitle id='btitle'>Foundation</stitle>";
echo "<author id='authr'>Asimov</author>";
?>
<script type="text/javascript">
var title = document.getElementById('btitle').textContent,
author = document.getElementById('authr').textContent;
alert(title + " by: " + author);
</script>

Related

How to display the value of a php variable by clicking on a hyperlink

I want to display the balance of the user when he clicks on the hyperlink. the balance of the user is stored in a php variable. I am hoping that this can be done using javascript but I dont have much experience in javascript.
Below is my code:
$userbalance = $xyz[2];
echo "Your balance stands at ".$xyz[2];
This thing is working, but I want to display $userbalance by clicking on a link
I don't know what to put in the anchor tag.
Is it possible that by clicking on the hyperlink the value of the php varibale gets displayed?
Can I pass a function to href? or can I use onclick in some way?
Try this:
<a href="somepage.php?balance=<?php $balance = $xyz[2]; echo "Your balance stands at ". $balance; ?>" >Click</a>
By above method you can display balance in url at any pages. Then if you need to use that balance there just get that value with super global variable $_GET['balance'];
In the most simplest form, this can be done via storing the value in the "data-" attribute that HTML supports and then using Javascript to alert the value upon user's click.
<p>
Click to see your account
balance.
</p>
The PHP part of this would be just to echo the correct balance into the correct place in the HTML code above.
balance.
Example of the final HTML: https://jsfiddle.net/oh8jnmg2/1/
Niltish has given the right hint. But I wouldn't recommend putting a output string into a link, which gets displayed in the url. Since HTML is rendered through PHP, you can simply attach your value to the link by typing:
<a href="yourprintsite.php?balance=$userbalance>Click here to see your balance</a>
And then on yourprintsite.php, you just type:
if (!empty($_GET['balance')) {
echo "Your balance stands at " . $_GET['balance'];
}
And you're done.
This is a solution if you don't want to actually use two pages but still show new content and hide everything else:
$userbalance = $xyz[2];
echo `Your balance stands at <a href='javascript:{document.documentElement.innerHTML = ""; document.write(` . $xyz[2] . `);}'>see variable</a>`;
If you want just to display a new value below, then use:
$userbalance = $xyz[2];
echo `Your balance stands at <div id="myDiv"><a href='javascript:{document.getElementById("myDiv").innerHTML = ` . $xyz[2] . `;}'>see variable</a></div>`;
Do you can write next code, function getAttribute must you help
<script type="text/javascript">
function clickHanler(d){
alert(d.getAttribute("data-userbalance"));
}
</script>
<a
data-userbalance="21"
href="#"
onclick="clickHanler(this);">
Click to do something
</a>
First, let's start with the HTML, you need to create a <a></a> that routes to no where :
Click to see Balance
Then, in the Javascript part :
We will assign a method to handle the click on our link.
we need to use an Ajax call to get the balance from the balance.php page :
$("#linktobalance").on("click", function(){
$.post( "balance.php", function(balance) {
//In this part, the balance is the value returned from th PHP, you can do whatever with it, I'll alert it
alert( "The user balance is "+balance );
});
});
Note : we used jQuery, you can add it to your project by doing this :
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$("#showbalance").click(function(){
$("#balance").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
Show Balance
<div id="balance" style="display: none;">
Balance = 1000
</div>

Targeting dynamic id's within a javascript file

In a php file I have tags with dynamic id's.
Example:
<ul id="<?php echo 'ul_'.$xx; ?>">
<li id="test_li">...</li>
</ul>
In a separate JavaScript file I am wanting to use the load function and target that div.
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
My question is, how could I load that php within a JavaScript file?
Notes:- The reason I have it set up this way is due to looping multiple ul's. I just want my ajax file to refresh the li's within the specific ul I am inside of.
Edit: If I use classes instead of Id's it adds my newly inserted rows into all of the ul's with the same class. If I use a plain Id it only works on the first ul. Further explaining why I need to target the way I am.
Unable to find a solution using the path I was on, I looked for alternate methods. Worked out I could add the event in the php file on the submit form button click.
The reason I wasn't using this method at first was because the code was running before it submitted to the DB and therefore was always behind in relation to the new data being submitted.
To my surprise I fixed this by just duplicating the line of code.
<script>
$("<?php echo '#enter_submit_button'.$linkid ?>").click(function(){
/*1*/
$('#<?php echo 'ul__'.$linkid; ?>').load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
$("<?php echo '#insert_new'.$linkid; ?>").fadeOut();
/*2 with delay*/
$('#<?php echo 'ul__'.$linkid; ?>').delay( 800 ).load('../includes/pursuit.inc.php <?php echo '#li__'.$linkid; ?>');
});
</script>
I honestly couldn't say exactly why this works but the logic behind trying the method came from hoping that the double load would pick up the latest submission.
The simplest answer would be to put your JavaScript code into the PHP file inside
<script></script> tags, i.e, just before closing your <body> tag, do this:
<script type="text/javascript">
$('<?php echo 'ul_'.$xx; ?>').load('../includes/myphpfile.inc.php #test_li');
</script>
But if you must use an external js file, then you could do this:
Create a (.php) file and write:
<?php
header("Content-type: application/javascript");
?>
// your js code with php inside (as you would do in HTML)
var othervar='<?php echo $phpVar; ?>';
//<?php //some php ;?>
Then, in your main (html/php) file, put in:
<script src='myjs.php' type='application/javascript'></script>
Hope that solves it.

Append <script> into <div> using jquery

I'm trying to append a <script> tag into my <div>. Whenever I try to do this, the script just doesn't loads. But it works if I hard coded it under the tag.
But if I try to append an <img> tag, it works!
Here's a partial code to give you some ideas.
$(document).ready(function() {
var tag = '<script src="xxx.js"></script>'; // file to grab images
var tag2 = '<img src="some image link"></img>';
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
On HTML
<div id="test"></div> <!-- Not Working! -->
<div id="test2"></div> <!-- This Works! -->
<div id="test"><script src="xxx.js file to grab images"></script></div> <!-- This Works too! -->
Edit with more info below:
I've actually looked for solutions over the net and most of the answer are almost the same as the ones given here. In my case, it is slightly different from the others. That's because the tag variable is actually a must from database.
<?
$result = mysql_query("SELECT code FROM users_loc WHERE method='script'") or die(mysql_error());
$row = mysql_fetch_array($result);
?>
and on javascript side:
$(document).ready(function() {
var tag = <? echo $row['code'] ?>;
var tag2 = <? echo $row2['code'] ?>;
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
On my site, users will input their external image source into my database, and I will grab the source and display it on my site. But the problem arise when a user put in a <script> tag which works if it were hard coded into the <div>
I kept having this error message on my console "A call to document.write() from an asynchronously-loaded external script was ignored."
I hope this answers the confusions. Thanks.
Edit: I think this is the problem with append: Does Jquery append() behave asynchronously?
It all because about the parsing problem. The problem showing up after found </script> this code. It's assume we want to close the script tag but we won't. In order to avoid that, put \ before / like so to escape special character :
$(document).ready(function() {
var tag = '<script src="xxx.js"><\/script>'; // file to grab images
var tag2 = '<img src="some image link"></img>';
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
DEMO
Try inspect the element in chrome to see the code.
Try it:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'xxx.js';
$('#test').append(script);
If it matters where in the source order the script tag is injected, Mario Araque's solution is for you. If it does not matter, R3tep's solution does the job nicely.

PHP: Reading DOM info of own HTML page

So, let's say I have only one file on my server called index.php :
<!DOCTYPE html>
<html>
<body style="background-color: orange;">
<!-- On/Off button's picture -->
<?php
echo ("<img id='button' src='data/button.jpg' alt='off'/>");
?>
</body>
</html>
Now, let's say I attach a JavaScript that changes the buttons ALT to ON when I click the button at some point.
How can I read the DOM elements on this page using PHP?
So far, I've found this code:
$dom = new DOMDocument;
$dom->loadHTML($html);
$main = $dom->getElementById('alt');
but I can't figure out how I would fit that in my code above, what page should I call loadHTML() for?
How do I make PHP read DOM elements it generated using echo?
First of all, your button has id button, so searching for the id alt would return no results.
Second: The piece of php you found reads a page $html (probably file_get_contents('some_url'), puts it in the variable dom and parses it, searching for the id alt. In your case it would read your own page, breaking it down in pieces looking for that button.
Thats of no use if you can read the status with javascript on your own page. You can then pass it to php trough an ajax-call or by adding it to the url like mypage.php?button=off
$main = $dom->getElementById('button');

WP get page content

I'm trying to retrieve page content in a javascript function. When I echo the test variable $htmlblock, the javascript lightbox works perfectly. But when I echo $contactinfo, it opens the page in a new tab.
<?php
// retireve content from "contact" page
$contactpageid=85;
$contactpage = get_page($contactpageid);
$contactinfo = apply_filters('the_content', $contactpage->post_content);
//test variable
$htmlblock = '<strong>Contact Information</strong><br/><table><tr><td id="name"><strong>NAME</strong></td><td id="phone">888-8888</td><td id="email">name#email.com</td></tr></table>';
?>
<script language="javascript" type="text/javascript">
function openLightbox() {
lightbox('<?php echo $contactinfo; ?>');
}
</script>
$contactinfo possibly contains HTML tags, where as $htmlblock is just a simple string.
I'm not sure you can do this with that Lightbox. You may want to check with the Lightbox docs (of the version you are using) on how to insert HTML content.
Or, you could try stripping out the HTML.
$contactinfo = apply_filters('the_content', strip_tags($contactpage->post_content));
http://php.net/manual/en/function.strip-tags.php

Categories