php variable pass to java script and alert it - php

index.php
<?php
$loginmessage = "this is message";
?>
$(document).ready(function(){
$("#sb-btn").click(function() {
alert("<?=$loginmessage?>");
return false;
});
});
i have a button i wanted to when the button is clicked , it alert the $loginmessage by java script , but when i clicked it noting happen and no error as well. what i have to do to make the php variable pass to javascript and alert it when user clicked.

Don't forget to call jquery library. then try this-
<?php
$loginmessage = "this is message";
?>
<script>
$(document).ready(function(){
$("#sb-btn").on("click", function() {
var getvalue = '<?php echo $loginmessage; ?>';
alert(getvalue);
});
});
</script>

Depending upon your PHP version and host, the short tags could be disabled. They recently came back into use with PHP7, which is still in Release Candidate state.
What this means is that you might have to replace the short tags with the full <?php echo use. Look in the generated HTML code on the client, to find out if this is the case.
One small thing I'd like to nitpick on, is your terminology. :P
You're not actually passing a variable to JavaScript from PHP, as much as you're using PHP to generate parts of said JS. It might seem trivial, but the difference is a crucial one. Passing the variable implies something being handled in the same program, which isn't the case at all here. The PHP code gets executed on the server side, which generates plain text output to the client. The client (web browsers) in turn parses said content, and figures out what kind of content the different part of this text actually is.
Having this clear mental separation in mind when developing web applications/sites will make it a lot easier for you to understand the details of how things work, and in turn make it easier for you to come up with clean and simple solutions that works as intended. :)

Try to write in console. Maybe your browser blocks alert messages. And-> are you see JavaScript errors in your console?
<script>
$(document).ready(function(){
$("#sb-btn").on("click", function() {
var getvalue = '<?php echo $loginmessage; ?>';
console.log(getvalue);
});
});
</script>

Create a function that is called when a button is clicked. Pass the message that you want to alert to that function. Hope this helps. Checkout the code in snippet.
function alertSomething(test){
alert(test);
}
<button name="samplebtn" onclick="alertSomething('test alert')">Test Alert</button>

Related

Calling PHP from Java Script

I'm new at dealing with web programming and not used to dealing with the flow of data through a site.
I was looking for a way to call PHP from Java Script or from HTML and came across the following code with many other answers from this site. One thing that I got from Stack Overflow was that Ajax was the only good way to do this and JQuery would be the best way to go about that.
Is the code below safe? Are there holes in it that I don't know about at this point of learning?
<?PHP
$a="hello";
?>
<script>
function echoHello(){
alert("<?PHP hello(); ?>");
}
</script>
<?PHP
FUNCTION hello(){
GLOBAL $a;
ECHO $a;
}
?>
<button onclick="echoHello()">Say Hello</button>
This is not AJAX, but server-side code that only loads at first request.
A mockup of your functionality using AJAX is:
functions.php file:
<?php
$clientSideMethodRequested = $_POST['method'];
if ($clientSideMethodRequested == "sayhello"){
tellHimHello();
}
function tellHimHello(){
echo 'Hello!';
}
?>
client-side AJAX call:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "mydomain.com/functions.php?method=sayhello",
success: function(returnedString){
alert(returnedString);
}
});
});
It will not work. PHP is executed on server, JS is executed in your browser. When you are opening page, the server will at first interpret your code. The result of your code, after this will be like that:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
As you see, everything what was between <?php and ?> was "removed" from the origin file. By "removed" I mean executed.
Sometimes, when your server is not configured to interpret PHP, you will see PHP code in page source in browser. But it still won't work, because no browser supports PHP.
PHP is a server side language, so the code that your browser will "receive" will contain nothing related to PHP. What will happen is that this PHP file will be parsed and executed still in the server, and your browser will get only the following code:
<script>
function echoHello(){
alert("hello");
}
</script>
<button onclick="echoHello()">Say Hello</button>
which is the result of your server's PHP execution. This might be just what you expected in this particular case, but what if we wanted to pass parameters to echoHello function?
<script>
function echoHello(speech){
alert("<?PHP hello(speech); ?>");
}
</script>
<?PHP
FUNCTION hello($speech){
return $speech;
}
?>
<button onclick="echoHello('hello')">Say Hello</button>
<button onclick="echoHello('bye')">Say Bye</button>
One could expect this to alert 'hello' when the user clicks the first button, or 'bye' for the second one. This is not true, as the server starts executing this code before the buttons even exist (as they will only exist when the browser downloads the processed document to render the elements), and thus won't even be able to execute echoHello since speech isn't a valid variable. For this case and many others, AJAX is indeed the most appropriate way to go.
This tutorial should be good for a start.

Calling a PHP function through an HTML Link (no form)

I have a PHP Function that I would like to integrate into my (existing) web page. Further, I would like it to execute when the user clicks a link on the page. The function needs to accept the text of the link as an input argument.
Everything I've researched for sending data to a PHP script seems to involve using forms to obtain user input. The page needs to accept no user input, just send the link-text to the function and execute that function.
So I guess the question is two-part. First, how to execute a PHP script on link click. And second, how to pass page information to this function without the use of forms. I am open to the use of other technologies such as AJAX or JavaScript if necessary.
EDIT:: Specifically what I am trying to do. I have an HTML output representing documentation of some source code. On this output is a series of links (referring to code constructs in the source code) that, upon being clicked, will call some python function installed on the web server (which leads me to think it needs called via PHP). The python function, however, needs the name present on the link as an input argument.
Is there some sort of interaction I could achieve by having JavaScript gather the input and call the PHP function?
Sorry for the vagueness, I am INCREDIBLY new to web development. If anything is unclear let me know.
You'll need to have a JS function which is triggered by an onclick event which then sends an AJAX request and returns false (so it won't be redirected to a new page in the browser). You can do the following in jQuery:
jQuery:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("myfile.php");
return false;
}
</script>
And in your page body:
Click Me!
In myfile.php:
You can add whatever function you want to execute when the visitor clicks the link. Example:
<?php
echo "Hey, this is some text!";
?>
That's a basic example. I hope this helps.
You will need to use AJAX to accomplish this without leaving the page. Here is an example using jQuery and AJAX (this assumes you have already included the jQuery library):
First File:
<script language="javascript">
$(function(){
$('#mylink').click(function(){
$.get('/ajax/someurl', {linkText: $(this).text()}, function(resp){
// handle response here
}, 'json');
});
});
</script>
This text will be passed along
PHP File:
$text = $_REQUEST['linkText'];
// do something with $text here
If you are familiar with jQuery, you could do the following, if you don't want the site to redirect but execute your function:
in your html head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
the link:
Execute function
in ajax.php you put in your function to be executed.
Maybe something like this:
....
<script>
function sendText(e)
{
$.ajax({
url: '/your/url/',
data: {text: $(e).html()},
type: 'POST'
});
}
</script>
You can use query strings for this. For example if you link to this page:
example.php?text=hello
(Instead of putting a direct link, you can also send a ajax GET request to that URL)
Inside example.php, you can get the value 'hello' like this:
<?php
$text = $_GET['hello'];
Then call your function:
myfunction($text);
Please make sure you sanitize and validate the value before passing it to the function. Depending on what you're doing inside that function, the outcome could be fatal!
This links might help:
http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
http://phpmaster.com/input-validation-using-filter-functions/
Here's an overly simplistic example of what you're trying to do..
Your link:
Some Action
Your PHP file:
<?php
if (isset($_GET['action']))
{
// make sure to validate your input here!
some_function($_GET['action']);
}
PHP is a server side language i.e. it doesn't run in the web browser.
If you want a function in the browser to operate on clicking a link you are probably talking about doing some Javascript.
You can use the Javascript to find the text value contained in the link node and send that to the server, then have your PHP script process it.

Cannot get .ajax to call my php script

for the life of me I cannot get my PHP file to be called using the ajax function. Here is my relevant HTML:
$(document).ready( function(){
$("#generate").click(function(){
alert("Been clicked");
$.ajax({
url: "filterScriptForMe.php",
success: function(data){
alert("response");
}
});
});
});
Here is my PHP file, which I can run by calling separately, and will print to the error log/echo/create the necessary image no problem when run on it's own:
error_log("script has been called");
$hello = imagecreatefrompng("./images/stock.png");
$hello = imagecreatefrompng("./images/stock.png");
imagealphablending($hello,false);
imagesavealpha($hello,true);
$x=imagecolorallocatealpha($hello,0,0,0,127);
$color = imagecolorat($hello,350,500);
for($y=0;$y<512;$y++)
for($z=0;$z<597;$z++)
{
if($color!=imagecolorat($hello,$y,$z))
{
imagesetpixel($hello,$y,$z,$x);
}
}
imagepng($hello,"done.png");
echo "done";
I am beginning to wonder if there is a problem on my server at this point. When run it will print the first alert saying "been clicked" but it does not seem to be running the php script as I get no output to my log files when clicking the button from the html file, as opposed to visiting the php directly in the broswer. Both the html and php are in the same directory, and I have double checked the names to make sure they are correct.
I know other jQuery functions are working on the page as well, as I've been successful in getting some jQueryUI elements to display and respond to manipulation using jQuery alone. Added to that the first alert seems to be firing, so I'm fairly sure the library/code is in there. I've tried going through with firebug, but it's a little beyond me when it starts getting deep into the library and I lose track of what's being done and why.
Any help that you can provide would be much appreciated, at least to get the PHP file called from the html page. Thanks!

php ajax within ajax

I have some ajax that loads php script output into a div. I would like the user then to be able to click on links in the output and rewrite the div without reloading the whole page. Is this possible in principle? Imagine code would look like:
html
<div id="displayhere"></div>
php1 output
echo 'ChangeToNew';
JS
function reLoad(par1,par2,par3) {
...
document.getElementById("displayhere").innerHTML=xmlhttp.responseText;
xmlhttp.open("GET","php2.php?par1="+par1 etc.,true);
xmlhttp.send();
php2
$par1 = $_get['par1'];
change database
echo ''.$par1.'';
Could this in principle work or is the approach flawed?
Thanks.
What you describe is standard, everyday AJAX. The PHP is irrelevant to the equation; the JS will simply receive whatever the server sends it. It just happens that, in your case, the server response is being handled by PHP. The JS and PHP do not - cannot - have a direct relationship, however.
So the principle is fine. What you actually do with it, though, will of course impact on how well it works.
Things to consider:
what will the PHP be doing? This may affect the load times
what about caching responses, if this is applicable, so the PHP doesn't have to compute something it's previously generated?
the UI - will the user be made aware that content is being fetched?
Etc.
I'm used to using jQuery so will give examples using it.
If you create your links as
Click Me
You could then write your code as
<script>
$("#do_this").live('click', function(){
var link_url = $(this).attr('href');
$.ajax({
url: link_url,
success: function(data) {
$('#displayhere').html(data);
}
return false;
};
</script>
If you use jQuery, make sure you use the .live('click', function(){}) method versus the .click(function(){}) method, otherwise it won't recognize dynamically created elements. Also make sure you do a return false.

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

Categories