Loading PHP function using jQuery onclick - php

I am trying to hide our mailing address on our website, until someone cliks a button to "load" the address. I am doing it like follows:
Homepage.php:
<button onclick="test()"> Click </button>
<div> </div>
<script>
function test(){
$.ajax({url:"address.php", success:function(result){
$("div").text(result);}
})
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Address.php:
<?php
function php_func(){
echo '<span><?php echo $address; ?></span>';
}
php_func();
?>
This works in echoing the text onto homepage.php, but it's not loading the PHP function. Just showing the function as text as seen here:
I tried $("div").write(result);} and it won't even load.
$address is already defined elsewhere. Any tips?

You're trying to write code which outputs code which outputs the address. Why? You're already in the context of outputting something from the PHP code:
echo "something...";
If what you want to output is the value of $address then just output that:
echo "<span>$address</span>";
I suspect the reason you did it that way is because you're expecting the currently loaded page to parse and execute that PHP code. This is a fundamental misunderstanding of how these technologies work. The PHP code for that page executed once, on the server, and delivered the resulting HTML/CSS/JavaScript to the client.
The AJAX operation is making a new, separate request to another PHP resource which will execute on the server and output back to the client. In this case it's just outputting a string value, which the client-side JavaScript code will then write to an element on the page:
$("div").text(result);
(This is a good opportunity for you to use your browser's debugging tools and observe the AJAX request/result in the network tab, to see what's actually being sent/received. At no point should actual PHP code be visible to the browser. All of that is executed on the server.)
The reason this is important is because, if this is the case, then you are likely misunderstanding where $address is defined. If it's defined in the PHP script which rendered the page you're looking at, that doesn't mean it's defined in address.php. If the code you're showing us for address.php is the entirety of that page then $address is not defined.
So you'll need to define $address on that page.
After having said all of that... You might find it much easier not to involve AJAX for this at all in the first place. Just output the address to the page but style the <span> to not be visible. Then when the user clicks the button, make it visible. No need for the complexity of an entirely new HTTP request:
$('button').click(function () {
$('span').show();
});
span {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
<span>this is the address</span>

You don't use <?php echo inside strings; that's only used when you're in a section of the script that's outputting literal text, not executing PHP code.
If you're in PHP code doing echo, you use variable substitution or concatenation.
<?php
function php_func(){
echo "<span>$address</span>";
}
php_func();
?>
You'll need additional code to set the $address variable; I assume you just left that out for simplification in the question.

<?php
function php_func(){
echo '<span>' . $address .'</span>';
}
php_func();
?>
this should work, u can't use 'echo' and inside echo open 'php' tag to use again.... more another 'echo'

Related

Javascript function to return PHP get_file_contents

I am stumped here, have asked this a few different ways. What I need to do is return the contents of a text file in PHP on click of an a tag. I thought it would be easy enough to just have the click and ID of the anchor tag in the JS and put the PHP method in the template like so. $textPath is var that points to the file in the settings. It goes to a help section and the text file authenticates the user. So the UL ends up being www.blahblah.com/help
<li><a id="help" target="_blank"><? echo file_get_contents($textPath);?> </a></li>
//Simple JS (part of another 'open' function for the menu)
$('#help').attr("href", "/help")
But it's still not working at all. Any ideas? Thanks
Highlighting a part of your code here:
<a id="help" target="_blank"><? echo file_get_contents($textPath);?> </a>
See you are using the shorthand echo tag. The opening tag should be <?= insead of <?. And since this is a shorthand echo tag, you don't need to use the echo construct.
This shall work fine:
<a id="help" target="_blank"><?=file_get_contents($textPath);?> </a>
Quoting from the PHP Manual
echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.
I have <?=$foo?> foo.
Coming to the question, you want to return the contents of the file. Your best bet will be achieving this via AJAX.
You can output as you wish. The best way will be to make a separate php file for handling all the ajax calls and return the output as plain text. To authenticate the user, just include the auth.php file(assuming that you are using one) in the ajax.php page.
ajax.php
<php
//Below code checks if a GET request is sent
if (isset($_GET['path'])) {
echo file_get_contents($textPath);
}
?>
jQuery
$('#help').click(function(e) {
e.preventDefault(); // Prevents the default action
// Send an AJAX request
$.get("ajax.php?path", function(s) {
//s is the responsetext. It contains the response from the server
your code here
});
});

Use of PHP code inside Javascript code

Since I know many consider the use of PHP code inside Javascript code bad practice, I wonder how to execute a javascript function provided that a certain PHP variable has a certain value.
This is the way I currently write the code:
<script type="text/javascript">
function execute_this() {
some code;
}
<?php
if(!empty($_SESSION['authorized'])) :
?>
execute_this();
<?php
endif;
?>
</script>
Any ideas how to avoid using PHP inside Javascript in this particular example?
If you don't want to include any PHP code inside the javascript code but want to know the value of a php variable, you have to integrate a communication between the server side (PHP) and the client (JS)
For example you could use a ajax request to call a small php snippet that provides the value in its reply. With that value you can go on in you java script code.
In my opinion you should decide if its worth the effort.
Edit:
In regard to the edited question: If it is important that the JS function is never ever called if the PHP session value isn't present I would stay with the PHP code but would do it that way:
<?php
if(!empty($_SESSION['authorized'])) :
?>
<script type="text/javascript">
function execute_this() {
some code;
}
execute_this();
</script>
<?php
endif;
?>
If you evaluate the value of the session variable in javascript, you have to make sure that nothing bad happens to your code if the provided value was manipulated.
It's a matter of code style. The time your project grows, you will find it increasingly difficult to maintain it or to extend its functionality. A better solution would be to initialize all needed variables in the beginning of the file and to externalize the main JavaScript functionality.
Example PHP:
<script type="text/javascript">
MYCONFIG = {
authorized: '<?php echo $_SESSION['authorized']; ?>',
foo: 'something else'
}
$(document).trigger('init'); // fire init event, you can call it as you like
</script>
Example JS with jQuery (note that i use the custom trigger 'init', you can call it however you like):
$(document).on('init', function() {
function execute_this() {
document.write(MYCONFIG.foo);
}
if(MYCONFIG.authorized) {
execute_this();
}
})
This should be in an external JS file and does not need any PHP tags.
You have to store the php variables somewhere in the html code and then access it.
For example:
<input type="hidden" id="hidval" value=<?php echo $_SESSION['authorized'] ?>/>
then in your js:
var somevar=document.getElementById(hidval).value;
if(somevar==what you want){
execute_this();
}
I think you have some basic design issues, and we are only seeing the tip of the iceberg and can't fully help you.
There is nothing inherently wrong with calling a php function this way, but you have several issues:
1) you cannot separate your js file & allow for caching or cdn
2) while MVC is certainly not "mandatory", it is definitely a good idea to try to separate this type of logic from your "view" - your rendered output
3) I suspect elsewhere you have a massive security hole - if you are setting certain parameters based on whether or not they are "authorized" in their session, this means you are most likely sending back info on which to base a permissions decision in your php code somewhere. Never do that from the page - all data should be "neutral" on the page itself, because you have no control over it.
Give this a read if you are not clear why I say that: http://www.codebyjeff.com/blog/2012/12/web-form-security-avoiding-common-mistakes
There are three possible ways to do it.
Use hidden field and add necessary variable value inside each fields and get those using jQuery.
User jQuery Session plugin and access php session variable.
make a ajax call to php and get response in json format and access response.

jQuery is messing with my PHP

I have a registration form that I'm working on and it's turning out to be a pain.
I'm very new to PHP, so please cut me some slack - haha.
I installed a jQuery plugin that allowed me to make inline labels for my textboxes. I also created an error box for any errors that occur during the registration process (invalid email, etc.). Here's some of my HTML/PHP code.
<?php
if($_POST['submit'])
{
$signuperror = "Hello World";
?>
<?php if($signuperror != "") { ?>
<span id="signuperror"><?= $signuperror; ?></span>
<?php } ?>
The problem was that the "error" of "Hello World" was not displaying when I clicked the submit button on my form. I copied and pasted this code onto a test.php document and it worked fine. So I knew that it had to be from my other html code. After troubleshooting almost every line of code, I found the culprit. It turns out that the jQuery plugin initialization for the inline labels was the problem.
$(function(){
$.fn.formLabels();
$("form").submit(function(){
var formVal = $("form").serialize();
parent.$("#default div.results").html(formVal);
return false
})
});
When I deleted this, it worked just fine (without my inline labels, of course).
What could I do to make BOTH the PHP and jQuery work.
Thanks.
- Ryan
Notice the return false at the end of the $("form").submit() function. That means the jQuery function is taking the place of your form's POST action. You're not reloading the page synchronously, so you don't have any value for $_POST["submit"]. Get rid of the return false line, and see if the page reloads as you're expecting.
There are lot of things here that are going on. Need to do this step by step.
Your PHP should either use <?php format or use <? short form but to be sure i would code all in <?php so its compatible everywhere
When you need to echo or output something use <?php echo $variable; ?> rather than <?=. Not that its no good or so but it will take out any php config issues with asp style output.
First test php output then check if statement.
Jquery is not messing with your PHP. That title is just as random as my answer.

How do I use jQuery to insert PHP tags through the DOM?

Here is what I'm trying to do...
$("div").prepend("<div id='comment-number'><?php the_comment_number(); ?></div>");
Is there some way to get this to work?
<div class="gallery-item">
<div class="comment-number"><!--?php echo htmlspecialchars(the_comment_number()); ?--></div>
</span>
<span class="gallery-icon">
<img src="http://mysite.com/test/wp-content/uploads/2011/06/fff-150x150.gif">
</span>
</div>
PHP is executed on the server, but JavaScript code (jQuery) is executed later, in the web browser. For that reason, PHP can produce JavaScript code, but JavaScript can't produce PHP code.
The <!--? in your posted output shows that something is filtering our your PHP code. So the problem isn't your PHP code, it's that you're not actually executing PHP code. If it's a .js file, PHP almost certainly can't be included.
If PHP were being evaluated (ex. if this were in a <script> tag in a .php file), this should produce valid JavaScript code that will do what you want:
$("div").prepend("<div id='comment-number'><?php echo htmlspecialchars(the_comment_number()); ?></div>");
1) php is SERVER side scripting
2) javascript is CLIENT side scripting (generally)
so this is what happens:
1) User opens up your page http://example/
2) Your CLIENT sends GET request to http://example/ server
3) Apache (given you run on it) captures the request, based on the server config approaches index.php (index.html, etc). If php is installed, your index.php will be parsed by mod_php module
<<<< this is where SERVER side scripting is activated
4) outcome of the parsing of index.php will be then transferred back to CLIENT
5) CLIENT will digest the outcome received by SERVER
6) If there are javascript calls, those are executed either immediately OR when document is loaded (based on approach)
That's it. Here normal request life ends.
NOW if you want your page to dynamically update some parts of it, here is how you do that:
1) Usually to update your page dynamically, you would use AJAX approach. When AJAX request is created, 2-7 happens again, but this time the caller is your ajax process and information which is received is sent back to that process to decided what to do with it.
Okay, some coding:
1) index.php
<!-- include jquery, etc //-->
<div id="comments"></div>
<script>
function fetch_comments(){
$.get("ajax.php", null, function(data)){
// this is called, when response from SERVER is received
$("#comments").prepend(data);
setTimeout("fetch_comments", 5000); // fetch again in 5 seconds
}
}
$(document).ready({
fetch_comments();
});
</script>
2) ajax.php
<?php
//fetch comments, return them for CLIENT
echo "<p>Comment on " . date("Y-m-d H:i:s") . "<br />Lorem Ipsum</p>";
This should help you understand the whole process. Did not test the code, but should be quite ok.
do a .ajax() query to PHP script that will provide you value of the_comment_number(); and put result to comment-number by $("#comment-number").prepend(result); on success event in ajax query.
Remebmer that PHP script have to have connection to database and pass to it all variables you need (like entity id, article id, page etc.). You can do it by GET or POST.
Request is sended by browser so session/cookies will be the same unless you changed it in current request.
PHP is executed on the server side so you cannot call it from javascript
You can try something like this which will render once the page loads
$("div").prepend("<div id='comment-number'>"+ <?php the_comment_number(); ?> +"</div>");
Couldn't you just add the value directly to the template instead of using javascriot? eg:
<div class="gallery-item">
<div class="comment-number"><?php echo (the_comment_number());?></div>
...
</div>
Also you have a </span> tag with out matching <span> tag in your example.
As already told, you can't produce or call php code from javascript directly(you need to make an ajax call or form submit). You need to make ajax call using jquery to fetch the comment number and then update it into div.
However, you may want to look at this library - http://www.phplivex.com/ .It may help you in doing things your way. It allows you to call user defined php functions in javascript using AJAX internally.
Reading through this disccussion and from what i understand you want to acheive.. You gotta figure how your page is served. If it is an .php file that is serving the content, then you wont need Javascript at all and could get your function call to work by adding the function between the div as so..
<div class="comment-number"><?php echo htmlspecialchars(the_comment_number()); ?></div>
Assuming you don't have access to the .php or if its a .html/htm page that serves the content then your only bet would be to use ajax. That is make an ajax call to a php file(on the same domain) that makes your function call and echos the comment no. The Ajax will retrieve the echo'd comment no. which you can append/prepend to the desired

php custom forum error

i have a form, and i want to have it be limited at 10 characters minimum. that is no problem, but what i want to do is echo the error at the top of the page, which is being included, so i cant just do:
echo '<div class="error">Error</div>';
i want to have a designated div that is empty (will be on the included header page), but when there is an error it gets filled with the error text to output. anyone know how to do this not using sessions or cookies?
This is a clear use-case for javascript. PHP is strictly a server-side language; that is, the code you write is executed on the server and not the client. Javascript, on the other hand, is run inside the user's browser. So say you create a div like so: <div id="error_msg" />. Then you can write a snippet of javascript code that looks like this:
function display_error () {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = "Error";
}
You would place this code in script tags at the top of your page inside the tags. More information on javascript form validation can be found here: http://www.w3schools.com/js/js_form_validation.asp
Hope this helps.
-tjw
Edit: if this isn't exactly what you're looking for, you might want to tag this post with 'javascript' to get more people who know about js form validation to answer the question.
<div id="error_msg" /></div>
<script>
function display_error (text) {
var err_msg_div = getElementById("error_msg");
err_msg_div.innerHTML = text;
}
display error('Error: your text here..');
</script>

Categories