PHP echo out javascript - javascript

On form submit, I want to give the user a message.
Originally, I was doing
if(isset($_POST['submit'])) {
echo "submitted";
}
But this would appear randomly at the top of the page.
I want control where the message is output, so I wanted to append the message to a DOM element... to do that, I thought I could use JavaScript as so:
if(isset($_POST['submit'])) {
echo "<script type=\"text/javascript\">
document.getElementById(\"submitmsg\").innerHTML = \"submitted\";
</script>";
}
The HTML shows that the PHP seems to output the JS correctly, but submitmsg is empty.
Any thoughts?
HTML form: calls itself so it can run the PHP code at the top of the page:
<form role="form" action="" method='post' accept-charset='UTF-8'>
<div class="row">
<div class="form-group col-xs-12 floating-label-form-group">
<input class="form-control" type="text" name="name" placeholder="Name">
</div>
</div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" name="submit" class="btn btn-lg btn-success">Send</button>
</div>
</div>
</form>

Not sure what you really do since you didn't post all the code, but I see 2 options.
First : On submit, you use an ajax query and don't refresh the page. If that's the case you should use the oncomplete() callback to do the javascript stuff (php should not return javascript code).
Second : The page is reloaded, then you should use PHP to directly echo html wherever you want in your code :
<nav ... >...</nav>
<p id='submitted><?= isset($_POST['submit']) ? "Submitted" : "" ?></p>
Note that you can put php tags where you want really :
<html>
<head>
<title><?php echo "Today is " . date('Y-m-d');?></title>
</head>
<body>
<?= "My Cool Body" ?>
</body>
<html>

I want control where the message is output
Why don't you store the submit status in a PHP variable and output it where required:
<?php
$is_submitted = isset($_POST['submit']);
?>
<html>
<body>
<!-- your page -->
<nav></nav>
<?php if($is_submitted) : ?>
<p id="submitmsg">Submitted</p>
<? endif; ?>
Or even just put your isset() check inline further down your page.
But this would appear randomly at the top of the page.
There is no point in echoing out a Javascript call to display this message, you can put PHP where ever you want to in a document.

the other answers are pretty much the right way.. if you wanna stick with the way you're doing things now, just switch your php output to:
window.onLoad = document.getElementById("submitmsg").innerHTML = "submitted";
if the Page is reloaded anyway you can echo submitted where you need it.

Related

fetch data without reloading by passing a variable to jquery

I want to fetch some data (without reloading page) based on UserIds that are linked to a tags. I am not able to pass on UserID to jquery successfully and accurately. What it does is, just picks the last UserID and fetches it.
I have also tried to pass on variable throuh a-tag URL but could not get it accurately in jquery file. It fetches the data from already opened url, not the one being clicked right now.
HTML:
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<input type="hidden" id="ANP" value="<?php echo ($Messagers1['UserID']*3);?>"></input>
<a class="LoadMsgsBtn">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
jquery:
$(document).ready(function(){
$(".LoadMsgsBtn").click(function LoadMsgsfunc(){
var ANP = $("input#ANP").val();
var Msg=6;
alert(ANP);
$("#result").load("LoadDB.php",{
ANP: ANP,
Msg: Msg
});
})
});
LoadDB.php:
<?php
$ID = $_POST['ANP'];
$Msg = $_POST['Msg'];
echo $ID . "\n";
echo $Msg;
I want to fetch data from database without reloading using UserID sent. $Messager is an array having multiple rows, there is a series of a-tags. clicking on any a-tag sents corresponding UserID to jquery code
Classic issue of multiple element selection. It's a bit tricky when you are using loops and jquery selectors ;) Check out the following code. It should work like butter B)
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<a class="LoadMsgsBtn" href="javascript:void(0)" onclick="featchData('<?php echo ($Messagers1['UserID']*3);?>')">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
Javascript
function featchData(userId)
{
console.log(userId);
//if you get the id, write in the rest of the code here ;)
}

How to pass php variable through jQuery and back to php using form without submit

I use a lightbox popup for several things, especially for people to leave feedback on work in progress, to approve/reject a job and so on.
Now I want to re-use this code for something that looks simple but I can't get it to work.
The first part of the code below triggers a jQuery script and passes on the variable $order_id1, which I need later on:
<button class="inner-preview" onclick="previewOrder('<?php echo $order_id1 ?>');" title="Preview the work">P</button>
This is the jQuery script that triggers the lightbox to popup, does it's job as well (eg. the lightbox pops up):
<script>
function previewOrder(order_id1)
{
jQuery('#preview_content').val(order_id1);
jQuery('.lightBoxWrapper3').fadeIn();
}
</script>
Now it gets tricky, as I want to call some things from the database using the variable $order_id1 as the ID to find it in the database.
<div class="lightBoxWrapper3" style="display: none; width: 100%; position: fixed; z-index: 9999999; background-color: gray;">
<div class="lightBoxContentArea3" style="width: 70%; margin: 0 auto;">
<p style="font-size:24px;margin:10px 0 20px 0;color:#6D7678;">Preview the work:</p>
<a class="closedPopup3" href="javascript:jQuery('.lightBoxWrapper3').fadeOut();">X</a>
<form action="" method="post">
<input type="hidden" name="order_id1" id="preview_content" value="">
<?php
$getwork=getOrder(['order_id1']);
echo "<h2>".$getwork['title']."</h2>";
echo $getwork['content'];
?>
</form>
</div>
</div>
So in short I want to use which was initially send as $order_id1 and which jQuery turned into order_id1 to be used in my getOrder() function without receiving an undefined index error message as it's already defined way earlier in the code over here:
<div class="inner-bottom2">
<?php foreach($orders as $approve_order) {
$order_id1=$approve_order['id'];
$status1=$approve_order['status'];
$approve1=$approve_order['approve'];
$title1=$approve_order['project_title'];
$writer_id1=$approve_order['writer_id'];
$name1=get_userdata($writer_id1);
if ($status1==1 && $approve1==0) { ?>
<ul>
<div class="inner-title"><?php echo wordwrap(substr($title1,0,40)); ?></div>
<div class="inner-id">ID: <?php echo $order_id1; ?></div>
<div style="clear:both;"></div>
<div class="inner-user2">By: <?php echo $name1->user_login; ?></div>
<button class="inner-reject" onclick="rejectOrder('<?php echo $order_id1 ?>');" title="Request a revision">R</a>
<button class="inner-approve" onclick="approveOrder('<?php echo $order_id1 ?>');" title="Approve the work">A</button>
<button class="inner-preview" onclick="previewOrder('<?php echo $order_id1 ?>');" title="Preview the work">P</button>
<div style="clear:both;"></div>
</ul>
<?php }
} ?>
</div>
</div>
The getOrder function on itself works fine, if I wouldn't get this undefined index issue cause it gets passed through jQuery.
In short I just want to pass those values from a specific foreach row to this lightbox thing and the only way to get there is through jQuery as I don't want the page to refresh, I can easily echo content and title in the first part of the code but that doesn't make it show up in the lightbox. Some have said use colorbox instead but it's not compatible with my theme for whatever reason and when I install the colorbox plugin all jQuery functions seaze working alltogether so I want to get it done with this lightbox, which works perfectly fine for my other goals like sending messages and such.

how to make a div load on submit without refreshing the page using ajax?

Here is my code that works fine, but it has to reload on every time submitted. I want to reload the comments.php on every time submit button is clicked.
What should I write in JavaScript?
Index.php:
<div class="form-group">
<form action="" method="post" id="reply" enctype="multipart/form-data" >
<div class="input-group">
<input type="text" placeholder="say something" class="form-control" name="comment"/>
<br/>
<button class="btn btn-info" type="submit" name="submit">submit</button>
</div>
</form>
</div>
<?php
if(isset($_POST['submit'])){
//php goes here
}
?>
<div>
<?php include("comments.php") ; ?>
// i want to make this reload on every submit
</div>
function myfunc(){
$.ajax({
url:"comments.php",
data:$("input").val(),
method:'post',
success:function(response){
},
error:function(error,message){
}
});
}
<form action="javascript:myfunc()"......>
this is with jquery
This question uses jquery. If you dont know it, visit http://jquery.org for more information:
Add a div around the comments.php:
<div id="comments">
<?php include("comments.php") ; ?>
</div>
Now you can catch the submit and replace it with an ajax call+ reload the comments:
<script>
$(document).ready(function(){
$("#reply").on("submit",function(e){
e.preventDefault();
$.ajax();//todo for you. I cannot write this with this rare information
$("#comments").load("comments.php");//the magic part
return false;//prevent the real submit
}):
});
</script>
You can use jQuery load() Method.
The jQuery load() method loads data from the server and place the returned HTML into the selected element. This method provides a simple way to load data asynchronous from a web server.
The parameters of the load() method has the following meaning:
The required URL parameter specifies the URL of the file you want to
load.
The optional data parameter specifies a set of query string
(i.e. key/value pairs) that is sent to the web server along with the
request.
The optional complete parameter is basically a callback function
that is executed when the request completes. The callback is fired
once for each selected element.
Your html :
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("#box").load("comments.php");
});
});
</script>
</head>
<body>
<div id="comments">
</div>
<button type="button">Load Comments</button>
</body>
</html>
Comments.php
<?php
//content here
echo "I'm loaded";
?>

PHP script echo isn't executed

I am printing a very simple JavaScript using PHP, which doesn't get executed. If I print the data, I see the following script (exactly as needed) at the end of the HTML file:
<script type="text/javascript">
document.getElementById("message").innerText="Email already exists";
</script>
I have also tried using innerHTML="Email already exists";.
This is printed in PHP as such:
echo "<script type=\"text/javascript\">
document.getElementById(\"message\").innerText=\"Email already exists\";
</script> ";
In my HTML I have an element which has the ID: message. It looks like this:
<h3 id="message"> </h3>
What I am expecting is to get "Email already exists" in the h3, however this doesn't happen. The JavaScript is not executed. If I use the exact same JavaScript code but place it ahead or on an "onclick" request, the code works.
One thing which could be relevant: I noticed that the JavaScript is printed after the closing HTML tag.
How do i get the JavaScript code to execute after being echo'ed into the HTML? I've read several threads which said its supposed to simply run, however mine doesn't. I have tried about 50 different fixes, none of which worked.
The code: http://ideone.com/dmR42O
You mentioned this:
One thing which could be relevant. I noticed that the javascript is
printed AFTER the closing html tag (the ).
That is very relevant. Any Javascript must be contained within the <html> element (before </html>). But, be sure that the Javascript appears after the <h3>. Javascript will run when it's encountered, as Marc said in a comment above.
If the Javascript must be before the , then do this:
window.onload=function(){
document.getElementById("message").innerText="Email already exists";
};
Try it like this:
echo '<h3 id="message"> Email already exists!</h3>';
<!DOCTYPE html>
<html>
<body>
<form id="submitform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="logIn_email_input" name="email" type="text" placeholder="Enter e-mail address" autocomplete="off">
<input id="logIn_password_input" name="password" type="password" placeholder="Enter password" autocomplete="off">
<input id="logIn_submit" type="submit" name="logIn_submit">SIGN UP</button>
</form>
<?php
$query = mysql_query("SELECT userid FROM users WHERE email = '". $email ."'");
if (mysql_num_rows($query) > 0) {
echo '<h3 id="message"> Email already exists!</h3>';
}
?>
<body>
</html>
You had a lot of issue here (maybe typos ?)
action="<?php echo $PHP_SELF;?>" should be action="<?php echo $_SERVER['PHP_SELF']; ?>"
<button id="logIn_submit" should be <input id="logIn_submit" type="submit" name="logIn_submit">
<? php had extra space should be <?php
If statement was missing closing brace }
No <body> tags

Javascript redirect based on form input

I need to redirect one page to another page using the form value.
I have this code, which i think is fine for first page and what should i put in the other page where i want to show the data ??
<meta http-equiv='refresh' content='0;url=http://site.com/page.php'>
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php echo $url; ?>">
<script language="JavaScript">document.myform.submit();</script>
</form>
Regards
You can't mix a meta-refresh redirect with a form submission per se.
Also, meta-refreshes are terrible anyway. Since you are already in control of the receiving page, and it's using PHP, use that to accomplish the redirect. Try this:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="submit" value="Go!" />
</form>
Then, in page.php:
<?php
// Act on the input, store it in the database or whatever. Then do the redirect using an HTTP 302.
header('Location: http://example.com');
?>
If you need the form to pass the destination along to page.php, you'll want to sanitize it to prevent a LOT of security problems. Here's a rough outline.
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="destination" value="http://example.com" />
<input type="submit" value="Go!" />
</form>
Then, in page.php (copied re-encoding from answer https://stackoverflow.com/a/5085981/198299):
<?php
$destination = $_POST['destination'];
$url_parsed = parse_url($destination);
$qry_parsed = array();
parse_str($url_parsed['query'], $qry_parsed);
// Check that $destination isn't completely open - read https://www.owasp.org/index.php/Open_redirect
$query = parse_url($destination);
$destination = "{$url_parsed['scheme']}{$url_parsed['host']}{$url_parsed['path']}?" . http_build_query($query);
header('Location: ' . $destination);
?>
I haven't double-checked that code (just wrote it here in the browser), but it should suffice as a rough sketch.
in site.com/page.php
<script>window.location.href = 'newPage.php';</script>
You will have to write this outside the php tags though.
To redirect a page in PHP, use:
<?php
header('Location: url/file.php');
?>
To refresh to a different page in HTML, use:
<meta http-equiv='refresh' content='0;url=http://url/file.php'>
In the content attribute, 0 is the amount of seconds to wait.
To refresh to a different page in JavaScript, use:
window.location.href = 'url/file.php';
When none of these work, follow an anchor link, using HTML:
Click here to go now!
To answer your question, it can be done several ways:
1) Very bad, requires two files, super redundant
HTML file:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Submit the form
document.forms['myform'].submit();
</script>
Page.php:
<?php
// Catch url's value, and send a header to redirect
header('Location: '.$_POST['url']);
?>
2) Slightly better, still not recommended
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Set form's action to that of the input's value
document.forms['myform'].action = document.forms['myform'].elements['url'].value;
// Submit the form
document.forms['myform'].submit();
</script>
3) Still very redundant, but we're getting better
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Simply refresh the page to that of input's value using JS
window.location.href = document.forms['myform'].elements['url'].value;
</script>
4) Much better, save yourself a lot of trouble and just use JS in the first place
<?php
// Start with a PHP refresh
$url = 'url/file.php'; // Variable for our URL
header('Location: '.$url); // Must be done before ANY echo or content output
?>
<!-- fallback to JS refresh -->
<script type="text/javascript">
// Directly tell JS what url to refresh to, instead of going through the trouble to get it from an input
window.location.href = "<?php=$url?>";
</script>
<!-- meta refresh fallback, incase of no JS -->
<meta http-equiv="refresh" content="0;url=<?php=$url?>">
<!-- fallback if both fail (very rare), just have the user click an anchor link -->
<div>You will be redirected in a moment, or you may redirect right away.</div>
Save that with a .php extension, and you should be good to go.

Categories

Resources