This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
Currently I have the following but it doesn't like me very much:
1. index.php:
<!DOCTYPE html>
<html>
<body>
<div id = "bookList">
<?php
include("list.php");
?>
</div>
</body>
</html>
2. list.php:
<?php
echo '<button id = "read">Read</button><br><br>';
echo
"<script type=\"text/javascript\">
$(\"#read\").click(function()
{
alert(\"<?php display(); ?>\");
});
</script>";
function display()
{
echo "hello";
}
?>
As is hopefully obvious from the code I posted above, I am attempting to create a button using php which when clicked on will in turn call a php function. I have not been successful as of yet. Any advice will be appreciated but I'd like my code to stay as close to what I currently have as possible.
Some basic misunderstandings here. PHP and Javascript does not interact like that
Let me give a rather silly analogy:
You go to the coffee shop and order some coffee.
The shop keeper gives you the coffee. You take a sip and find you need more sugar
You tell the shopkeeper who adds the sugar to your coffee. Lets call this action addSugar().
Everything is cool here. Now what happens in this second scenario:
You go to the coffee shop and order some coffee.
The shop keeper gives you the coffee. You take the coffee with you and walk home
You take a sip and find you need more sugar
You tell the shopkeeper to addSugar()...? erm...
Well the shopkeeper aint there. In the same way, when a page reaches your browser, it has left the coffee shop. There is no PHP/shopkeeper around anymore
Your request to addSugar() that you are trying on button click using Javascript will not work.
What you will need to do is use something called AJAX which is a way to quickly run to the coffeshop just for adding a little sugar.. Its a broader topic and you will need to read about it, but there are tons of resources out there..
Related
First, I want to apologize if this is somewhere else. I'm looking for something simple. I have a PHP script that uses glob to retrieve a list of files from a directory. The directory is determined by a request sent though the address bar. ie. http://somewebsite.com/?loc=mydirectory
I'm looking for a way to create a button that you can click on and the file list will display without refreshing the page.
Here is the PHP code.
<?php
$BaseLoc='./';
$SecLoc='archives';
$FullLoc=$BaseLoc.$SecLoc.'/';
$loc=$_GET["loc"];
parse_str($_SERVER['QUERY_STRING'], $urlparams);
$GFloc=$urlparams['loc'];
function DirList() {
global $FullLoc;
$DirList=glob($FullLoc.'*',GLOB_ONLYDIR);
foreach ($DirList as $dirlist) {
$edl=explode ('/',$dirlist);
$dirlist=end($edl);
echo '<li>'.$dirlist.'</li>';
}
}
function ListFiles($GFloc){
global $FullLoc,$GFloc;
$FileLoc=$FullLoc.$GFloc;
$FileList=glob($FileLoc.'/*');
foreach ($FileList as $filelist) {
echo $filelist.' - '.$GFloc.'<br />';
}
}
?>
keep in mind that this is a test project for the purposes of getting a handle on how to do this type of AJAX. I know there is some Jquery with .get and I could have sworn I'd done this before but for the life of me I just can't seem to wrap my head around it. I know it's got to be something simple with a button click and then write the result into a div. Any help would be appreciated or even a link to an answer that I missed.
Thanks.
I'm editing this on 1-28-2017 to try and clarify what I'm attempting to do.
With the current php code above. When this .php page is visited it generates a list of sub-folders inside a folder and turns that list into clickable links. Inside each of those sub-folders is a group of media files. Currently if I click on one of the now generated sub-folder links. The entire page refreshes and I get a display of all the files inside that sub-folder. This is done by using php get and a variable inside the url. The only thing I 'm trying to change is that I get the same result, without refreshing the page. If you want to see an example of this functionality as it currently is, you can go to my test page. http://testbed.myreth024.tk/ajax/ I keep thinking it's something simple with the jquery .get. I just can't seem to find a good example of how to pass those url parameters through. Anyway. Thanks again for all the responses.
<button type="button">Click Me</button>
<div id="iamdiv"></div>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){ //you can use class(with .yourclass) or id(with #yourid) instead of button if you need to be.
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
alert(data);
$("#iamdiv").html(data);
}
});
});
});
</script>
In script.php
<?php
echo "You win";
?>
I hope that helps cheers!
I want to thank everyone for their time and input. I want to point out that I feel as programmers we have a tendency to over-complicate things. Eventually I arrived at a solution to this question. It's entirely possible I didn't ask the question as clearly as I could have. Before I post the code let me walk through the basics of what occurs. Hopefully this will help someone else who is looking for a similar solution.
The index page opens and the php code executes and generates a directory listing. Each of the directory names is clickable through javascript. When a directory is clicked, the space below the directory listings displays a list of files in that directory.
Here is the index file:
<style>.menu{cursor:pointer;padding:1%;float:left;}</style>
<?php
$loc=$_GET["loc"];
function DirList() {
global $loc;
$dlist=glob("./files/*",GLOB_ONLYDIR);
$dend=$dlist[0];
$dende=explode ('/',$dend);
$default=end($dende);
foreach ($dlist as $Dlist) {
$edl=explode ('/',$Dlist);
$DList=end($edl);
echo '<div class="menu" id="'.$DList.'">'.$DList.'</div> ';
}
if(!$loc){header("Location: ?loc=".$default);}
}
?>
<p></p>
<div><?php DirList();?></div>
<div><div id="flist" style="clear:both;border:1px solid black;min-height:25px;"></div></div>
<p></p>
<script type="text/javascript">
$(".menu").click(function() {
var dloc=this.id;
$.get("file-list.php?loc="+dloc,function(data) {
$("#flist").html(data);
});
});
</script>
Then I have a file-list.php for the purposes of generating the list of files.
<?php
function FileList() {
$loc=$_GET["loc"];
$dloc = "./files/".$loc.'/';
$flist=glob($dloc.'*');
foreach ($flist as $fList)
{
$efl=explode ('/',$fList);
$FList=end($efl);
echo '<div style="padding:1%;width:45%;margin:0px auto;">'.$FList.'</div>';
}
}
FileList();
?>
Ultimately what I was missing was how I could take the data and put it into a div. When creating my links, I used the css id to store the directory name as well. This allowed me to reference it more easily in the code. Ultimately it was essentially about retrieving the "data" from the file-list.php and then simply writing that "data" into the div with the jquery .html. It ended up being a simple .get command which if I understand it, is a jquery ajax solution. If anyone has any questions or comments on how I could have asked the question better or ways to improve the code, feel free to let me know. I'm still learning some of this and I'm always open for improvement.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
So now i now this was a dumb question but does anyone now the best way to solve it without an ajax request, becaus I think it would be stupid to make a new file for just one line of code
I am making a gallery and I want two types of views one grid-view and a slide view. My slide and my grid view both work but they stand in different files. So I wrote a simple jquery function to load some php code into the html code. So that when I click a button the html code dissappears and there is php code. The jquery funtion works but the problem is that when the code is changed it doesn't recognise it as php code but just as a string.
This is what I see, you can see the text but it needs to execute that code:
Here is the jquery function:
$(document).ready(function(){
$("img.grid_icon").click(function() {
$(".werkvenster").html("<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>");
})
});
I use the < and >, otherwise the browser sees it as php code it has to execute instead of seeing it as a string.
Here is the html code it has to be in:
<body>
<section class="werkvenster">
<img src="img/website/icon_grid.png" height="30px" class="grid_icon">
<div class="galerij" id="galerij">
</div>
<button class="omlaag" id="galerij_knop">Terug</button>
<button class="omhoog" id="galerij_knop">Verder</button>
</section>
</body>
So everything between the section tags with class "werkvenster" needs to be changed by
<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>
When someone clicks on the grid icon.
Thanks a lot in advance and please don't mark this as a duplicate because I have been searching for over an hour to find an answer to this question.
It seems you need some clarification how PHP and JS work.
a) PHP-code is executed on the server-side. all of it. and nothing else
b) The output, completely free of PHP, is sent to the browser
c) JS-code is executed on the client-side. all of it. and nothing else
If you use JS to write PHP-code, it only happens inside the browser, which doesn't know what to do with it. and long after every bit of PHP-execution.
You do NOT write anything back to the server with this.
what you CAN do is to do an AJAX-request to a specific PHP file that returns your desired output. but you can't just mix JS and PHP like that. it just doesn't work.
edit: in response to your edit about how to solve the problem without using AJAX
to put it simply: not at all. you have to get the data from the server, the best way to do this is AJAX (it was made for this and nothing else) and on the server you have to generate the data somehow. and the cleanest way is a new file.
it doesn't recognise it as php code but just as a string
That's because it is a string:
"<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>"
PHP doesn't run in the browser, it runs on the server. By the time the page is delivered to the browser, the PHP code has executed and completed and produced its output. PHP is no longer involved after that point.
If you want to execute code client-side, that's what JavaScript is for. If you need code to execute server-side, the browser will have to make a request to the server to make that happen. A page load, a form post, AJAX, etc. They all take the form of an HTTP request (potentially with some data sent to the server) which invokes a PHP script and receives that script's output as the response.
You could do what you are trying to do without ajax. You just have to create a hidden <section> that contains the php code (which you have to do on the server-side before it gets sent to the browser). And then in the browser, use jquery to get the contents from the hidden <section> (or just swap the sections)
Here is an example:
Server-side PHP:
<body>
<section class="werkvenster">
<img src="img/website/icon_grid.png" height="30px" class="grid_icon">
<div class="galerij" id="galerij">
</div>
<button class="omlaag" id="galerij_knop">Terug</button>
<button class="omhoog" id="galerij_knop">Verder</button>
</section>
<section id="hiddenStuff" style="display:none">
<?php include_once('resources/UberGallery.php'); $gallery = UberGallery::init()->createGallery('img/gallerij/'); ?>
</section>
</body>
jQuery:
$(document).ready(function(){
$("img.grid_icon").click(function() {
$(".werkvenster").html($("#hiddenStuff").html());
})
});
I would like to know if something like this is possible for php:
Very-Pseudo-Code:
<body>
<textarea name="text1">
</body>
<?php
$A=mysqli_connect(...);
if($A){**text1.echo "Connection established";**}
$B=mysqli_select_database(...);
if($B){**text1.echo "Database selected";**}
?>
I want a life feedback that tells the user what is going on in the background. Kind of a life feed that consistently gives the user information. I played around with GET and POST methods and also with PHP_SELF, but nothing worked out.
In javascript it seems to be quite simple with something like
document.myform.append()
Is there something like this for php, or do i have to mix it with javascript?
(This is my first html/php project, i hope its not a silly question)
I have a site that has voting on the front page node, and I need to update a view on the same node after each vote. I'm currently using the following code in my page.tpl.php
<script type="text/javascript">
function fivestarResult(voteResult) {
$('div#fivestar-summary-'+voteResult.vote.id).html(voteResult.result.summary);
window.location = "http://www.mydomain.com/";
};
</script>
Is there a way to directly refresh the view instead of refreshing the whole page? I'm not very good in javascript so I'm a little lost.
An idea i may do in this kind of situation is to Ajax call the view again and render it inside the page again via JQuery on click event.
take this example , i guess this will clarify more
Drupal 6: Render Views 2 data in a page tpl file
Thanks Rabe,
That sounds like it should work. I tried it a few different ways but couldn't get it to ...
Is there something obvious I could be missing from this code (in page.tpl.php)?
<script type="text/javascript">
function fivestarResult(voteResult) {
$('div#fivestar-summary-'+voteResult.vote.id).html(voteResult.result.summary);
<?php
$name = "comparison_view";
print views_embed_view($name, $display_id = 'default');
?>
};
</script>
Thanks a lot for the help
Like many things in Drupal, there may be a module already written to do this. Ajax views refresh sounds very promising!
I have spent countless hours debugging a view only to realize I had caching enabled and was looking at old results. The caches for different user groups are separate as well. So you may need to manually flush cache to get this to update, which might be a challenge with Ajax.
This question already has an answer here:
how do i write a javascript alert box to give a yes or no question and integrate with php calls?
(1 answer)
Closed 7 years ago.
I'm reposting this post I just posted a while ago.
how do i write a javascript alert box to give a yes or no question and integrate with php calls?
I wasn't getting any more responses, so I figured the post got lost in somewhere out there.
what I tried doing was this
<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) {
<?php
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>
}
</script>
and it didn't work. the record just got deleted once I pressed the link to delete.
what am I doing wrong? thanks
ps: I cant do ajax yet I'm looking for a simple way of doing it so I can comprehend how it works
thanks
You cannot use JavaScript to control the flow of PHP code in the way you've provided. The reason the record is always deleted is because the PHP interpreter kicks in as soon as it sees the <?php identifier, so the statement will always be executed.
I would try something like this:
Use a standard form and the post method to submit the id of the record to be deleted
Use JavaScript to enhance the form; bind to the submit event and then you can ask for confirmation, only allowing the form to submit if they say okay.
In this way, the JavaScript enhances functionality and it will degrade gracefully. You'll still have to implement all the business logic of deleting the row from the PHP script that handles the form submission.
From what I can gather you are failing to understand that PHP runs on the server while Javascript runs on the client. Follow #Peter's advice, also read and learn more before diving head first into it and coming up with weirdness like that. A rudimentary fix would be something like:
<script type="text/javascript">
function deleteRecord(id) {
if(window.confirm("Are you sure you want to delete that record?")) {
window.location.href = 'myScript.php?id=' + id;
}
}
</script>
In your myScript.php:
<?php
$id = $_GET['id'];
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>
you can use something like this:
<script type="text/javascript">
function askUser() {
return window.confirm("Are you sure you want to delete that record?");
}
</script>
and then in your html:
delete record
of course you need to create a file delete.php which handles all your logic for deleting.
ps. in real life you should avoid inline javascript, i'm just using it here for this short example