Is it possible to use ajax to load a single php function? - javascript

Example:
I have written a php script like below:
<?PHP
function _hello(){ "Hello world!"; }
function _bye(){ "Good Bye!"; }
function _night(){ "Good Night!"; }
?>
<html>
<head>!-- required files -- </head>
<body>
<div id="thisDIV">
<? echo _hello(); ?>
</div>
<div>
This is another Division.
</div>
</body>
</html>
Is it possible that I just want to reload the function _hello() in the division (id=thisDIV) by using javascript? Or ajax, Jquery ajax or whatever.. How can I make it? Thanks!

You could add a querystring to your URL and then tie that to what function you want to run:
eg: http://myurl.com/page.php?function=hello
In page.php:
$function = $_GET['function'];
if($function == "hello") {
hello();
}
etc etc

Related

How to call a php function on a html text click?

I want to call php function while call that function I need to pass parameter, when click on some text, It has to call the method called test();
How to do this.
I don't know anything about ajax.I have taken this code to try it.To try I have used simple code it is also not working.
This is Ajax.html file
<!DOCTYPE html>
<html>
<head>
<body>
<p>Click Me</p>
<script>
$(document).ready(function() {
$("p").click(function(){
$.ajax({
url:"script.php", //the page containing php script
type: "POST", //request type
success:function(result){
alert(result);
}
});
});
})
</script>
</body>
</head>
</html>
script.php contains,
<?php
function test(){
echo "Hello";
}
?>
how to call php function when user click on some text.where I have to call that test() method. Can Any one help me?
Either you need to call when page called
<?php
test()//mind it
function test(){
echo "Hello";
}
?>
Or use any param like name of action
<?php
if(isset($_GET['action']) && $_GET['action']==1){
test()//mind it
}else{
otherFunc()//mind it
}
function test(){
echo "Hello";
}
?>
Set action in url
url:"script.php?action=1",

PHP: echo as condition of if statament?

I need to put echo as condition of if statement. So, for example:
<html>
...
...
<body>
<form onsubmit"<?php $c=false; if(echo "<script>example();</script>";){ $c=true; } echo "\""; if($c){ echo "action=\"./\"";} method="post">
...
</form>
...
...
<script>
function example()
{
alert("This is only an example");
if(..) return true;
return false;
}
</script>
</body>
</html>
So I need to create a function in JavaScript (this top is only an example, but, in realty, it is more complicated) and call it in the if statement.
Update
The code should be execute "action" of the form only if the Javascript function is true.
PHP runs in the server. JavaScript runs in the client. So php can't use a js variable or its function to server side action. What u can do is , u can call JS function from PHP like
echo "<script> myFunction() </script>";
But in the same same case, u can use php values for JS actions,
eg
<script>
var x = <?php echo $myVar ?>
if(x == true){
alert("yahooo");
}
</script>

Echoed Javascript Code from PHP Via AJAX Not Running

My code is meant to get the author of an inputted book using the Google Books API via AJAX. If nothing is inputted it prints "Empty". What it actually does is print out the Javascript code when a book is inputted. When nothing is inputted, it prints "Empty" as it should. How could I modify my code to make the echoed Javascript execute and hence get the author of an inputted book?
Just to see, I replaced the echo part with echo "<script>document.getElementById('txtBox').innerHTML = 'Hello';</script>";. It also prints out the javascript code, so I don't think it has something to do with using the API.
getAuthor.html
<!DOCTYPE html>
<html>
<body>
<!-- Input -->
<div class="form">
<form onsubmit="makeRequest(); return false">
<input type="text" id="inputText" name="inputText">
<input type="submit">
</form>
</div>
<br>
<!-- Output -->
<div class="txtBox">
<textarea id="txtBox">
</textarea>
</div>
<!-- AJAX to create output using jEcho.php file-->
<script>
function makeRequest() {
httpRequest = new XMLHttpRequest();
console.log(httpRequest.responseText);
httpRequest.onreadystatechange = function() {
document.getElementById("txtBox").innerHTML = httpRequest.responseText;
};
httpRequest.open("POST", "jEcho.php", true);
httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpRequest.send("inputText=" + document.getElementById("inputText").value);
}
</script>
</body>
</html>
jEcho.php
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>
<script src='$scriptSource'></script>";
}
?>
Links
Echoing Javascript From PHP:
How to call a JavaScript function from PHP?
Echoing javascript from PHP
Google Books API:
https://developers.google.com/books/docs/v1/getting_started
https://developers.google.com/books/docs/v1/using
<script> elements are only run when your page is first loaded. Script elements created later on, either by assigning to an element's .innerHTML, creating them using document.createElement(), or otherwise, are not executed.
If you want to have a PHP script send back code to be evaluated, you'll have to do that directly, e.g:
httpRequest.onreadystatechange = function() {
eval(httpRequest.responseText);
};
(And remove the <script> tags from the response.)
Try setting header in jEcho.php file (not tested)
header('Content-Type: application/javascript');
I'm not allowed to comment so:
I'm not certain what has caused it for but could <script src='$scriptSource'></script>"; be called before the handleResponse function. I'm not too sure what is causing it, at the moment, that is my best idea.
Also could you not just have the url already in the code like this: (jEcho.php)
<?php
$input = $_POST["inputText"];
if ($input == "") {
echo "Empty";
} else {
// used to parse
// e.g. The Rosie Project -> The+Rosie+Project
$temp = str_replace(" ", "+", $input);
// create appropiate source
//$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
echo "
<script src='https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse'></script>
<script>
function handleResponse(response) {
var item = response.items[0];
document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
}
</script>";
}
?>

converting the result of a javascript function into a usable variable

I have this code which returns on a click of a button the URL of an iframe
<html>
<body>
<iframe src="start.php" name="vframe" id="vframe"></iframe>
<script>
function glink() {
alert(document.getElementById('vframe').contentWindow.location.href);
}
</script>
<button onclick="glink()">Click me</button>
</body>
</html>
What I want to do is somehow use the javascript function to create a variable (the link it captures via the onclick) inside the function without the need for an onclick that can be used in the parent page
For example
<html>
<body>
<iframe src="start.php" name="vframe" id="vframe"></iframe>
<script>
function glink() {
var x = document.getElementById('vframe').contentWindow.location.href;
}
</script>
Then I can use var x in this way ...
<script> if ($link =="start.php") { echo '<img src="start.jpg">' } else {
echo '<img src="end.jpg">' }
</script>
</body>
</html>
Obviously, the javascript is somehow able to get the link, but I need to get it programmatically and not have to rely on a 'click', and I need to be able to hold the link in a variable so I can use it in a conditional statement, as noted above.
I am not too familiar with javascript syntax.
====
Edited
====
I tried this (based on DevishOne's suggestion):
<html>
<body>
<iframe src="start.php" id="vframe"></iframe>
<script>
function glink() {
var x = $('#vframe').attr('src');
$.get('processIframeLink.php',{link:x});
}
</script>
<?
$link = $_REQUEST['link'];
echo $link;
if ($link =="start.php") {
echo '1';
} else {
echo '2';
}
?>
</body>
</html>
But there is nothing showing at '$_REQUEST['link'];'
however I just tried this:
<html>
<body>
<? $test = '<p id="demo"></p>';
echo $test;
?>
<iframe src="start.php" name="vframe" id="vframe"></iframe>
<script>
document.getElementById("demo").innerHTML = document.getElementById('vframe').contentWindow.location.href;
</script>
</body>
</html>
Here, echo $test returns the result of the script. But for some reason, it keeps returning "about:blank"
If there was some way to get "document.getElementById('vframe').contentWindow.location.href;" to show the iframe link, then I have accomplished the goal.
I have found "document.getElementById('vframe').contentWindow.location.href;" in many places on the net saying it can get the iframe link, but I keep getting "about:blank"
==========
edit
Here is the latest attempt:
<html>
<body>
<iframe src="start.php"></iframe>
<script>
function glink() {
var x = frames[0].location;
document.getElementById("demo").innerHTML = x;
}
</script>
<button onclick="glink()">Click me</button>
<? $link = '<p id="demo"></p>'; ?>
echo '<p id="demo"></p>';
?>
</body>
</html>
What this does is (upon the click), allows the JS to find the link and then the PHP reads it as a variable. The only issue here is if there is no 'click', frames[0].location; = "about:blank" ... if there is a click, then the code writes the link to the PHP variable.
how to 'read' the link without the click or to simulate a click to bring in the link, that would be ideal.
The problem with your question is that JS cannot directly communicate with PHP.
PHP page is rendered instantly, and JS is rendered WHILE page is being loaded, through your Web browser.
To solve this problem you need to use either Ajax or jQuery and use POST or GET functions through POSTBACK functions.
They allow you to send information to secondary page, while fetching results and rendering those results into the primary page.
HTML
<script>
function glink() {
var x = $('#vframe').attr('src');
$.get('processIframeLink.php',{link:x});
}
</script>
PHP (processIframeLink.php)
$link = $_REQUEST['link'];
if ($link =="start.php") {
echo '<img src="start.jpg">';
} else {
echo '<img src="end.jpg">';
}

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

Categories