This question already has answers here:
How can I get the title of a webpage given the url (an external url) using JQuery/JS
(3 answers)
How to get the content of a remote page with JavaScript?
(6 answers)
Closed 2 years ago.
How I can read the title of a remote web page with javascript? Suppose the web page is:
www.google.com
I want to read the title of that page; how should I do this?
You won't be able to get this data with jQuery alone, however you can use jQuery to communicate with PHP, or some other server-side language that can do the heavy lifting for you. For instance, suppose we have the following in a PHP script on our server:
<?php # getTitle.php
if ( $_POST["url"] ) {
$doc = new DOMDocument();
#$doc->loadHTML( file_get_contents( $_POST["url"] ) );
$xpt = new DOMXPath( $doc );
$output = $xpt->query("//title")->item(0)->nodeValue;
} else {
$output = "URL not provided";
}
echo $output;
?>
With this, we could have the following jQuery:
$.post("getTitle.php", { url:'http://example.com' }, function( data ) {
alert(data);
});
Getting the content of a remote page you have no control over is going to be a problem because of the same-origin-policy. For more information look here: How to get the content of a remote page with JavaScript?
Try this
alert(document.title);
in your case i guess you would only be using the document.title
The effective method is to write some Server side code (using PHP/ASP/.NET) and pass the URL via AJAX in script and get the title of any remote page.
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I have the following javascript code:
function like(){
if(loged) {
if(liked) {
likes-=1;
liked = false;
document.getElementById('alike').src = "img/icons/like.png";
} else if(disliked) {
dislikes-=1;
disliked = false;
likes+=1;
liked = true;
document.getElementById('alike').src = "img/icons/like1.png";
document.getElementById('adislike').src = "img/icons/dislike.png";
} else {
likes+=1;
liked = true;
document.getElementById('alike').src = "img/icons/like1.png";
}
} else {
<?php header("Location:login");?>
}
}
I want to redirect the user to the login page how can i user php inside javascript to this. I do not want to have to use any other things like ajax etc. Thanks.
You do not need to use PHP header() to redirect with JS. You can simply use the window.location property:
window.location.href = "your_url";
//or
window.location = "your_url";
//or
location.href = "your_url";
//or
location = "your_url";
As mentioned in the other comments, to redirect in javsascript you want to use something like window.location.href = "your_url";.
Here's a bit of extra information as well to help you out in the future, as you seem to have misunderstoon the relationship between PHP and JavaScript.
In a nut shell, you can't call PHP functions from javascript. PHP code and javascript code run at two very different times in the request cycle. PHP is run by the server and JavaScript is run by the client (browser)
PHP
When you load a webpage a request will be sent by your client (browser) to a server, which receives it and returns a response.
PHP runs on the receiving server and it's job, very simply put, is to generate a response to send back to the browser. So it may generate html, javascript, etc.
You can use PHP to output html for example <?php echo 'Hello world'; ?>.
Once PHP has sent it's response that's it, it's game over for PHP.
HTML and JavaScript
The requesting browser will receive the response that the server sent and will then handle it. For HTML it will render a page and any JavaScript will be run.
Javascript can't interact with the PHP in anyway at all, since the PHP code was run on the server, while the javascript runs on the client.
It's important to understand the different between client and server, otherwise you'll find yourself running into similar problems going forward :)
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want to check the inputs of a form if they are empty and then i want to use php codes for user registeration.
<script>
$('#submitbutton').click(function(){
if($('#usernameinput').val() == ''){
alert('Input is blank');
}
else {
//here i want to use php codes for example;
$bgl = new mysqli("localhost", "root", "", "users");
if ($bgl->connect_errno) {
echo "Failed to connect to MySQL: (" . $bgl->connect_errno . ") " . $bgl->connect_error;
}
$username = mysql_real_escape_string($_POST['username']);
.....
.....
..... /and so on..
}
});
</script>
In this case you most likely want to use $.ajax() to call a PHP page that supplies this information.
jQuery.ajax()
There is no such thing as php and javascript working together like that. Javascript in run on client side and php is run on server side. The best you can to is to pass and retrieve values to and from a php page and then use those values as intended.
You have a few options here. The first is to post the form to a PHP page after the JavaScript validations (just use the form action) or use Ajax and call the PHP page, as Robin says.
That's not posible, you can embed javascript into php code but not vice versa.
The best way to implement that is developing a REST service and retrieving data with AJAX.
I need to do what a bookmarklet does but from my page directly.
I need to pull the document.title property of a web page given that url.
So say a user types in www.google.com, I want to be able to somehow pull up google.com maybe in an iframe and than access the document.title property.
I know that bookmarklets ( the javacript that runs from bookmark bar ) can access the document.title property of any site the user is on and then ajax that information to the server.
This is essentially what I want to do but from my web page directly with out the use of a bookmarklet.
According to This question
You can achive this using PHP, try this code :
<?php
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
//Example:
echo getTitle("http://www.washingtontimes.com/");
?>
However, i assume it is possible to read file content with JS and do the same logic of searching for the tags.
Try searching here
Unfortunately, its not that easy. For security reasons, JavaScript is not allowed to access the document object of a frame or window that is not on the same domain. This sort of thing has to be done with a request to a backend PHP script that can fetch the requested page, go through the DOM, and retrieve the text in the <title> tag. If you don't have that capability, what you're asking will be much harder.
Here is the basic PHP script, which will fetch the page and use PHP's DOM extension to parse the page's title:
<?php
$html = file_get_contents($_GET["url"]);
$dom = new DOMDocument;
$dom->loadXML($html);
$titles = $dom->getElementsByTagName('title');
foreach ($titles as $title) {
echo $title->nodeValue;
}
?>
Demo: http://www.dstrout.net/pub/title.htm
You could write a server side script that would retrieve the page for you (i.e. using curl) and pars the dom and return the desired properties as json. Then call it with ajax.
What I'm trying to do is read a specific line from a webpage from inside of my PHP application. This is my experimental setup thus far:
<?php
$url = "http://www.some-web-site.com";
$file_contents = file_get_contents($url);
$findme = 'text to be found';
$pos = strpos($file_contents, $findme);
if ($pos == false) {
echo "The string '$findme' was not found in the string";
} else {
echo "The string '$findme' was found in the string";
echo " and exists at position $pos";
}
?>
The "if" statements contain echo operators for now, this will change to database operators later on, the current setup is to test functionality.
Basically the problem is, with using this method any java on the page is returned as script. What I need is the text that the script is supposed to render inside the browser. Is there any way to do this within PHP?
What I'm ultimately trying to achieve is updating stock from within an ecommerce site via reading the stock level from the site's supplier. The supplier does not use RSS feeds for this.
cURL does not have a javascript parser. as such, if the content you are trying to read is placed in the page via Javascript after initial page render, then it will not be accesible via cURL.
The result of the script is supposed executed and return back to your script.
PHP doesn't support any feature about web browser itself.
I suggest you try to learn about "web crawler" and "webbrowsers" which are included in .NET framework ( not PHP )
so that you can use the exec() command in php to call it.
try to find out the example code of web crawler and web browsers on codeproject.com
hope it works.
You can get the entire web page as a file like this:
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data('http://example.com/page.htm');
$my_file = 'file.htm';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $returned_content);
Then I suppose you can use a class such as explained in this link below as a guide to separate the javascript from the html (its in the head tags usually). for linked(imported) .js files you would have to repeat the function for those urls, and also for linked/imported css. You can also grab images if you need to save them as files.
http://www.digeratimarketing.co.uk/2008/12/16/curl-page-scraping-script/