append PHP code to HTML input placeholder? - javascript

I want to append a PHP function that shows the user his/her IP within an inputs' placeholder. I've never seen anything like this been done before so I'd like to just see if it's possible or not.
My thoughts right now is to do something along these lines:
$('input').attr(placeholder,function(){
$('input').append('<?php $variable ?>');
});
then run the PHP code through here some how. If someone can shed some light on this I would be very grateful!

try this:
$('#inputID').attr("placeholder","<?php echo $variable; ?>");
And if you want to append to all inputs:
$(":input").attr("placeholder","<?php echo $variable; ?>");
should do the work

If you want to do it in PHP you can make a function to retrieve the IP of the user then echo the script in your page:
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
echo "<script type='text/javascript'>
$('input').attr(placeholder,function(){
$('input').append('".getUserIP()."');
});
</script>";
?>

Related

Show div element after reCaptcha validation

I am using Googles reCaptcha API for form validation.
I have opted to have the submit button show once the validation has been complete by using a little bit of JS.
<?php
if(isset($_POST['Login'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = '6LerNA0UAAAAAEReb9rS5JXjtvNSYlMjKiocUv_O';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true){
//show submit button
echo '<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="visible";
}
</script>';
}
else{ // stay hidden
'<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="hidden";
}
</script>';
}
}
?>
<div id='logDiv' style='visibility:hidden')
<?php
echo $form->add('Login',array('type' => 'submit'));
?>
</div>
Currently, the solution isn't working; when the Captcha is validated the div remains hidden.
Is this a result of a syntax error or have a made a logical error?
What is the bug in my code?
Are there any more robust solutions?
Why not simply use a php condition to show the div? I think your JS isnĀ“t working because you never call myFunction().
Try something like this but it will become complex over time and amount of code:
if(isset($data->success) AND $data->success==true){
$showButton = true;
}
......
if($showButton) { ?>
<div id='logDiv' style='visibility:hidden'
<?php echo $form->add('Login',array('type' => 'submit'));
?> </div> <?php }
......
Or a simple Solution:
if(is_bool($data -> success) && $data -> success){
echo '<div id="logDiv">'.$form->add('Login',array('type' => 'submit')).'</div>';
}
Echo the HTML Elements only if validition was successful otherwise simply dont ouput any HTML for the Div.
Hope this Helps.

Insert an paragraph with jQuery in an PHP 'If' statement

I've written a simple login script that connects to a db, and now I want to insert a paragraph with jQuery in my #loginbox which says 'Login failed' when
if (!$row = mysqli_fetch_assoc($result))
is true.
My thought was:
[function.js]
function loginfailed() {
$('#loginbox').html("<p>Login failed.</p>");
}
[login.php]
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<?php
include '../config.php';
include 'dbh.php';
session_start();
$uid = $_POST['uid'];
$pw = $_POST['pw'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pw='$pw'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php');
echo '<script> loginfailed(); </script>';
}
else
{
header('Location: ../index.php');
}
?>
But it doesn't work.
DON'T EVER STORE PASSWORDS IN PLAIN TEXT!!
Regarding your question.
The header function redirects to index.php and does not execute the echo. One solution can be to add a $_GET parameter and after the redirect check if it exists and echo the message or append it with JS.
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php?status=fail');
}
In the index.php file at the bottom (if you want to use JS/jQuery to show message)
<script>
var status = "<?php echo (!empty($_GET['status']) && $_GET['status'] === 'fail') ? 0 : 1; ?>";
if(!status) loginfailed();
</script>
Thanks guys, but i've found my own solution with the help of Allkin.
My header now redirects to
header('Location: ../index.php?status=fail');
and my #loginbox checks if status is set and then executes my loginfailed() function.
if(isset($_GET['status'])) {
echo '<script> loginfailed(); </script>';
}
Nothing easy like that!
Thanks for your help everyone.

Alert box in PHP - Making me crazy

I know this question is very common, I have search alot, and after alot of hard work, I am asking here.
I simply want to show an alert box and redirect it to a page.
The code below is redirecting me, but not showing me the alert box.
Please, let me know my mistake.
<?php
require_once('connection.php');
if(isset($_POST['person'])){ $name = $_POST['person']; }
if(isset($_POST['pwd'])){ $password = $_POST['pwd']; }
if(isset($_POST['position'])){ $pos = $_POST['position']; }
if(empty($name) or empty($password))
{
echo "<SCRIPT type='text/javascript'>
alert('Places should not be empty! Press Ok and try again!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
else
{
//$query=mysqli_query($con,"insert into members (username, password,position) values ('$name','$password','$pos')");
echo "<SCRIPT type='text/javascript'>
alert('Added!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
?>
I personally make this function to show an alert box and redirect it to a page.
function do_alert($msg,$link=NULL)
{
echo '<script type="text/javascript">
alert("' . $msg . '");
</script>';
if(!empty($link)) {
echo '<script type="text/javascript">
window.location="'.$link.'";
</script>';
}
}
Use this function both alert and redirect to a page use this
do_alert("Message","URL");
do_alert("Here this is your alert","addmember.php");
do_alert("Only your alert");
If the function 2nd parameter URL is empty then it'll only do alert.
try to change
window.location.replace(\"addmember.php\");
to
window.location='addmember.php';

Serve Javascript with PHP: Return/Echo URL/URI

EDIT: Missed the echo statement!
EDIT2: Added missing paranthesis!
EDIT3: Found the solution. See below!
What I am trying to achieve is this:
Dynamically create a Javascript-file with PHP
Serve Javascript-file as .js as embeddable Javascript on different URLs
Dynamically add Page Name and Page URL information inside the JS to be used in Javascript
Currently I do the following:
code.php
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
echo $func->getPageURL();
echo $func->getPageName();
?>
*/
var fred;
...
class.functions.php
<?php
class Functions {
function getPageURL() {
$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
$data = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
return $data;
}
function getPageName() {
$data = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
return $data;
}
}
Whenever someone triggers my script-embed code I route them to my code.php. Example:
<script src="//servingdomain/dynamic/123.js"></script>
Now, my code.php does a great job, but returns me this:
/*
servingdomain/dynamic/123.js
*/
/*
https://servingdomain/dynamic/123.js
index.php
*/
var fred;
...
Unfortunately my getPageURL und getPageName are not executed properly, but I am failing to understand why.
I am aiming to get this as output:
/*
servingdomain/dynamic/123.js
*/
/*
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
*/
var fred;
...
How should I takle this problem and get this working correctly either by clean code or dirty workaround ... I am aware of window.location.pathname and window.location.href in Javascript, but I need those to be passed in PHP, since I need to reuse this information to generate dynamic code in code.php.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer and running that through
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
<?php
$func = new Functions;
$purl = $func->getPageURL()."\n";//use ()
$pname = $func->getPageName();
echo $purl;
echo $pname;
?>
The PHP code is executed just fine, but it just doesn't have any result. You need to write out the values to the file:
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
$purl = $func->getPageURL;
$pname = $func->getPageName;
printf("%s\n", $purl);
printf("%s\n", $pname);
?>
*/
var fred;
...
This will write the values of those variables to the javascript file.
Note that if you want to use these values in the javascript code, you need to assign them to a javascript variable like this, outside of javascript comments:
printf("var pageName='%s'\n", $pname);
That way, you can use pageName in your javascript.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
Running that through this function
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)

How to use javascript in PHP? The script tag is not recognized

I don't know why but the script tag is not working, the SELECT query is working but i am not getting the prompt from the javascript.
it is not redirecting anywhere only a blank screen is seen
$qry1="SELECT area, aadhar FROM user where username='$user'";
$result1 = $connector->query($qry1);
if($result1){
$row1=mysql_fetch_array($result1);
$userarea= $row1['area'];
$useraadhar=$row1['aadhar'];
}?>
<body>
<script type="text/javascript">
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
if(inputarea==userarea){
<?php/
//date
$today = date("Y-m-d");
//Create INSERT query
$qry = "INSERT INTO complain (user,category,regno,course,lecturer,room,details,address,datein) VALUES ('$userid','$category','$reg','$coursename','$lectname','$roomno','$details','$address','$today')";
//$result = #mysql_query($qry);
$result = $connector->query($qry);
//Check whether difjslk the query was successful or not
if($result) {
$errmsg_arr[] = 'Complain succesfully added, please wait for your response';
$errflag = true;
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: _new_complains.php");
exit();
}
header("location: _new_complains.php");
exit();
}else {
die("Query failed, couldn't add the new record");
header("location: _new_complains.php");
exit();
}
?>
}
You are sending data (for example body tag) before header(), therefore PHP creates an error. You just don't see it. Header needs to come before anything is sent to the browser (even a space).
You have multiple JS syntax errors:
var inputarea=<?php echo $coursename; ?>;
var userarea=<?php echo $userarea; ?>;
var useraadhar=<?php echo $useraadhar;?>'
Never EVER dump out raw text from PHP into a Javascript context. You're generating code that looks like
var inputarea=foo;
var userarea=bar;
var useradhar=baz';
The data will be seen as undefined variables, and you've got a stray ' in there. All of these errors will KILL the entire <script> block.
Always use json_encode() to dump from PHP->JS:
var inputarea = <?php echo json_encode($coursename); ?>;
This will GUARANTEE that you're producing correct Javascript code. The above line would produce
var inputarea = 'foo';
and be perfectly valid and executable code.

Categories