Calling JavaScript within Php block and vice-versa - php

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>

Related

php variable pass to java script and alert it

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>

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.

Using javascript function and variables in combination with PHP and MYSQL

On my page I have a search result that contains a list with users where each is followed by an "addfriend" button. Each row contains a username and userID. Meanwhile the ID of the user that requested the searchresult is stored in a Session variable.
When the addfriend-botton is clicked the following 2 things should happen:
Store the userID and $_SESSION['userID'] is a MySQL table which describes the relationship.
Do NOT refresh the page (this the core of my problem) but stay focussed and change the state of the button to e.g. "friend request send". I'm thinking of GetElementByID().style method.
I was thinking of this:
<a href="#" onClick="addFriend('<? echo $_SESSION['userID'];?>','<? echo $rij['userID']; ?>')">
which calls the javascript function addfriend
I was hoping to catch the two ID's like this:
<script>
function addfriend(id1, id2)
{
//server side php code where I use value of
//the client-side javascript variables: +id1+ and +id2+ .
}
</script>
Is this at all possible or I'm I thinking the wrong way? Any suggetions on how to accomplish this?
You are in the right way, inside your addFriend() function, you can call one php file (via AJAX) and send the IDS without refresh the page. I think better you work with Jquery in this case, something like this:
<script>
function addfriend(id1, id2)
{
$.ajax({
type: 'POST',
url: 'yourPHPfile.php',
data: { your_id_1:id1, your_id_2:id2 },
success: function(data){
if(data){
alert('Done!');
}
},
dataType: 'text'
});
}
</script>
And in your PHP File you can do this:
<?php
//receive Ids
$id1 = $_POST['your_id_1'];
$id2 = $_POST['your_id_2'];
//do something here
echo "OK!";
<?
to do this work you need download and add the jQuery plugin in your page, rather into head tag
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
Good work and don't give up! (:
You can do this using AJAX (asynchronous JavaScript and XML), which is really just a fancy term for "sending stuff to a server with JavaScript and getting a response back, without reloading the page". There's nothing special about AJAX; it just involves using plain old JavaScript to send an HTTP request.
Check out jQuery, a JavaScript library that handles most of the technical stuff for you. Specifically, look at its post() function, which allows you to send data to a PHP script using the $_POST system variable. There are lots of clear examples on that page.
Note that you don't need jQuery to use AJAX; jQuery is just a library that makes things easier. If you really want to learn how the JavaScript side of AJAX works, try following one of the many tutorials out there, such as Mozilla's or this one.
AJAX is the answer you're looking for.
It sounds like you already have a basic understanding of this, but to clarify, Javascript executes on the client side, and PHP executes on the server side. So you would have to make a call back to your server in order to interact with PHP/MySQL.
The purpose of AJAX is to do this without requiring a page refresh.

Trying to toggle divs with JS after calling a PHP script

I am wondering whether this is possible:
I have a page. The user clicks a link and that calls a PHP script. The PHP script returns true or false.
Depending on the true or false, I was hoping to be able to toggle a div.
I am wondering whether I need to do it the AJAX way? How do people usually accomplish this?
Seems pretty common.
I am using this YUI library already:
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.8.2r1/build/reset-fonts-grids/reset-fonts-grids.css&2.8.2r1/build/base/base-min.css">
jQuery:
$.post('/path/to/url', {data: 'some data'}, function(data) {
if (data) $('#some-div').show();
else $('#some-div').hide();
}, 'json');
PHP:
echo json_encode(true);
For more information see:
http://api.jquery.com/category/ajax/
http://php.net/manual/en/function.json-encode.php
Yes, you should use AJAX to create a good flow in your site. Instead of implementing your own AJAX handling functions, you could use one of the big JavaScript frameworks, I recommend http://jquery.com/. There, you can read about (and see examples of) jQuery.ajax - http://api.jquery.com/category/ajax/.
This should get you started, but the main idea is to bind that link to an AJAX function, that will call your PHP script, and based on the contents of the returned data, toggle your DIVs on/off.
Good luck!
Set the php script to add a hidden field ... such as...
<input type="hidden" id="passed-value" value="passed-val-is-true" />
Then in your Javascript when you fire the toggle event .. check that element ...
In jQuery would be something like this ...
$foo.click(( if (passed-value.value === "passed-val-is-true") { foo.toggle(); }
Sorry for syntax .. but you should get the general idea.
Also, if you need it to do without page reload, i would def recommend Ajax (pref via jQuery)
Yes, very easy, no need for Ajax. Here's two ways:
Using straight PHP:
<?php
if($test) {
echo "<div>Content...</div>";
}
?>
Or, using inline Javascript (in the PHP script), assuming you have a <div id='targetDiv'> in your HTML, and a $testVar in your PHP:
<script type='text/javascript'>
function toggle(testVar) {
if(testVar) { document.getElementById('targetDiv').style.display = ""; }
else { document.getElementById('targetDiv').style.display = "none"; }
}
window.onload = function() { toggle(<?php echo $testVar; ?>); }
</script>
The second method can be easily altered to degrade gracefully.

How do I call a php function from javascript onclick() event?

For example, I have a php function:
function DeleteItem($item_id)
{
db_query("DELETE FROM {items} WHERE id=$item_id");
}
Then, I have something like the following:
<html>
<head>
<script type="text/javascript">
function DeleteItem($item_id)
{
alert("You have deleted item #"+$item_id);
}
</script>
</head>
<body>
<form>
Item 1
<input type="button" value="Delete" onclick="DeleteItem(1)" />
</form>
</body>
</html>
I want to be able to call the PHP function DeleteItem() from the javascript function DeleteItem() so that I can use Drupal's db_query() function, so I don't have to try to establish a connection to the database from javascript.
Does anyone have any suggestions on how this might be done? P.S. I understand that PHP processes on the server-side and javascript processes on the client-side, so please no responses saying that. There has got to be some kind of trick one can do in order to have this work out. Or maybe there is a better way of doing what I am trying to accomplish.
Since you are aware that PHP processes on the server-side and javascript processes on the client-side, you must also realize you can't call a PHP "function" from javascript. Your client side code can redirect to a PHP page, or invoke a PHP program using AJAX. That page or program must be on the server and it should do a lot more than just the one line you have in your function. It should also check for authentication, authorization, etc. You don't want just any client side script anywhere to call your PHP.
You need to write a PHP script which will execute the function. To call it, either:
use XMLHttpRequest (aka Ajax) to send the request
change the page's location.href and return HTTP status code 204 No Content from PHP
You will want to use ajax for that.
Also, database connection from within javascript is something you should not even consider as an option - terribly insecure.
A very simple example:
//in javascript
function DeleteItem($item_id) {
$.post("delete.php", { id: $item_id}, function(data) {
alert("You have deleted item #"+$item_id);
});
}
//in php file
db_query("DELETE FROM {items} WHERE id=" . $_REQUEST["id"]);
you can't actually call PHP functions within JavaScript per se. As #Christoph writes you need to call a PHP script via a normal HTTP request from within JavaScript using the magic that is known as AJAX (silly acronym, basically means JS can load external HTTP requests on the fly).
Take a look at jQuery's AJAX functionality on how to reliably make a HTTP request via JS, see http://docs.jquery.com/Ajax
All the normal security rules apply, i.e. make sure you filter incoming data and ensure it's what you're expecting (the $item_id in your example). Bear in mind there's nothing to stop someone manually accessing the URL requested by your JS.
First, use jQuery.
Then, your code will have to be something like:
<input ... id="item_id_1" />
<script>
$(document).ready(function() {
$('input').click(function(){
var item_id = $(this).attr('id');
item_id = item_id.split('_id_');
item_id = item_id[1];
$.get('/your_delete_url/' + item_id);
});
});
</script>

Categories