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.
Related
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'
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
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.
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>
Anybody have any idea how I might go about doing something like this.
I've got a textarea setup to allow users to edit page content. the content is then stored in a database and is retrieved on the frontend by php within an html template. something like:
<html>
yada yada...
<?php
echo get_page_contents_by_id($_GET['id']);
?>
yada yada...
</html>
its all run in a .php file, in case anyone wanted to call that out.
What I'm wondering is, because I'm getting the content from the database via php, is there any way that I can retrieve php code within that content and still run it without doing any sort of file writing.
You can use the PHP eval() method to execute the PHP code returned from the database - just as if it was actually written in your PHP file directly.
e.g.
<?php
eval("echo('hello world');");
?>
Prints:
hello world
You can use eval for this purpose.
http://php.net/manual/en/function.eval.php
eval() is as James Goodwin and Gazler say in fact the only way to execute PHP code from string data.
In addition to the security consequences - it will become possible to compromise your whole web site by gaining access to your mySQL data - this approach will make code very hard to debug, as you will have to follow all error messages through the eval()d code.
I attempted to do this same thing, but with the addition of tags and normal HTML tags. This will not work. If you need to store HTML along with your PHP, consider a more XHR solution that relies less on PHP code for every page.
Consider another alternative. Really.
Regardless of any security checks you do, function parsing, etc., this is still an EXTREMELY bad idea.
A slightly less bad idea, why not look into a templating solution like http://www.smarty.net or http://www.google.com/search?q=php+template+engine
Below is the code to execute the code in textarea.
<?php
if($_POST){
print_r($_POST);
extract($_POST);
$file = rand(1000,10000); // creating file with random number
file_put_contents($file.'.php', '<?php '.$code.' ?>');
ob_start();
include $file.'.php';
echo ob_get_clean();
unlink($file.'.php'); // deleting the created file after execution.
die('test');
}
?>
<textarea id="testcode" ></textarea>
<input type="submit" onClick="return changePermissions1()" />
<script>
function changePermissions1(){
var code = {};
code['code'] = $("#testcode").val();
var pass_url = "executefile.php"; // there you can pass the code
$.ajax({
type : "POST",
beforeSend : loadingStarts,
url : pass_url,
data : code,
success : function(responseText){`enter code here`
loadingEnds();
alert(responseText);
}
});
}
</script>