How to use a jQuery object from php? - php

Why does this not work? This is the first thing in the body:
<?php
if(isset($_POST['submit'])){
echo "<script>$('.classToShow').show();</script>";
}else{
echo "<script>$('.classToShow').show();</script>";
}
?>
classToShow is a simple div in the body. It won't show up and its not depending on the boolean condition, it must be the code...
While this works:
<?php
if(isset($_POST['submit'])){
echo "<script>alert('works');</script>";
}else{
echo "<script>alert('works');</script>";
}
?>
So the simple JavaScript works, but the jQuery doesn't... Why is this?

This is your problem:
This is the first thing in the body
At that point the element with the class of classToShow does not exist yet, so nothing happens. You should wait for the DOM to be ready before you run that code.
On the other hand, if you just want to show something when a POST request was made, you can add it directly using php and you don't need jQuery to do that afterwards.
A common solution would be to show it directly using php and then use javascript to hide the message after a certain timeout.

You can use $(document).ready() and inside that write the code

Related

Loading PHP function using jQuery onclick

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'

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 to print a page using javascript for every php while loop?

I want to print a page using javascript in php while loop. Please help me by giving an advice.
eg:
$q=mysql_query("SELECT name, address FROM member_table);
while ($r=mysql-fetch_row($q)){
echo $r['0']."<br />".$r['1'];
echo 'javascript:window.print()';
}
But this is not working. Please help me.
I want to print the page similiar to Print But this should be automatic as while condition will bring more result in looping process
Is there any way to send the page directly to printer one by one from loop or other method. Please help me by giving an example
Could you provide more details on what you're trying to do. PHP is server side while javascript is client side. When php is done producing the page (loops or not) you still have just 1 page rendered. I am not sure what javascript:window.print() in the loop gives you.
If you want to trigger the page to print after the whole thing is rendered, you can put
<script>
javascript:window.print();
</script>
at the bottom of your page but not in your loop.
Don't use echo for javascript output.
<?php while { ?>
Javascript here
<?php } ?>

jQuery - click() not working when attached to anchor created in PHP

I have this PHP code which outputs HTML anchor elements on a page:
if(!$isOnOwnPage)
echo '<a id="message-button" class="button">Message</a>';
if($isOnOwnPage)
echo '<a id="add-img-button" class="button">Add Image';
else if(!$isFollowing)
echo '<a id="follow-button" class="button">Follow';
else
echo '<a id="follow-button" class="button">Unfollow';
echo "</a>";
When I load the web page, I get this, as expected:
...
<a id="message-button" class="button">Message</a><a id="follow-button" class="button">Unfollow</a>
...
But when I try to attach a click() function to it, the clicking doesn't work. This is the jQuery code. (It's weird because all of my other JS on the page works flawlessly."
$('.button').click(function() { alert("HEY"); }); // It doesn't work grabbing by #follow-button or #message-button either.
What did I do wrong here? I've spent an hour looking at these snippets of code to no avail.
Try this:
$('.button').live('click',function() { alert("HEY"); });
Put it in your $(document).ready function.
Gonna go out on a limb and guess that you've forgotten to wait for document.ready and that the a.button element doesn't exist when the click event is bound.
Is ajax included somehow? Because then you need to either use the live, or re-apply the function.
It should work regardless if it's PHP generated. In the end it's still HTML that gets output to the client.
I think you should make sure that the JS code gets to the part where you assign clicks to the buttons. Maybe there's not document ready or a correct one. Maybe there's a boolean IF that doesn't get passed.
All in all, if you can see the code in the View Source page, then it's a HTML/JS problem, not a PHP one.
This is an old question, but to all there who want to add listeners to dynamic content, instead of using $('a').(click(function(){}) or $('a').on('click',function(){}), you need to use instead the document as the object you want to attach the listeners, because the tag you are inserting wasn't in the DOM when the listener was assigned.
So instead you should use:
$(document).on('click','a',function(){ ... });

Call jquery from php

I have a form with Name : input and a submit. When pressed, it posts to the same php file. My first check is basically if(!$name) { call jquery to insert error class }. I have the jquery set up in a function but I'm not sure how to call the function from the if statement.
You need to do your check in javascript / jquery and avoid posting to the php file until the javascript validation is completed / satisfactory.
Then in php you need to validate again in case the visitor has javascript disabled.
Don't use jquery in this case. Just have PHP output the appropriate class in the HTML, since PHP can not directly (or even indirectly) call javascript functions:
<?php
$name_error = empty($name); // $name_error is true/false;
?>
[...snip...]
<div class="this and that <?php if ($name_error) { echo 'error classname here'; } ?>">
<?php if ($name_error) { echo 'error message here'; } ?>
</div>
Trying to get PHP to call javascript to do what PHP can already do perfectly well on the server is a waste of effort. It's like driving to a payphone instead of using the perfectly good phone that's already sitting on your desk.
I think my answer for this question should prove helpful.
In a nutshell - your PHP script will need to send data back to the client that will let you identify which field is in error and why. jQuery will then be responsible for altering the field as you see fit.

Categories