I have a PHP code:
if($billing_total>$limit_to_send){
echo '<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>';
When I am printing this message, it is being printed at the beginning of the PHP page as below:
<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-----------------------------------------------------------
This caused the header (logo) of my page in the browser to move down one line.
and the page will look very bad because all the items there will be moved down one line.
I hope it is clear to you. Please any solution ?
===========================================================================
Thanks for All ...
Solution:
$alert_message=<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
Printing $alert_message somewhere in the HTML code before the body tag ^_^
Make sure you never output anything before the DTD (doctype declaration).
See this question for more information...
The doctype declaration must be the first element of your html page, it's from what the browser decides how to handle the rest of the html code. Outputting anything before that will probably put your browser in quirks mode so you can't be sure how the browser will render your page.
How to avoid this?
The echo command gets executed as its line is reached, and it seems that the rest of your html code follows after that.
You could either
move the html DTD and header to the top of your php (but sometimes that is not possible) OR
store the error html in a variable, so instead of echo '<script ... do $errorhtml = '<script ... and output that string, if not empty, at a specific place in the head or body generating code of your php.
If you have no control over the original source, you could consider redirecting to an error page with its own html DTD, header and body which you can design as fits you best.
Either append die() into the if codeblock or have your php print the script somewhere in the body or head.
This shows a bad design of your application. I would suggest you change it to something like:
$errors = array();
if($billing_total>$limit_to_send){
$errors[] = 'Sorry, you do not have enough credit';
}
Then on your HTML file, before the <body> tag closes, read your array and display any errors
<?php if(is_array($errors)): ?>
<script type="text/javascript">
<?php foreach($errors as $error): ?>
alert('<?php echo $error; ?>');
<?php endforeach; ?>
</script>
<?php endif; ?>
Related
I'm trying to get my page to scroll to a certain number of pixels down the page when it loads. I'm editing a wordpress template that I created so it's in PHP.
I've got:
<?php
echo "<body onload='window.scroll(0,400)'>";
?>
at the top of the php file but it's not working. what do I need to do to make this work?
Use this code in your header.php on your child theme or any similar.
<script type="text/javascript">
$( document ).ready(function() {
window.scroll(0,400);
});
</script>
Don't forget insert jquery in your head if this code not working
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
The onload event attribute is expecting a function, and you can do that inline with javascript: in the attribute...
<?php
echo "<body onload='javascript:window.scroll(0,400);'>";
?>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is my PHP code. I want error to be displayed using an alert window.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
include error.html.php';
exit();
}
This is error.html.php that is supposed to be parsed by the browser
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error = <?php echo $error ; ?>;
window.onload = function(){ alert(error); }
</script>
</body>
</html>
Wahts up with the script tags ? Do they prevent PHP from running ?
The real problem is that this is what your rendered result looks like:
var error = You must choose a project.
Click ‘back’ and try again.
Does that looks like valid JavaScript to you? I think not.
var error = <?=json_encode($error);?>;
That should result in:
var error = "You must choose a project.\r\n Click ‘back’ and try again.";
Much better.
Your problem is that javascript is run on the client and will run after the page loads and so after the php is run on the server.
However, you can do something like the following which allows php to set the value of a javascript variable when the page loads and then AFTER the page is loaded runs the javascript to display the message.
<?php
$error = "test me";
echo "<script>error = '" . $error . "'</script>";
?>
<script>
var error;
window.onload = function(){
alert(error);
}
</script>
UPDATE
Based on your edits, here's an updated answer.
The echo "<script>error = '" . $error . "'</script>" is needed to assign the $error to the javascript variable when the page is loaded.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
echo "<script>error = '" . json_encode($error) . "'</script>"
include error.html.php';
exit();
}
And the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error;
window.onload = function(){ alert(error); }
</script>
</body>
</html>
If you have an $error within your PHP, then you can write:
<?php
echo "<html><head></head><body></body>";
$error = "whoops!"; // just for testing
echo "<script>\n";
echo "alert('{$error}')\n";
echo "</script>\n";
echo "</html>";
?>
and the alert will happen as soon as the page is loaded, tested it on my server. This is for the situation where the $error is happening on the server side. (By the way, thanks for the fun question this late in my day!)
Actually it's quite simple.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
include 'error.html.php';
exit();
}
$error will now contain You must choose a project. Click ‘Back’ and try again. Note, there are no quotes, so then the line
var error = <?php echo $error ; ?>;
looks like this in the client:
var error = You must choose a project.
Click ‘Back’ and try again;
Which naturally causes an error as that is not valid javascript. You need to add quotes, either inside the definition of $error serverside or outside the PHP -- something along the lines of:
$error = '"You must choose a project.
Click ‘back’ and try again."';
OR
var error = '<?php echo $error ; ?>';
as per your preference...
You certainly can use inline php to generate javascript code. They will, of course, be executed in different contexts, Server-Side vs. Client-Side, but that's mostly irrelevant.
However, you have to realize that the two languages aren't communicating as such, but part of the JS is being generated by the output of the PHP. You have to be careful about that output. One of the issues you have is that JS does not support multiline strings, so the value of $error in PHP can't have a newline.
Try this instead:
if ($projectid=="")
{
$error = 'You must choose a project. Click \"back\" and try again.';
include 'error.html.php';
exit();
}
and
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error = "<?php echo $error ; ?>";
window.onload = function(){ alert(error); }
</script>
</body>
</html>
List of fixes:
Fixed quotes in the include statement.
Added quotes around the inline PHP echo in the JS code.
Removed the newline in the $error var so JS gets it all in one line.
Removed html quotes and replaced them with escaped regular quotes. Alert boxes don't process those.
i tried to do like this. i think its worthless
here my code..
<?php
$screen = '<script type="text/javascript">document.write(screen.width);</script>';
$echo $screen;
?>
this javascript code is work without php code..
<script type="text/javascript">
document.write(screen.width);
</script>
but i want to get only width from variable
i tried to like this get screen size from php.. but its not work.. someone can help me for do this one.. i want to variable for screen width.. if have another good method plz give me answer for this one.. thanks.
As mentioned in one of the comment, you need to differentiate client and server.
Though to make things simple, if you want to get screen width on server side, you can do the following :
Index.php
<?php
session_start();
if(!isset($_GET['width']) && !isset($_SESSION['screen.width'])){
?>
<html>
<head>
<script type="text/javascript">
location.replace('http://example.com/?width='+screen.width);
</script>
</head>
<body></body>
</html>
<?php
die();
}
if(isset($_GET['width'])){
$_SESSION['screen.width'] = (int) $_GET['width'];
}
echo "screen width : ".$_SESSION['screen.width'];
?>
I'm a college business student trying to build a website with a business model.
I'm building a website where I want to allow users to signup. Right now I'm using action: signup.php to store the user into the database. After the user is successfully inserted, I redirect the page back to the index.html where the form was submitted.
My question is, how can I reference JavaScript to change the login from display:block to display:none and sign up confirmation from display:none to display:block through my PHP tag?
I'm currently using $_GET to grab the success/fail status from signup.php and I want to use an IF statement to execute the correct JavaScript code.
UPDATE
I was advised to instead set all div's to block and use a PHP IF statement to display the login or signedup divs. However, after implementing the changes, the index.html still cannot distinguish the success/fail status. Here is my code below:
signup.php:
if (mysqli_num_rows($data) == 0)
{
$qry = "INSERT INTO logins (username, password, email) VALUES ('$username', SHA('$password1'), '$email')";
$result=mysqli_query($dbc, $qry);
if($result)
{
header('Location: index.html?signup=success');
}
}
else
{
header('Location: index.html?signup=fail');
}
index.html: Head
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Site</title>
<link type="text/css" rel="stylesheet" href="home.css">
<script type="text/javascript">...</script>
<?php
if(!empty($_GET['signup']))
{
$signup = $_GET['signup'];
}
?>
</head>
index.html: Body
<body>
<div id="container">
<?php
if(!$signup)
{
?>
<div id="login">...</div>
<?php
}
?>
<?PHP
if($signup)
{
?>
<div id="signedup">...</div>
<?PHP
if($signup == 'success')
{
?>
<div id="confirmation">...</div>
<?php
}
?>
<?PHP
if($signup == 'fail')
{
?>
<div id="failure">...</div>
<?php
}
?>
<?php
}
?>
</div>
</body>
As of now, after the user submits the form they are inserted into the database. The problem is that once they are redirected to the index.html, the php does not recognize the success/fail status and consequently only displays the login form.
That PHP code needs to go in your <head> or <body> section. You have it before <html> right now.
And yeah, onload = function(); should probably be window.onload = function;
This code doesn't do what you think it does:
onload=signedup();
You need to attach to the onload handler correctly:
window.onload = signedup;
Now, this isn't the best way to do things (it waits for EVERYTHING to be loaded), so if you happen to have jQuery included in your page, it'll be more efficient:
$(function(){ signedup(); });
Also, move the PHP to inside the HEAD tag since it prints out a script - and scripts should generally be in the HEAD tag.
Now, to take a different direction - why don't you just do it with PHP by printing out the HTML only if it's needed:
<?php if(!$signedup) { ?>
<div id="login"> ... </div>
<?php } ?>
This is probably the way to go in this case!
I am just started with PHP and have a rather simple problem I can't seem to figure out. I have set up a basic PHP script with will send me the content from my sites contact page. The script itself is fine - and so is the validator. Now what I am trying to achieve is getting a simple popup (similar to an alert function in javascript). Here is my try:
if ($valid) {
//*isUTF8($subject);
//*isUTF8($formcontent);
sendMail();
$body = $successMarkup . $backMarkup;
$title = "Form sent";
#header("location:formsent.php");
} else {
$body = $errorMarkup . $errorMarkupEnd . $backMarkup;
$title = "Form errors";
}
The file formsent.php I am refering to here only includes basic html markup as well as an javascript alert which is executed as soon as you open the page:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Contact Success</title>
</head>
<body>
<script language="Javascript">
<!--
alert ("Thank you for your message! I will come back to you as soon as possible!")
//-->
</script>
</body>
</html>
Here my question:
After I send the filled out contactsheet via the send button I get a popup with the message shown above - BUT to do so it leaves the actual page I am on and shows me only a white screen.
How can I get that popup message implemented without leaving the page I am on?
Try using this one: http://jquery.malsup.com/form/ with jQuery to make an Ajax form submit simple.
The examples, shown on that page are quite enough to implement your type of a story.
just put:
<script>
$(document).ready(function(){
$('form#form_id').ajaxForm(
function(data){
alert(data);
}
)
})
</script>
And so everything you need to do in your sendmail script is to echo the needed message, no redirecting required.
header("Location: <url>") results in a proper redirect. You need to use Ajax here to send the data (when the user submits it), receive the contents of the popup box and then display it.