Call jquery from php - 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.

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'

How to use a jQuery object from 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

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 to add a javascript alert with a PHP script?

let's say i have an input form, wherein, it's use for an email address. this form is part of a long form so i use an alert box instead when other inputs got errors....my question now is, if I checked the email input string via php, if it has been taken , how will I put the message like e.g "this email has been taken" in an alert box if i am using PHP to check it from backend ?..i want an alert box, since I use it with the other input boxes that don't need a backend check
e.g
alert("$errormessage");
PHP is server-side language. you can output it to user with
echo "<script>alert('".mysql_real_escape_string($errormessage)."');</script>";
or you can write your own function
function alert($a){
echo "<script>alert('".mysql_real_escape_string($a)."');</script>";
}
alert("test");
You can echo any kind of javascript with PHP. The question is however, are you sure you want to do this? You can also do like this:
<?php if(emailExists): ?>
<script>alert('Email exists!')</script>
<?php endif; ?>
But you could also use jQuery and Ajax requests to check if email exists with ajax when user has typed the email.
echo '<script>alert("ssss");</script>' ; just put it within echo it will work that way

Categories