PHP Script in OnClick Event - javascript

This IS a duplicate from Calling a php function by onclick event, but I have a question on it. The answer I had a question on is by timpanix, and basically it won't work.
He said to execute some PHP code in a On Click event do this:
onclick="document.write('<?php //call a PHP function here ?>');"
and call the PHP function. Yet whenever I try it:
<button id="profileinformationbutton" input type="submit" value="Login" onclick="document.write('<?php profileupdated() ?>');"> Update Profile </button>
it prints out ');" > Update Profile, yet I have no clue why. It is inside of a form, and the PHP function looks like this:
<?php
function profileupdated() {
?>
<div id="profileupdated"> Profile Updated </div>
<?php
}
?>
Why would the code be displaying this? Please help! :) Thank You.
EDIT
The code does not seem to be writing Profile Updated to the page, any idea why?

function profileupdated() {
echo "<div id='profileupdated'> Profile Updated </div>";
}
Also if you only want to print this value to your tag why you're using function? Assign it to a variable.
like
$myVar = '<div id="profileupdated"> Profile Updated </div>';
Then use this variable where you want?
you should echo or return your function body. Carefull! I changed quotes!

Your PHP function is writing to the page already, rendering the document.write (javascript) useless. Try this:
<?php
function profileupdated() {
return "<div id='profileupdated'>Profile updated</div>";
}
?>
I do want to note though that you might want to consider a cleaner way of doing this: If you just want to display a fixed text ("Profile updated"), stick to pure client-side Javascript.
Otherwise (if there's logic to be done server-side), you might want to decouple server and client and use an AJAX call and JSON to transfer your data.

PHP is a server side programming language, you are executing the JavaScript on the client side.
If you want to call a PHP script from your JavaScript you need Ajax, f.e. jQuery.

Related

using ajax to pass string from php to javascript

So I have a piece of javascript code in an html document that responds to a button click. I want a new url to open, and if I specify the link in javascript as I've done below, everything works fine.
<input type="submit" id="submitbtn" value="Purchase Module"/>
<script type="text/javascript">
document.getElementById("submitbtn").addEventListener("click",handle_click);
function handle_click() {
var link;
link="http://www.google.com";
window.location.href=link;
}
</script>
Problem is I want to hide the real link on the server side as it includes a username:password. The php script below calls a function (not shown) that generates the link (a string). This also works fine.
<?php
$link=get_page_link();
?>
I want to pass the link string to the javascript and have tried various iterations of
link=<?php echo $link ;?> to no avail. As I understand it you can't pass strings this way and you need to use ajax. That's where I'm stuck. Seems like I need a $_POST on the php side and a $_GET on the java side, but not sure on the specifics. Any help would be appreciated. Thanks.

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

how to call php function through hypertext link

I want to call a PHP function passing an argument on clicking a hyperlink (text with <a> tag) on the same page, i.e. href='#' onclick='loadpic($id).
Where $id is the variable to be passed to PHP function.
You can do that by ajax easily. Create a loadpic function in javascript instead and then pass $id to the php file via ajax and do something when you get the result.
Your javascript file should look like this-
(make sure you've inserted a link for jquery in your index file)
function loadpic(id_param){
$.post("filename.php",
{
id: id_param
},
function(data){
alert("Data received:" + data);
});
};
The data parameter in function(data) would be the value that you've echoed in the php file.
If you want to use onclick() method in your HTML element then you have to write your method is javascript and make an AJAX call to PHP. THis is one simple way to do this using php and javascript. And for this please see javascript and ajax with PHP.
But if you dont want to use javascript then here is a simple way and very simple code.
<?php
if(isset($_GET['myMethod'])){
myMethod($_GET['id']);
}
function myMethod($id){
echo $id."<br>";
}
?>
<?php
$myId = 4;
?>
<a href="index.php?id=<?php echo $myId ?>&myMethod" >MyLink</a>
Note: Copy this code and paste into a file called index.php because notice the hyper link tag and its attribute href="index.php".
Also note that you can not directly call php method using js like onclick() from your HTML tag. You should use AJAX or something. But using above demo code you can easily call myMethod() which is a PHP method using the hyper link tag.
In your case:
<?php
if(isset($_GET['call_loadpic'])){
loadpic($_GET['id']);
}
function loadpic($id){
echo "My loadpic method has been called! and the id is".$id."<br />";
}
?>
<!-- your other codes -->
<?php
$id = 4;
?>
<a href="this-same-file-name.php?id=<?php echo $id ?>&call_loadpic" >MyLink</a>
This is because your php function is in the same page and you want to call that function using same file and hyperlink in the same file. (According to your question)
You still will have to make javascript handle the exception because php has no onclick.
onClick=\"loadpic("'.$id.'");"\
//this will only send a php variable javascript will still have to loadpic();

need javascript or jquery function to wrap php code (window.setInterval bootstrap list group)

Thanks for all the answers, seems like AJAX is the solution, I'll give it a try. But what about JSON? Isn't JSON an even better solution? If it is, why is AJAX more preferable?
I'm looking for a way to update this part of php code every 5 seconds, which would regenerate this bootstrap list group. what would be a good way to do it? I figure I couldn't just wrap it in window.setInterval, and refreshing the entire page is not an option. Thanks in advance.
<?php
$i=0;
// Display all room
foreach ($rooms as $room) {
$room_num = $room['room_num'];
$room_type = $room['room_type'];
$note = $room['note'];
echo '
<a class="list-group-item" >
<h4 class="list-group-item-heading" id="room_num' .$i. '" ><p>'.$room_num." - " .$room_type.'</p></h4>
<p class="list-group-item-text" id="note' .$i. '" ><p>'.$note.'</p></p>
</a>
';
$i++;
}
$rooms = "";
getList();
?>
All on the same 'page.php'
php part:
<?
if ($_POST["whatever"])
{
echo 'your shizzle here'
exit;
}
?>
Javascript part: (with jquery)
<script>
setInterval(function()
{
$.post( "page.php", { whatever: 1}, function( data ) {
document.getElementById('someid').innerHTML = data;
});
},5000);
</script>
html part
<div id = "someid"></div>
Another way to do it could be using an iframe :) But iframes won't be used in the future I think.
Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)
So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.
In your case, Save the PHP code which ever you want to execute in a file say php_temp.php
Now just do
setInterval(function(){
$.get("php_temp.php", function(data){
console.log(data) // data stores whatever php_temp.php echoes
});
},5000);
more on Ajax: Ajax Basics

How do I embed Javascript in PHP code?

I have a HTML form and PHP code. In my form, I have a textbox and a textarea. Within both, I have included the "disabled" option. I want both textboxes to remain disabled until the user decides to click the "Edit" button, in which case both textboxes should be enabled so changes can be made and the output once again saved. According to the research I have done, the only way to do this is to use javascript, so I have included the following code within my PHP;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "var oldnotes = document.getElementById('oldnotes');";
echo "oldnotes.disabled = false;";
echo "var record = document.getElementById('record');";
echo "record.disabled = false;";
echo "</script>";
}
I have also tried;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "$('#oldnotes').removeAttr('disabled')";
echo "$('#record').removeAttr('disabled')";
echo "</script>";
}
But no luck :(
I am not receiving any errors, the textboxes just remain disabled after I click the Edit button. Could anyone help me with this? Thanks in advance.
This is a better approach for these kind of problems :
if (isset($_POST['edit'])){
?>
<script type="text/javascript">
var oldnotes = document.getElementById('oldnotes');
oldnotes.disabled = '';
var record = document.getElementById('record');
record.disabled = '';
</script>
<?php
}
<?
<script language='javascript'>
(javascript code here)
</script>
?>
Try use onclick on your Button
<input type="button" name="edit" id="edit" onclick="document.getElementById('oldnotes').disabled=false; document.getElementById('record').disabled=false; return false;">
I hope it helps.
The second approach seems correct, but you're missing ; there. Also, you haven't put any newline characters.
Here's what I suggest:
<?php
if (isset($_POST['edit'])) {
?>
<script type="text/javascript">
alert("Check entry"); // Use this for checking if your script is reaching here or not
$('#oldnotes, #record').removeAttr('disabled');
</script>
<?php
}
?>
You don't need to echo the whole thing. You can simply put it out of the PHP and keep it inside a if block.
Also, I've kept the alert to check if your code structure is proper. If you're getting the alert on clicking the edit button, means you're on the right path. You just need to workout on the JS.
If not, something wrong with your edit button and the form POST
Use single quotes for script type
echo "<script type='text/javascript'>\n";
//javascript goes here
echo "</script>";
use this jquery code:
<script>
$('#oldnotes,#record').attr('disabled','')
</script>
If you want to use JS with PHP you can read here:
how to write javascript code inside php
However: it seems you want the JS to be called on it own accord upon evaluation in the php logic as per the implementation provided.
Technically speaking your JS simply states it should re-enable the controls. Rather add the JS functionality to the OnClick of the submitting control and it should work fine. This is a quicker way of testing the functionality as well.
<a href="javascript:void(0);" onclick="document.getElementById('oldnotes').disabled=false;" >
Once it is clicked it will hide the appropriate control instead of trying to write new JS on the fly that is not executed. This is tried and tested and should work fine for you.
Hope it helps!
you can always make a cookie
use document.cookie()
set the onclick=“” to changing the cookie
and make a script that runs and gets the cookie when you open the site (use window.onload = function(){/*code goes here*/})

Categories