We are trying to fetch url from PHP DOM but webapge that we try to fetch has functionality (change price after page load) so now we need that PHP Dom function file_get_html get HTML after this onload functionality of remote page has been completed.
$html = file_get_html('https://www.example.com');
// Find all article blocks
foreach($html->find('div.pad15 h4 a') as $article) {
echo $article->innertext.'<br>';
}
foreach($html->find('p.sprc span.fb') as $pr){
echo $pr->innertext.'<br>';
}
$html->clear();
unset($html);
if I right undestend question you problem is get html after loading js. It's impossible. Becouse php open connection and get data at once
answer about you question is "NO"
php can not receive javascript rendered result. javascript is running on browser side and it not possible with php.
alternative is to do task with
http://phantomjs.org/
var page = require('webpage').create();
page.open('http://google.com', function () {
console.log(page.content);
phantom.exit();
});
Related
I have two pages. mobile.html and video.php. mobile.html sends an ajax post request with a single variable. video.php should read that variable and pass it to a JS function in the same page that would change a video control. I tried to use this logic:
mobile.html sends an ajax post request
video.php has PHP code inside a div to read the request and get the variable
reload video.php and allow the JS code in the same page to get the variable from inside the div
pass the variable to the intended JS function in video.php.
execute the function on the video.
here is my code and for simplicity I replaced the video with <p> tag. mobile.html code works fine. my problem is in video.php
mobile.html
$.post("video.php", {gesture: action}, function(response){
$("#result").html('response: '+response);
});
video.php
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
//a div to hold the value of post variable
<div id="dom-target" style="display: none">
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if( isset($_POST["gesture"]))
{//put the variable value inside the div to fitch it later
$gesture = $_POST["gesture"];
echo $gesture;
}
else {
echo "none";
}
}
else {
echo json_encode("PHP no post");
}
?>
</div>
//p content should be updated with the value of $gesture
<p id="update">
should be updated with post variable using JS
</p>
<script>
//get post variable from the div
var div = document.getElementById("dom-target");
var myData = div.textContent;
$("#update").html(myData);
console.log("myData: "+myData);
</script>
</body>
</html>
I have been up over my head for a week trying to work around this problem but I cannot seem to get the result that I want because when I reload the page I find my variable in the ajax callback function :/
the output I am getting currently is "PHP no post" in video.php and myData: "PHP no post" in the console of video.php which is ok because obviously the first time I run the page it is not through a post request. however when I click the button that triggers the post request in mobile.html I get the output of this line console.log("myData: "+myData); with the correct data but in mobile.html console! not in video.php console. meaning that the code is run in the callback function of the ajax post request in mobile.html.
I failed to find a way to update the <p id="update"> in the currently opened video.php page. Now I am not even sure I can do it with PHP since it runs only on a server and JS runs only on the web browser.
My question is: can I do the steps explained above using PHP ?
IF YES can you help me figure out a way to dynamically and instantly update the video.php page using a post call sent from mobile.html ? or any other way that would work with PHP?
IF NOT can you suggest what other languages/platforms I can use to do what I want to do ?
UPDATE:
to have an idea of what I want to achieve, I did two pages using localstorage. open mobil.html in one window and then openvideo.html
in another window side by side. play the video then use the controls on mobile.html and see how it changes the playback in video.html.
I want to be able to do the same thing but remotely using PHP because I have to use a real mobile instead of mobile.html
You are sending your gesture value to the video.php file, but you are not using it to get a new paragraph element with the updated value in it. PHP should do its work on the server and JavaScript strictly on the frontend.
Keep your POST request the same.
$.post("video.php", {gesture: action}, function(response) {
$("#result").html('response: ' + response);
});
But modify the response that server returns. The gesture value is in the $_POST array. From there you can use it to render a new paragraph and echo or return this to the frontend.
<?php
// Set default value.
$gesture = 'none';
if ( isset( $_POST[ "gesture" ] ) ) {
// Overwrite if there is a gesture value.
$gesture = $_POST[ "gesture" ];
}
// Echo a new paragraph with the gesture in it.
echo '<p id="update">' . $gesture . '</p>';
exit;
?>
first just please organize the code a little bit so you can see the code well
you need to put the post request inside a function with a trigger action because with that it would be never called
you need to make sure that you are getting the correct data in 'action' variable (console.log it before the post)
(if $.post is not working for some reason download jquery and use it locally because it might not be in the slim CDN)
Hint:
$( document ).ready(function() {
console.log(gesture); //check this in the console after refreshing the page
$.post("video.php", {gesture: action}, function(response){
$("#result").html('response: '+response);
});
});
I am answering my own question for those who have been rumbling about not understanding how to update a part of a web page in real time without having to reload it. Long story short, To achieve the scenario I mentioned in my question I have to use WebSockets as #EmielZuurbier pointed out in the comments of the first answer, so thanks to him.
There are tons of ways to do that.For beginners, you have to be patient and make sure you understand how it works properly before you jump in coding. Also, know that some codes that are available on the internet work only on the backend and that there are specific ways to make websockets work on a browser. In my case I used Node.js in the server side and isomorphic-ws in the client side in a web browser
here are some helpful references that helped me during the past week:
Here is the official site for Node.js for installation and documentation.
This is a good video to get you started if you are new to WebSockets. it explains Websockets and display real implementation of it.
Here you can find documentatino of WebSocket().
This video demonstrate how to implement a websocket in your local
machine (aka laptop): How to Create a WebSocket Server & Client.
Be aware that the video above will work only on backend which you can run using Terminal on mac or Command line in Windows. To work it on a
browser I used isomorphic-ws which is a wrapper that allows
websockets to work on web browsers.
I wish this could help anyone who was stuck like me on how to implement a real time communication between two ends.
How can I make a Modal Box/Notification Box appear when I do header redirect or some other method of redirection to a page? Basically as a Success kind of thing. Like I click on send it opens a page and then brings them back to the same page where the send button is and will show a Success box? Any ideas?
If you need to trigger some code on a PHP page through an AJAX call you can do it without directly opening that URL. You just pass that PHP URL to a call, the PHP page code is executed and the response is returned back to the page where the request originated. It would look something like this:
<span id="someButton">Button</span>
<div id="someDivOnYourPage"></div>
<script>
$('#someButton').click(function(e) {
$.ajax('page.php', {
success: function(data) {
alert(data); //This alerts 'Hello from PHP!'
$('#someDivOnYourPage').html(data);//this will set 'Hello from PHP!' inside the #someDivOnYourPage div
},
error: function() {
alert('An error occurred');
}
});
});
</script>
page.php
<?php
echo "Hello from PHP!";
?>
A more detailed explanation with downloadable examples can be found here: jQuery Ajax POST example with PHP.
If it's just a login or something similar, you can store the message in a session on whatever page you're processing and then once the page has been redirected, put that session variable into a regular variable and unset your session. Then you'll just print out whatever as HTML or Javascript.
On the page you submit to
//Do your processing
$_SESSION['someReturnMessage'] = 'Success!';
header('Location:./originalpage.php');
On originalpage.php
//Top of file
if(isset($_SESSION['someReturnMessage'])){
$message = $_SESSION['someReturnMessage'];
unset($_SESSION['someReturnMessage'];
}
...further down the page where you want the message to show...
if(isset($message){
echo $message;
}
You could also use AJAX, which may be a better fit for doing simple tasks.
Using sessions can be a bad idea though, so make sure you don't use them when there are better solutions: Error messages stored in SESSION
I am working on updating my website, which now uses an AJAX engine. My engine works well, up-to-hand for some reason some pages do not execute javascript, let me explain: when the anchor change I use $.get for data recovery. The pages have this structure:
title
h1
script1.js,script2.js,etc.js
style1.css,style2.css,etc.css
<!--there's the page's content-->
It appears reload the page solves the problem, but i don't understand what is different. In the previous code, the engine runs successfully, reloaded or not:
$.getScript("script1.js");
$.getScript("script2.js");
$.getScript("etc.js");
In addition, a php generated script contains user's current state under an Object form:
$(function(){
user = new Object();
user.id = user.logged = <?php echo $user->getId();?>;
user.nick = "<?php echo $user->getNick();?>";
user.mail = "<?php echo $user->getMail();?>";
user.logout = function(){
};
});
The $.getScript request is successful, but the user object is not changed. The script, however, has yet been modified. And it don't works from console too.
The update is currently online at v2.wawolf.com, you'll find everything you need.
Hotlink: Engine's code
I just solved my problem: when all document is loaded, $(function(){}) will not work again, so calling a script which uses $(function(){}) will no get run. I removed it from all my secondary-called scripts and now all works perfectly!
it might just be a loading order issue.
try encapsulating the JS loading in an onload function
$(window).load(function(){
//get script loads here
}
or
$(document).ready(function() {
//get script loads here
}
Sometimes I use one inside the other for dynamic JS script that needs to be loaded last.
I have asked this question, but I think that wasn't clear enough so I am putting it differently. I have a _form.php page and a grid-view(index.php)page.
I am sending a Pjax request from _form.php and want to update/refresh the grid-view(index.php)page.
on top my _form.php I am having this code.
<?php
$this->registerJs(
'$("document").ready(function(){
$("#new_medicine").on("pjax:end", function() {
$.pjax.reload({container:"#medicine"}); //Reload GridView
});
});'
);
?>
Now the container "#medicine" is not on _form.php page, but grid-view(index.php) page. So how can I modify the above code so that it updates/refresh the container "#medicine" in index.php page.
I think I have explained the situation correctly. please tell me, if more information is needed.
Thanks.
Try using $this::POS_READY instead of wrapping your code in $("document").ready(function(){})
$js = '$("#new_medicine").on("pjax:end", function() {
$.pjax.reload({container:"#medicine"}); //Reload GridView
});'
$this->registerJs($js, $this::POS_READY);
EDIT
Apparently you want to reload the gridview that is open on another client's index.php after data is inserted using _form.php.
It isn't possible to send jQuery commands to another client (browser) and have it executed.
You can for example reload the gridview on the index.php every x seconds or minutes.
$js = 'function refresh() {
$.pjax.reload({container:"#medicine"});
setTimeout(refresh, 5000); // restart the function every 5 seconds
}
refresh();';
$this->registerJs($js, $this::POS_READY);
I am making a function which searches the database for flight information. I want user to be redirected on "ticket.php" if the response is true. I want to update the content of the page "ticket.php" using jquery. But jquery doesn't work. Am I doing something wrong here ? Here's part of javascript. It's an external javascript. It's included in both "search.php" and "ticket.php" page. This function gets invoked by clicking on search button in "search.php" page.
if(data){
setTimeout("location.href = 'ticket.php';",3000); // Redirect to new page
//Change content of "ticket.php" using jquery.
$("#source").text(x);
$("#destination").text(y);
$("#date").text(z);
$("#no_person").text(person);
$("#trip_type").text(type);
}
else
$("#alert").text("Oops! No Flight matches your criteria ! ");
When you set location.href to ticket.php, the user is then redirected to that new page (ticket.php). Then the browser will load that new page and will no longer use the javascript you have on your current page.
You will have to make the data appear on ticket.php, using e.g. url parameters taken from what they searched like this:
window.location.href = 'ticket.php?from=norway&to=sweden';
The reason this is not working for you is because when you redirect to ticket.php the page is reloaded and all of the javascript on the page is refreshed, losing whatever value they had before. To keep the data you have to send the information to ticket.php
There are a couple of ways to accomplish this, ordered in preferred method.
all assuming you are requesting the page like this: ticket.php?from=norway&to=sweden
php on the page ticket.php
<?php
echo $_GET['from'];
echo $_GET['to'];
?>
javascript on the page ticket.php
solution for getting params from this post:https://stackoverflow.com/a/1404100/2033671
alert(getURLParameter('from'));
alert(getURLParameter('to'));
jQuery from a different page on the same domain
$.get('ticket.php',function(response){
$html = $(response);
$html.find("#destination").text(y);
$html.find("#source").text(x);
$("html").html($html);
});