Get a page's source with PHP, manipulate with JavaScript - javascript

JavaScript cannot get an arbitrary page's source code, last I knew. But PHP can pretty easliy.
//get page source code with php
<?php
url = 'http://www.thesaurus.com/browse/strong?s=t';
$src = file_get_contents($url);
?>
PHP is not good at manipulating the DOM, but jQuery is great for that!
I would like to do something like
//manipulate source code with javascript
<script>
html = '"' + <?php echo $src;?> + '"';
listItems = $(html + " li");
printLists = '';
$.each(listItems, function(ind, el) {
printLists += el.innerHTML + "<br/>";
});
document.write(printLists);
</script>
But, any time I echo $src into the script tag, it gets interpreted as HTML immediately and the page becomes a live mockery of the actual site.
//Actually just shows me thesaurus.com#strong
<body>
<div id="holder" style="display: none;"></div>
<script>
holder = $("#holder");
nodeNames = [];
html = $.parseHTML(<?php echo $src;?>, holder, false);
</script>
</body>
The phrase 'virtual DOM' sounds right, though I really don't want any of the copied source code to show up at all. I just want to extract certain parts of it : to run a script from the console, search a few thesaurus sites for a term, take the results, and save them to JSON accessed by a local thesaurus script.
I have a solid idea of how to do everything else, didn't expect this to be the tricky part!
Any suggestions on preventing the browser from parsing HTML?
(I would prefer this to run just as a script file without a browser anyway, but had trouble loading jQuery in a thesaurus.js file.)

You could run a php script to get file contents and echo the results to a textarea with readonly/disabled on, then query that php file through ajax to display the resulting textarea on the page.
For example, output.php:
<?php
$str = '<p>I am a paragraph.</p>';
echo '<textarea readonly="readonly">'.$str.'</textarea>';
?>
AJAX call in the original file:
$.ajax({url: 'output.php', success: function(data) { $('#result').html(data); }});

Related

Javascript generated in PHP is not executing

I'm trying to create a roulette system, which should work as follows: The user clicks on a submit button, which is then checked on the opening_case_handler.php file to see whether the user has sufficient funds in his account or not, and if he does it will echo javascript code which will create the animation for the roulette and will also come out with the winning prize. For security purposes I am executing the js code in php so the user has no access to it since it is executed in the server side.
The issue here is that the js and jquery code do not get executed once this line of code has been reached:
var gw = $(".gift").outerWidth(true);
in the opening_case_handler.php.
You will notice that there are two alerts before and after the previous line code I have just mentioned. If I uncomment alert("TEST1") it will get executed and an alert message will appear however the rest of the code will no be executed. Also if I uncomment only the alert("TEST2") it will not be executed and nothing will happen.
To make sure that the javascript code actually works. I previously tested it in a javascript file and sourced it in the index.php file and it worked perfectly.
index.php
This page contains the roulette with all the different images of each item. The submit button is at the bottom. This is the button that users will click to be able to spin the roulette.
<div class='rafflebox'>
<div class='pointer'></div>
<div class='boxwrapper'>
<ul class='giftwrapper'>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg2">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg3">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
<div class="gift item bg-size2 box-bg4">
<img class="item-product2" src="graphics/mouse.png" draggable="false">
</div>
</ul>
</div>
</div>
<form method="post">
<button type="submit" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
</form>
</div>
opening_case_handler.php
<?php
session_start ();
if(isset($_POST['opening_case']))
{
opening_case ();
}
function opening_case ()
{
if ($_SESSION['balance'] >= $_SESSION['box price'])
{
echo '
<script>
//alert("TEST1");
var giftamount = 10;
var gw = $(".gift").outerWidth(true);
//alert("TEST2");
var giftcenter = gw/2;
var cycle = 7;
var containercenter = $(".boxwrapper").outerWidth(true)/2;
for(var i = 0; i <=5; i++)
{
var giftduplicate = $(".giftwrapper").children().clone(true,true);
$(".giftwrapper").append(giftduplicate);
}
$(".button").click(function()
{
alert("You DO have sufficient funds");
var btn = $(this);
btn.hide();
var randomgift = Math.floor(Math.random() * 4) + 1;
var dev = Math.random()*(giftcenter+1);
var distance = giftamount * cycle * gw + (randomgift*gw) - containercenter -24 +dev;
console.log(distance);
$( ".giftwrapper" ).css({left: "0"});
$(".giftwrapper").animate({left: "-="+distance},10000,function()
{
alert("You Won Gift" + randomgift);
btn.show();
});
});
</script>';
} else {
//to be done
}
}
?>
Please feel free to express your ideas on how this type of system should be better built. I am open to all suggestions, I am fairly new to this.
Thank you!!
Try using Heredoc string quoting example for printing your JavaScript:
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Heredoc text behaves just like a double-quoted string, without the
double quotes. This means that quotes in a heredoc do not need to be
escaped, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
If it is just a php code file. You can try some below.
<?php
echo "some stuff here"
if ($condition){ ?>
<script>
alert("condition true");
</script>
<?php } else { ?>
<script>
alert("condition false");
</script>
<?php }?>
When a form gets submitted it redirects you to the PHP page (ie when you click submit in index.php you will get redirected to opening_case_handler.php ) and then the PHP page will send you back to the index page with the new info. Thus, your javascript code gets printed in the opening_case_handler.php which is why your javascript did not get executed. Also, your javascript code will always be visible unless if you do something really creative so if you are trying to handle any sensitive information do it in PHP or any backend framework you are using.
There are ways to fix this issue but I would recommend a different approach to solve this issue. You can use an AJAX request which basically works in the following manner:
You send a request to your PHP server with the data you want to send.
Your PHP server will process the request and send it back to you
Your Javascript code will process the result and show the animations
or whatever you want to do.
This way your algorithm is not shown and your client ( the javascript side ) only handles information entered by the user and the results came from the server.
In your case, we can do that using the following changes
Index.php (which can be changed to index.html now)
<button type="submit" id="opening_case" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#opening_case").on("click", ()=>{
// $.get( "opening_case_handler.php?opening_case=true", function( data ) {
// console.log(data.funds)
// });
$.ajax({
url: "opening_case_handler.php?opening_case=true",
success: (data)=>{
if(data.funds) {
alert("You DO have sufficient funds")
} else {
("You don't have sufficient funds")
}
},
dataType: "JSON"
});
})
</script>
opening_case_handler.php
<?php
if(isset($_GET['opening_case'])) {
$result = [
"funds" => true,
];
$ResultsInJSON= json_encode($result);
echo $ResultsInJSON;
}
?>
The index.php will send the request when the button is clicked using AJAX which you can read about it here https://api.jquery.com/jquery.get/ then your PHP will receive the request and response with a JSON code which can be processed using the data.whatever as shown in the example above.
Note: I am not a PHP expert but I believe this will be a better method to use in this case.
Note2: You don't need Jquery for Ajax but it's easier! Here is how you do it without Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

How to show php file output in span by document write?

My JavaScript code inserts values into a database.
I want to:
echo some value in insert.php file, and
show the results in above span by document.write().
preferable a text link or image link.
What amendment do I need to make to insert.php to do so?
<script language="JavaScript" >
var bhs = document.createElement('script');
var bhs_id = "yvw3lwc1tnvq670ybzprm8xyh93rider";
bhs.src = "//online.examaim.com/insert.php?site=" + bhs_id + "";
document.head.appendChild(bhs);
document.write("<span id='o_" + bhs_id + "'></span>");
</script>
Could you provide more of an explanation as to what you are trying to achieve? It sounds like you might be confused as to how php works but to do specifically what you are asking:
document.write("<span id='o_" + <?php echo $someVariable ?> + "'></span>");
but I am guessing that the file with this javascript in is not insert.php?
You link to php files the same way you link to a html file. I think there may be a fundamental misunderstanding on how php works here: http://www.w3schools.com/php/

How to put php content into javascript markup?

I have a video gallery, and all the titles are generated by php. The lightbox for these videos, however, is customized in javascript. How can I put the php titles inside the iframe markup?
See here:
$('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> <?php the_title();?> </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
EDIT
For reference, I need the attachment title below ($attachment_data['title']) in the javascript section mentioned (the markup).
<?php
$the_query = new WP_Query(array(
'post_type' => 'attachment',
'category_name' => 'video'
));
while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<?php
$attachment_data = wp_prepare_attachment_for_js( $attachment->ID );
echo'<figure><a class="video" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
echo''.the_post_thumbnail ('medium').'';
echo'<div class="photo-title"><h2>'.$attachment_data['title'].'</h2></div></a></figure>';?>
<?php
endwhile;
wp_reset_postdata();
?>
Try this:
$('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> <?=the_title()?> </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
Notice the use of the <?= shorthand for echo. (read more about it)
There are a few ways to get javascript and PHP to interact. You could pull from the client using an ajax call. If you need to get a bunch of data asynchronously, that might be the thing. If you're going to have 20 copies of this iframe, you might consider using an AJAX call to pull a whole array of values/objects with JSON and then you can do with them whatever you'd like.
But... I suspect that you'll just use this iframe once per page. Rigging up some ajax for a once-per-page thing is probably a little overkill.
If you are putting your javascript right on your page, you could do as IzzEps suggested and simply echo your php values right into the iFrame. But I know most folks like to keep their javascript separate from their html content in a .js file. This makes it more maintainable. While not impossible, php most easily puts content onto .php files rather than others like js. I don't have any experience with getting a browser to use a php file for a script source.
What I've found easiest and cleanest is to write my javascript in my .js file as normal, then I'll add the variable(s) to my .php file as minimally as possible at the top in a script tag.
So, at the top of your page, you could do something like any of these:
<script>
ObjectYoureWorkingWith.Title = '<?php echo $the_title(); ?>';
var TitleObjectList = <?php echo json_encode($list_of_titles); ?>;
</script>
Basically, you feed input from your php into whatever module, object, array, or variable you're working with and then you can refer to that in your javascript wherever you need it. That way you're not forced into putting all your javascript right in with your html. You can even do this with a whole object or collection of object using json_encode (which is javascript's native object notation anyway).
Update:
I was typing the above on my cell (not the best way to respond to this sort of thing). Let me demonstrate what I'm describing:
Let's say in your php you have 20 titles you want to work with. You could make an associative array. Use an Id or whatever identifier you want to call it with.
$titleArray = [ 123 => 'Title1', 456 => 'Title2']; //(and so on....)
Then, on the php page you're wanting that data, do this:
<script>
var titleArray = <?php echo json_encode($titleArray); ?>;
</script>
This will now allow you to access it on that page (or in a js file loaded on that page) by doing this:
var myFirstTitle = titleArray["123"]; //This will return "Title1"
json_encode will take a PHP object and translate the public variables into a javascript object. Simply echoing this to a javascript variable will give javascript the object to work with.
The developer of the lightbox has a solution that I was already partly implementing. For the title to appear in the lightbox, I needed this callback from my original code:
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
But I had neglected to include the title in my PHP loop, corrected here:
echo'<figure><a class="video" title="'.$attachment_data['title'].'" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
There's a similar post that also covers this answer, for reference:
Title for iframe/video in magnific popup
Thanks again for all your help!

Insert code with JS just like echo in php

I want to get some code snippets from a PHP server to be "injected" in HTML. Basically when I open page.php I get some text like "_off".
The injection works with this code, however I can't use php in this html since it is local.
<img src="images/test
<?php
{ echo "_off"; }
?>
.jpg">
JavaScript seems to be the logical step. But if I just enter this at the position where I want the text of course it doesn't work:
<script type="text/javascript"> $.get( "page.php", function( data ) { document.write(data); } ); </script>
Any ideas?
You need to use $('#someElement').html(data) or $('#someElement').text(data) if you want to write the data to a specific place on the page. You should avoid using document.write
Here is a fiddle to demonstrate: https://jsfiddle.net/yd9mx4d3/

PHP link written into page not being retrieved by a JAVASCRIPT function

I'm writing on a page the following code with PHP. This code creates a A HREF link with the ID equal to $intIdType, which is the value of the PRIMARY KEY in a database, and $count gets the amount of records per category on the database. All of this is inside a WHILE that reads each record and writes on the PAGE the results
echo "<a href='#' id='$intIdType'>";//Starts creating the link
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "(";
echo " $count1 )"."</a>";
Now, after the results are on the page it will look like this:
$intIdType $arrBusinessTypes $count
--------------------------------------------
1 -Auto Sales ( 1 )
2 -Auto Repair ( 1 )
5 -Web Desig & I.T. Services( 2 )
6 -Computer Shop ( 1 )
The above result displays each rown as a link where I can click on it, but nothing happens. Even just a simple Alert in javascript does not show up. It seems that it never reaches even the Javascript at all.
What I need now is to retrieve that PHP generated code on the page by a Javascript file, that will allow me to use the hiperlink generated by PHP into the .HTML page
It works if I write directly into the page what PHP is suppose to write. I wonder if this happens because Javascript can not read posted data from PHP into the page.
The Javascript File looks like this:
window.onload=post_result
function post_result() {
$("#1").click(function() { //This is the HREF ID that is written by PHP into the page
$('#list_results').load("results.php");//This seeks to run a PHP file in a DIV
$('.title').text('Listing Categories');//This just replaces the Title in the page
})
I'm just a beginner trying. Thanks for any help.
echo "<a id='$intIdType'>";//Starts creating the link echo "$intIdType -";
echo "$intIdType -";
echo $arrBusinessTypes["business_Description"];
echo "("; echo " $count1 )"."</a>";
just remove href attribute and try
Remark #1: quote custom data when outputs it to HTML:
echo $arrBusinessTypes["business_Description"]; must be
echo htmlspecialchars($arrBusinessTypes["business_Description"]);
Remark #2: you don't need window.onload handler here. In this piece of code you select complex way to do simple thing. Why do not write direct onclick handler? Write function loading some data depending of parameter and do something like:
$htmlspecialchars = function($s){return htmlspecialchars($s);};
echo <<<HTML
<a href='#' id='$intIdType' onclick='loadInfo($intIdType)'>
$intIdType -{$htmlspecialchars($arrBusinessTypes["business_Description"])} ( $count1 )
</a>
HTML;
(converted to heredoc to make HTML more clean)

Categories

Resources