Can I use PHP print as Input Field's default Value? - php

I have placed a php code for getting current page URL and now I can get current page URL by writing this code
<?php print(selfURL()); ?>
Now, I want to know how can I write this code as the default value of Input field?
Actually I want the Input field to automatically filled up with the current page URL.
When I use <?php print(selfURL()); ?> as value="<?php print(selfURL()); ?>" it simple shows a text and don't display current url. But when I paste it in other place then its working fine.
Any suggestions?
UpDATE:
Guys, this is the full code of the page, may be it helps!
<?php
function selfURL() { $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; $protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s; $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']; } function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2)); }
?>
<?php
// Start YOURLS engine
require_once( dirname(__FILE__).'/includes/load-yourls.php' );
?>
<!DOCTYPE html>
<html>
<head>
<title>YOURLS Public Interface Sample</title>
<style>
body {
background:#E3F3FF;
color:#595441;
font:16px/30px verdana,arial,sans-serif;
}
a, a:visited {color:#2A85B3}
h1 {text-align:center; color:#2A85B3}
h2 {
border-bottom:1px solid #2A85B3;
color:#2A85B3;
margin-left:-10px;
padding-left:25px;
width:80%;
}
#container {
width: 780px;
margin-left: auto;
margin-right: auto;
background-color: #fff;
border: 3px solid #2A85B3;
padding: 10px;
margin-top: -13px;
-moz-border-radius:15px;
-webkit-border-radius:15px;
}
#footer {
text-align:center;
margin-top:20px;
}
#footer p {
padding:5px;
background:white;
margin:0 auto;
width:750px;
-moz-border-radius:10px;
border-radius:10px;
-webkit-border-radius:10px;
border:1px solid #2A85B3;
-moz-border-radius-bottomleft:35px;
-moz-border-radius-bottomright:35px;
-webkit-border-bottom-left-radius:25px;
-webkit-border-bottom-right-radius:25px;
}
#footer p a {
background:#fff url(http://yourls.org/images/favicon.gif) 2px center no-repeat;
padding-left:20px;
}
div#copybox { width:600px; height:auto;}
div#sharebox {height:auto; width:600px; margin-top:20px;}
</style>
<link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/share.css?v=<?php echo YOURLS_VERSION; ?>" type="text/css" media="screen" />
<script src="<?php echo YOURLS_SITE; ?>/js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="<?php echo YOURLS_SITE; ?>/js/ZeroClipboard.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>
<script type="text/javascript">ZeroClipboard.setMoviePath( '<?php echo YOURLS_SITE; ?>/js/ZeroClipboard.swf' );</script>
<script src="<?php echo YOURLS_SITE; ?>/js/share.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>
</head>
<body>
<h1>YOURLS: Your Own URL Shortener</h1>
<div id="container">
<?php
// Part to be executed if FORM has been submitted
if ( isset($_REQUEST['url']) ) {
$url = yourls_sanitize_url( $_REQUEST['url'] );
$return = yourls_add_new_link( $url );
$shorturl = isset( $return['shorturl'] ) ? $return['shorturl'] : '';
echo <<<RESULT
<h2>URL has been shortened</h2>
<p>Original URL: <code>$url</code></p>
<p>Short URL: <code>$shorturl</code></p>
RESULT;
// Part to be executed when no form has been submitted
} else {
$site = YOURLS_SITE;
echo <<<HTML
<h2>Enter a new URL to shorten</h2>
<form method="post" action="">
<p><label>URL: <input type="text" name="url" value="<?php echo selfURL(); ?>" size="70" /></label></p>
<p><label>Optional custom keyword: $site/<input type="text" name="keyword" size="8" /></label></p>
<p><label>Optional title: <input type="text" name="title" size="57" /></label></p>
<p><input type="submit" value="Shorten" /></p>
</form>
HTML;
}
?>
</div>
<?php print(selfURL()); ?>
</body>
</html>

Try this,
<input name="textVal" type="text" val=<?php echo selfURL(); ?> />

You can use like below.
Method 1
<input name="myinput" type = "text" value = "<?php print(selfURL()); ?>" />
Method 2
<input name="myinput" type = "text" value = "<?php echo selfURL(); ?>" />
Answer after question has been updated
<input type="text" name="" id="" value="<?php echo $_SERVER['PHP_SELF']; ?>"/>

below is the solution : $_SERVER['PHP_SELF'];
Tested Code is as below
<input type="text" name="" id="" value="<?php echo $_SERVER['PHP_SELF']; ?>"/>
your code edit
$var = $_SERVER['PHP_SELF'];
OR
$var = selfURL();
<p><label>URL: <input type="text" name="url" value="$var" size="70" /></label></p>
You are adding php inside her-doc syntax and that's the error

Related

I got a problem with select option and value

I try to keep the value from selected options after the button is clicked.
For now, I have done this with my inputs(range,text) and it's working but I can't figure how to do this with my select option.
ADDITIONAL THINGS(you have to create them to run it)
c13ustawienia.php
<?php
$serwer='localhost';
$uzytk='root';
$haslo='';
$baza='komis';
?>
c13dane.txt
1993|Volkswagen|Passat|19000
1973|Opel|Blitz|12000
1997|Volkswagen|Passat|17000
2010|Mercedes|M5|29000
2001|Volkswagen|Passat|29000
1990|Volkswagen|Passat|23000
2018|Tesla|Super|129000
2018|sla|Super|9000
1992|Volkswagen|Passat|10000
2006|Audi|B9|74000
2009|Volkswagen|Passat|89000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Baza</title>
<style>
table {border-collapse: collapse;}
td,th {border: 1px blue solid;}
th {background-color: azure;}
.id {width: 20px; text-align: center;}
.mar {width: 90px;}
.mod {width: 70px;}
.rok {width: 40px; text-align: right;}
.cena {width: 50px; text-align: right;}
.zolty {background-color: yellow;}
.pomar {background-color:orange;}
[type=text] {width:60px;}
header {height: 60px; background-color:greenyellow;}
header>img {height: 75%; text-align: center;}
nav {height: 400px; width: 30%; background-color:khaki;
float: left;}
main {height: 400px; width: 70%; background-color:moccasin;
float: left;}
footer {height: 40px; background-color: powderblue;
clear: both; text-align: center; color:blue;}
</style>
<script>
function wartosc() {
min=document.getElementById('cmin');
max=document.getElementById('cmax');
wmin=document.getElementById('wmin');
wmax=document.getElementById('wmax');
minint=parseInt(min.value);
maxint=parseInt(max.value);
if(maxint<minint)
maxint=minint+1;
wmin.value=minint;
min.value=minint;
wmax.value=maxint;
max.value=maxint;
}
</script>
</head>
<body>
<?php
function tworz_baze() {
require('c13ustawienia.php');
$link=mysqli_connect($serwer, $uzytk, $haslo);
mysqli_query($link, "DROP DATABASE $baza");
mysqli_query($link, "CREATE DATABASE $baza");
mysqli_query($link, "USE $baza");
mysqli_query($link, "CREATE TABLE auta (
ID int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
marka varchar(20),
model varchar(25),
rok int(4),
cena double)");
return $link;
} // tworz_baze()
function czytajdane($plik) {
$f=fopen($plik, 'r');
while(!feof($f)) {
$linia=rtrim(fgets($f));
if(strlen($linia)>5)
$tab[]=explode('|', $linia);
}
return $tab;
} // czytajdane($plik)
function dobazy($link, $tablica) {
foreach ($tablica as $sam) {
list($rok, $mar, $mod, $cena)=$sam;
mysqli_query($link, "INSERT INTO auta VALUES
(NULL, '$mar', '$mod', $rok, $cena)");
}
} // dobazy($link, $tablica)
function pisz($li, $marka, $cenamin, $cenamax) {
echo "<h3>Wybrano:<br>marka: $marka<br>
zakres cen: $cenamin - $cenamax zł</h3>";
echo "<table>
<tr><th>id</th><th>marka</th><th>model</th>
<th>rok</th><th>cena</th></tr>";
$wyn=mysqli_query($li, "SELECT * FROM auta WHERE
marka='$marka' AND cena>=$cenamin AND cena<=$cenamax");
$licznik=FALSE;
while($wiersz=mysqli_fetch_array($wyn)) {
list($id, $mar, $mod, $rok, $cena)=$wiersz;
$kolor = $licznik ? 'zolty' : 'pomar';
echo "<tr class=\"$kolor\"><th class=\"id\">$id</td>
<td class=\"mar\">$mar</td>
<td class=\"mod\">$mod</td>
<td class=\"rok\">$rok</td>
<td class=\"cena\">$cena</td></tr>";
$licznik=!$licznik;
}
echo '</table>';
mysqli_close($li);
} // pisz($li, $model, $cenamax)
function filtry() {
if(isset($_GET['cmin']))
$tab['cmin']=$_GET['cmin'];
else
$tab['cmin']=0;
if(isset($_GET['cmax']))
$tab['cmax']=$_GET['cmax'];
else
$tab['cmax']=CENAMAKS;
if(isset($_GET['marka']))
$tab['marka']=$_GET['marka'];
else
$tab['marka']='Volkswagen';
return $tab;
} // filtry()
function lista($link) {
$w=mysqli_query($link, "SELECT DISTINCT marka
from auta ORDER BY marka");
while($m=mysqli_fetch_array($w))
echo '<option value="'.$m['marka'].'">'
.$m['marka'].'</option>';
// $x=$m['marka'];
// "<option value=\"$x\">....
} // lista($link)
?>
<header>
<img src="auto.png" alt="auto">
<span>Komis samochodowy</span>
</header>
<nav>
<h3>Filtry:</h3>
<form action="c41.php" method="GET">
Cena:<br>
od: <input type="range" name="cmin" id="cmin"
min="0" max="<?php echo CENAMAKS ?>" value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
do :<input type="range" name="cmax" id="cmax"
min="0" max="<?php echo CENAMAKS ?>"
value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
<input type="text" name="wmin" id="wmin" disabled
value="<?php echo $tf['cenamin'];?>"
> -
<input type="text" name="wmax" id="wmax" disabled
value="<?php echo $tf['cenamax'];?>"
><br>
<select name="marka" id="marka">
<?php lista($li); ?>
</select>
<input type="submit" value="Filtruj">
<input type="reset" value="Czyść">
</form>
</nav>
<main>
<?php pisz($li, $tf['marka'], $tf['cmin'], $tf['cmax']); ?>
</main>
<footer>
Adam Kowal ©
</footer>
</body>
</html>
To make inputs work I have giving them variable of function and pointed right key of database to have what I want, but i have no clue how to make it work with select option
frame of code that gives me what i want in inputs: value="<?php echo $tf['cenamin'];?>"
Change your code with the following:
First add a new parameter to the "lista" function to be able to mark the selected value, e.g.
function lista($link, $selected = "default") {
// function code here
}
Secondly, modify the function to respect the passed value and match it to the value gotten from the database:
while($m=mysqli_fetch_array($w)) {
$status = "";
if ($selected == $m['marka']) $status = "selected";
echo '<option '.$selected.' value="'.$m['marka'].'">' .$m['marka'].'</option>';
}
Thirdly, pass the selected value to the function in your code, e.g.:
<?php lista($li, $_GET['marka']); ?>
NB! You should NOT use your current code in any production environments: it includes several SQL injections and isn't built up by best practises (e.g. separating html from the program code etc).

Convert eBay Link Generator results into bitly.com link

I managed a small PHP script that takes the eBay product searched and converts it into promote eBay link.
It goes like this:
user searches for example: ocz vertex
clicks on "Submit" and gets the results in following format
http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz
vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg
(Can't fix that space in the link generated between ocz and vertex words)
Now, the result is nice, but I want to shorten it via bitly.com account using their API.
Basicly I want it to generate and convert the full eBay link results into small bitly.com link (http://ebay.to/2scU91k for example) and to see that link on my bitly account.
The process would go like this:
User search for term like ocz vertex
click on "Submit"
get the ebay.to short link (while the real process is in background,
converts to rover.ebay.com address and then to ebay.to using my
bitly.com credentials)
I found that and that and especially that, but didn't understand how do I implement the results as a new bitly convert.
Here's the PHP code:
<!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>
<link rel="stylesheet" type="text/css" href="css/screen.css">
<style type="text/css">
body{
margin:0px;
font-size:0.7em;
font-family:trebuchet ms;
color:#222;
}
#mainContainer{
width:840px;
margin:5px;
}
table,tr,td{
vertical-align:top;
}
.textInput{
width:300px;
}
html{
margin:0px;
}
.formButton{
width:75px;
}
textarea,input,select{
font-family:helvetica;
}
i{
font-size:0.9em;
}
</style>
<script language="Javascript">
<!--
var copytoclip=1
function HighlightAll(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
if (document.all&&copytoclip==1){
therange=tempval.createTextRange()
therange.execCommand("Copy")
window.status="Contents highlighted and copied to clipboard!"
setTimeout("window.status=''",1800)
}
}
//-->
</script>
</head>
<table width="80%" height="100px" align="center" style="margin:0 auto"><tr><td align="center">
<h2>Link Generator Online</h2>
</td><tr></table>
<table width="80%" align="center" style="margin:0 auto"><tr><td align="center">
</div>
</td><td valign="top">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<br>
URL<br>
<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url" size="20">
<br>
<br>
<input type="SUBMIT" name="submit" VALUE="Submit">
</form>
</td></tr></table>
<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name=array($url);
foreach ($name as $name)
{
if (ereg("^\.",$url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\<", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\[", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\'", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\#", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (ereg("\`", $url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (!strlen($url)) {
echo "<br><center><font color=\"red\">Empty Field.</center>";
Die();
}
if (strlen($url) > 100) {
echo "<br><center><font color=\"red\">The field cannot contain more than 150 characters.</center>";
Die();
}
}
?>
<br>
<center>
<form name="vini">
<a class="highlighttext" href="javascript:HighlightAll('vini.select1')">Select All</a><br>
<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=<?php echo $url ?>&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg
</textarea>
<br>
</form>
<?php
}
?>
</body>
</html>
See on live: Ebay link Generator
I built a small solution that works without external libraries. It essentially boils down to this:
Acquire an API key from the "Register an application" dashboard or an oauth token from the oauth API
Make the request to the /v3/shorten API endpoint with your token and URL
First step: Get the token
You only need to do this once. Bitly's documentation lists a few examples how you can do it using curl, I think that is the easiest way. You could also do it with PHP. Simply make this POST request (taken from here):
curl -u "username:password" -X POST "https://api-ssl.bitly.com/oauth/access_token"
The result is something like this:
e663e30818201d28dd07803e57333bed4f15803a
That is your token.
Second step: Make the request
Insert the token and url-encoded URL into the HTTP request to the /v3/shorten endpoint:
<?php
$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=ocz%20vertex&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg"
$token = "e663e30818201d28dd07803e57333bed4f15803a"; // change this
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url)."";
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];
echo $short_url;
?>
The result of the API call is JSON and needs to be decoded. An example is in the documentation. This code example does not take into consideration API timeouts or other errors that might occur (such as token expiry, which is currently not an issue).
The complete code:
<!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>
<link rel="stylesheet" type="text/css" href="css/screen.css">
<style type="text/css">
body{
margin:0px;
font-size:0.7em;
font-family:trebuchet ms;
color:#222;
}
#mainContainer{
width:840px;
margin:5px;
}
table,tr,td{
vertical-align:top;
}
.textInput{
width:300px;
}
html{
margin:0px;
}
.formButton{
width:75px;
}
textarea,input,select{
font-family:helvetica;
}
i{
font-size:0.9em;
}
</style>
<script language="Javascript">
<!--
var copytoclip=1
function HighlightAll(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
if (document.all&&copytoclip==1){
therange=tempval.createTextRange()
therange.execCommand("Copy")
window.status="Contents highlighted and copied to clipboard!"
setTimeout("window.status=''",1800)
}
}
//-->
</script>
</head>
<table width="80%" height="100px" align="center" style="margin:0 auto"><tr><td align="center">
<h2>Link Generator Online</h2>
</td><tr></table>
<table width="80%" align="center" style="margin:0 auto"><tr><td align="center">
</div>
</td><td valign="top">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<br>
Insert keywords:<br>
<input type=text style="font-size: 13px; font-family: tahoma,arial; font-weight: bold; color: #000000; BORDER: #555 1px solid ; BACKGROUND-COLOR: #FFF" input name="url" size="20">
<br>
<br>
<input type="SUBMIT" name="submit" VALUE="Submit">
</form>
</td></tr></table>
<?php
if(isset($_POST['submit'])){
$url = $_POST['url'];
$name = array($url);
foreach ($name as $name) {
if (preg_match("/^[\.\<\[#`]/",$url)) {
echo "<br><center><font color=\"red\">Invalid Characters.</center>";
Die();
}
if (!strlen($url)) {
echo "<br><center><font color=\"red\">Empty Field.</center>";
Die();
}
if (strlen($url) > 100) {
echo "<br><center><font color=\"red\">The field cannot contain more than 150 characters.</center>";
Die();
}
}
$ebay_url = "http://rover.ebay.com/rover/1/711-53200-19255-0/1?icep_ff3=10&pub=5575165347&toolid=10001&campid=5337851510&customid=&icep_uq=".urlencode($url)."&icep_sellerId=&icep_ex_kw=&icep_sortBy=15&icep_catId=&icep_minPrice=&icep_maxPrice=&ipn=psmain&icep_vectorid=229466&kwid=902099&mtid=824&kw=lg";
$token = "e663e30818201d28dd07803e57333bed4f15803a";
$endpoint = "https://api-ssl.bitly.com/v3/shorten?access_token=".$token."&longUrl=".urlencode($ebay_url);
$result = file_get_contents($endpoint);
$json = json_decode($result, true);
$short_url = $json["data"]["url"];
?>
<br>
<center>
<form name="vini">
<a class="highlighttext" href="javascript:HighlightAll('vini.select1')">Select All</a><br>
<textarea name="select1" rows=3 cols=75 style="font-family:tahoma;color:#555;border:1px dashed #ccc">
<?php echo $short_url; ?>
</textarea>
<br>
</form>
<?php
}
?>
</body>
</html>
Note: I changed your ereg calls to preg_match for compatibility with PHP7 and shortened the ifs with a regular expression. I also used urlencode($url) so that spaces won't break the link.

Using jquery- $.post(); inside php- foreach() function, to send variable data to URL file

I am trying to delete files inside folder, using delete_file.php, which is action file offcourse. It can recieve data as $_POST['filename1'] only, but for every foreach() iteration , this value is getting over-written. Any suggestions, what else can SOLVE this subject? Thanks in Advance.
Problem:
delete_file.php is catching filename1 as $_POST['filename1']
But with each foreach iteration, filename1 is getting over-written.
And delete_file.php, is deleting LAST ENTRY ONLY, EVERY TIME.
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!--[if lte IE 8]>
<script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css"/>
<!--[if lte IE 8]>
<link rel="stylesheet" href="assets/css/ie8.css"/><![endif]-->
<!--[if lte IE 9]>
<link rel="stylesheet" href="assets/css/ie9.css"/><![endif]-->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.leanModal.min.js"></script>
</head>
<body class="no-sidebar">
<table border="1px solid" style="text-align:center; margin-left:auto; margin-right:auto; width:900px">
<tr>
<th><strong>S.No</strong></th>
<th><strong>Image-Name</strong></th>
<th><strong>Image/Logo</strong></th>
<th><strong>Image Size</strong></th>
<th><strong>Action</strong></th>
</tr>
<?php
$dirname = "../assets/img/logos/";
$images = glob($dirname . "*.{jpg,png,gif,tiff,jpeg,JPG}", GLOB_BRACE);
$sn = 1;
foreach ($images as $image) {
$imageName = str_replace("../assets/img/logos/", "", $image);
$variable_id = str_replace(".", "_", $imageName);
?>
<!---///////////////////// IMAGE-<?= $sn++ ?> STARTS //////////////////////----------->
<tr>
<td><?= $sn++ ?></td>
<td><?php echo $imageName; ?></td>
<td><img src="<?php echo $image; ?>" width="150px" height="100px"/></td>
<td><?php echo filesize($image) / 1000 . " KB"; ?></td>
<!-------
<td>
<a id="delete" href="delete_plogos.php?filename=<?//=$imageName ?>" style="color:#D00A0D"><strong>Delete</strong></a>
</td>
-------->
<td>
<p style="text-align: center; font-size: 10px; margin-top: 5px;">
<a id="modaltrigger_<?= $variable_id ?>" href="#<?= $variable_id ?>" class="btn"
style="border: none !important;">Delete</a>
</p>
</td>
</tr>
<!----------------------popup for delete----------------------->
<div id="<?= $variable_id ?>" class="popupContainer" style="display:none;">
<header class="popupHeader" style="background: #F4F4F2;
position: relative;
padding: 10px 20px;
border-bottom: 1px solid #DDD;
font-weight: bold; height: 55px;">
<span class="header_title">Delete</span>
<span class="modal_close"><i class="fa fa-times"></i></span>
</header>
<section class="popupBody">
<!-- Register Form -->
<div class="deleteplogo_<?= $variable_id ?>">
<form id="newpageform_<?= $variable_id ?>" name="newpageform_<?= $variable_id ?>" method="post">
<input name="filename_<?= $variable_id ?>" id="filename_<?= $variable_id ?>" type="text" style="display:none"
value="<?= $imageName ?>"/>
<p><strong><?= $imageName ?> - Image will be deleted Permanently. <br/>Proceed
?</strong></p>
<br/>
<div class="action_btns">
<div class="one_half" style="float:none;">
<a id="ajax-submit_<?= $variable_id ?>" class="btn btn_red" style="cursor: pointer"
>Yes! I
Agree
.Delete</a></div>
</div>
</form>
</div><!--------delete_plogo----------->
</section>
</div> <!----------------------#modal ENDS----------------------->
<!---------------- delete image : pop up ------------------------------>
<script type="text/javascript">
var magica = "<?php echo $variable_id; ?>";
$('#modaltrigger_' + magica).leanModal({top: 200, overlay: 0.6, closeButton: ".modal_close"});
$(function () {
$('#modaltrigger_' + magica).click(function () {
$('.deleteplogo_' + magica).show();
return false;
});
})
/////// 3.) AJAX-FORM SUBMIT - + then reload
$("#ajax-submit_"+magica).click(function () {
var filename = $("#filename_"+magica).val();
if (filename == '') {
alert("File doesn't EXIST....!!");
} else {
$.post("delete_plogos_action.php", {filename1: filename}, function (data) {
$("span.modal_close > i").trigger("click"); // to auto-close leanModal window
alert(data).fadeOut("slow");
window.location=trustedpartners_listviewdel_logos.php;
//close_modal("modal");
});
}
});
</script>
<!---///////////////////// IMAGE-ENDS //////////////////////----------->
<?php
}
?>
</table>
</body>
</html>
You can try something like removing the php loop:
<script type = "text/javascript" >
$(function() {
$('div[id^="modaltrigger_"]').leanModal({
top: 200,
overlay: 0.6,
closeButton: ".modal_close"
});
$('div[id^="modaltrigger_"]').click(function() {
magica = $(this).attr('id').split('_')[1];
$('.deleteplogo_' + magica).show();
return false;
});
})
$('div[id^="ajax-submit_"]').click(function() {
magica = $(this).attr('id').split('_')[1];
var filename = $("#filename_" + magica).val();
if (filename == '') {
alert("File doesn't EXIST....!!");
} else {
$.post("delete_file.php", {
filename1: filename
}, function(data) {
$("span.modal_close > i").trigger("click");
//alert(data).fadeOut("slow"); damn you can't fade out a alert box :))
window.location = mypage.php;
} // else ends here
});
}); < /script>
A better solution will be to replace the ids with a class and append a data-attribute to the elements iwth the value of magica
Deleted all AJAX-JQUERY code & used :
file1.php
<td>
<p style="text-align: center; font-size: 10px; margin-top: 5px;">
<a id="modaltrigger_<?= $variable_id ?>" href="delete.php?id=<?php echo $imageName; ?>" class="btn"
style="border: none !important;">Delete</a>
</p>
</td>
delete.php
<?php
$filePath = "D:/folder/".$_GET['id'];
if(is_file($filePath)){
#unlink($filePath);
echo ('<strong>SUCCESS! Deleted: <span style="color:red">'. $_GET['id']. '</span>, file from Directory</strong>');
}
else if(!unlink($filePath)){
echo ("Error deleting file : ". $_GET['id']. " Already deleted OR doesn't EXIST");
}
?>
Worked like Charm ! Thanks !

Using PHP to submit survey-form to database

I am setting up a survey to go at the bottom of our FAQ page, I am new to PHP, and this is my first time trying to connect to the database (without a tutorial).
I have the HTML page set up, a PHP set up, and a table set up in MySQL.
The database is creating a new row every time I submit, but all of the rows have "0" instead of the values assigned to the inputs/divs. Please help!
EDIT: I updated the HTML to now be a form, however, when I submit I get a 404 (and the rows do not update at all. What could be wrong?
Here is the HTML:
<?php
//error_reporting(0);
require 'db/connect.php';
?>
<!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">
<html>
<head>
<title>State Requirements Feedback</title>
<!--<link rel='stylesheet' type='text/css' href='stylesheet.css'/>-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$('.rating').click(function() {
$('.rating').removeClass('selected');
ratingClick(this);
});
});
function ratingClick(that) {
console.log(that.id);
if (that.id == 'rating4' || that.id == 'rating5') {
$('#questions').fadeOut('slow');
$('#thankYou').fadeIn('slow');
} else {
$('#getMore').fadeIn();
$(that).toggleClass('selected');
}
}
$(document).ready(function() {
$('#submit').click(function(){
$('#questions').fadeOut('slow');
$('#thankYou').fadeIn('slow');
});
});
</script>
<style>
.ratings {
float: left;
width: 100%;
}
.rating {
margin: 7px;
font-weight: bold;
background-color: aliceblue;
}
.rating:hover {
background-color:#990000;
color: white;
}
#getMore {
display:none;
clear:both;
background-color:aliceblue;
border:solid black 1px;
padding:0px 5px 5px 10px;
margin:0px 0px 0px 7px;
}
#thankYou {
display:none;
font-weight: bold;
}
.selected {
background-color: #990000;
color: white;
}
textarea {
resize: none;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
}
h2 {
margin-bottom: 5px;
font-size: 12px
}
</style>
</head>
<body>
<form id="questions" action="connect.php" method="post">
<h2>How helpful is this article?</h2>
<div class="ratings">
<input type="radio" name="Q1" class="rating" id="rating1" value="1">Not at all helpful
<input type="radio" name="Q1" class="rating" id="rating2" value="2">Not very helpful
<input type="radio" name="Q1" class="rating" id="rating3" value="3">Somewhat helpful
<input type="radio" name="Q1" class="rating" id="rating4" value="4">Very helpful
<input type="radio" name="Q1" class="rating" id="rating5" value="5">Extremely helpful
</div>
<div id="getMore">
<h2>Please tell us why you didn't find this article helpful:</h2>
<input type='checkbox' name="Q2_1" value="1">Not related to my issue<br/>
<input type='checkbox' name="Q2_2" value="1">Too complicated explanations<br/>
<input type='checkbox' name="Q2_3" value="1">Too much information<br/>
<input type='checkbox' name="Q2_4" value="1">Incorrect information<br/>
<input type='checkbox' name="Q2_5" value="1">Unclear information<br/>
<input type='checkbox' name="Q2_6" value="1">Incomplete information<br/>
<h2>Do you have any other feedback about this article?</h2>
<p><input type="text" name="Q3" /><p>
<div id = "submit"><input type='submit' value="Submit" /></div>
</div>
</form>
<div id="thankYou">
Thanks for your feedback!
</div>
</body>
</html>
Here is the php document:
<?php
define('DB_NAME', 'staterequirements');
define('DB_USER', 'myuser');
define('DB_PASSWORD', 'mypass');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected) {
die('Can\'t use ' . DB_NAME . ' : ' . mysql_error());
}
$Q1 = (isset($_POST['Q1']) ? $_POST['Q1'] : null);
$Q2_1 = (isset($_POST['Q2_1']) ? $_POST['Q2_1'] : null);
$Q2_2 = (isset($_POST['Q2_2']) ? $_POST['Q2_2'] : null);
$Q2_3 = (isset($_POST['Q2_3']) ? $_POST['Q2_3'] : null);
$Q2_4 = (isset($_POST['Q2_4']) ? $_POST['Q2_4'] : null);
$Q2_5 = (isset($_POST['Q2_5']) ? $_POST['Q2_5'] : null);
$Q2_6 = (isset($_POST['Q2_6']) ? $_POST['Q2_6'] : null);
$Q3 = (isset($_POST['Q3']) ? $_POST['Q3'] : null);
$sql = "INSERT INTO response (Q1, Q2_1, Q2_2, Q2_3, Q2_4, Q2_5, Q2_6) VALUES ('$Q1', '$Q2_1', '$Q2_2', '$Q2_3', '$Q2_4', '$Q2_5', '$Q2_6')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
}?>
These points are parts of your problem.
This:
<div id="questions" action="connect.php" method="post">
should be <form and not a div:
<form id="questions" action="connect.php" method="post">
And this:
<div class="ratings" name="Q1">
<div class="rating" id="rating1" value="1">Not at all helpful</div>
<div class="rating" id="rating2" value="2">Not very helpful</div>
<div class="rating" id="rating3" value="3">Somewhat helpful</div>
<div class="rating" id="rating4" value="4">Very helpful</div>
<div class="rating" id="rating5" value="5">Extremely helpful</div>
</div>
I'm not sure whether you wanted to use a dropdown menu select or checkboxes or radio buttons or inputs, however those divs are not valid form elements.
I would also like to point out that it is highly recommended that you use MySQLi_ and/or PDO instead of the deprecated MySQL_ because your (posted) code is open to injection.

How to process submission without refreshing the page

Hi I am facing some problems in submitting form without refreshing, I know that it has something to do with "return false " but i just dont know where and how to use it. I tried refreshing the page by placing it in (if there are errors) but it just doesnt seem to work. Can you guys help me out??
<?php
$message = '';
$errors = array();
$noErrors = true;
$haveErrors = !$noErrors;
require_once('validations/tradeformresult.php');
if ($noErrors && $userArriveBySubmittingAForm) {
require_once('price.php');// INSERTION
echo "<script type='text/javascript'>\n";
echo "</script>";
echo "<script type='text/javascript'>\n";
echo "alert('Trade is successfully executed!');\n";
echo "</script>";
///////////MESSAGE/////////////////
}
elseif ($haveErrors && $userArriveBySubmittingAForm) {
echo "<script type='text/javascript'>\n";
echo "alert('Please re-enter your parameters.');\n";
echo "return false";
echo "</script>";
}
else if ($userArriveByClickingOrDirectlyTypeURL) { // we put the original form inside the $message variable
$newTitle = 'The link is broken';
$h1Title = '';
$message = '';
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
</script><head><meta charset="UTF-8"></head>
<style type="text/css">
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
text-align: center;
}
div#specialBox {
display: none;
position: relative;
z-index: 3;
p.padding;
padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;
margin: 150px auto 0px auto;
border: 3px solid blue;
outline: 3px solid darkblue;
width: 500px;
height: 500px;
overflow:auto;
background: #FFF;
color: #000;
}
div#wrapper {
position:absolute;
top: 0px;
left: 0px;
padding-left:24px;
}
</style>
<script type="text/javascript">
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox');
overlay.style.opacity = .8;
if(overlay.style.display == "block"){
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
</script>
</head>
<body>
<!-- Start Overlay -->
<div id="overlay"></div>
<!-- End Overlay -->
<!-- Start Special Centered Box -->
<div id="specialBox" style="display:none">
<script>
</script>
<p>Create Order
<p><?php
$timestamp=time(); require_once 'start.php';
?>
<form method="post" name="formSubmitted" **return false;"**>
<input type="hidden" name="formSubmitted" value="true" runat="server">
<?php echo $message; ?>
<?php ?>
<?php if ($haveErrors || $userArriveByClickingOrDirectlyTypeURL) : ?>
<fieldset>
<p>Symbol : <select name = "selection" id="selection">
<option disabled = "disabled" selected = "selected"> Choose one </option>
<option value="eur/usd"<?php If($selection=='eur/usd'){Echo 'selected';}?>>EUR/USD</option>
<option value="usd/jpy"<?php If($selection=='usd/jpy'){Echo 'selected';}?>>USD/JPY</option>
<option value="usd/cad"<?php If($selection=='usd/cad'){Echo 'selected';}?>>USD/CAD</option>
<option value="eur/jpy"<?php If($selection=='eur/jpy'){Echo 'selected';}?>>EUR/JPY</option>
<option value="eur/chf"<?php If($selection=='eur/chf'){Echo 'selected';}?>>EUR/CHF</option>
<option value="gbp/usd"<?php If($selection=='gbp/usd'){Echo 'selected';}?>>GBP/USD</option>
<option value="aud/usd"<?php If($selection=='aud/usd'){Echo 'selected';}?>>AUD/USD</option>
<option value="usd/chf"<?php If($selection=='usd/chf'){Echo 'selected';}?>>USD/CHF</option>
</select><font color="red"><?php echo $selectionError?></font>
<p> Date : <input type="datetime" value="<?php echo date("Y-m-d ",$timestamp); ?>"READONLY name="date"/></p>
<p> Type : <input type="radio" name="type" value="buy"<?php if ($type == 'buy') echo 'checked'; ?>CHECKED> Buy <input type="radio" name="type" value="sell" <?php if ($type == 'sell') echo 'checked'; ?>>Sell<font color="red"><?php echo $typeError;?></font></p>
<p> Size : <input type="number"pattern="[0-9]+([\.|,][0-9]+)?" step="0.01"min="0"name="size"value="<?php echo $size;?>"/><font color="red"><?php echo $sizeError?></font></p>
<p> Bid Price (Sell) : <input id="bidprice" READONLY name="bidprice" type="text" value="<?php echo $bidprice;?>"/><font color="red"><?php echo $bidpriceError?></font></p>
<p> Offer Price (Buy) :<input id="offerprice" READONLY name="offerprice" type="text" value="<?php echo $offerprice;?>"/><font color="red"><?php echo $offerpriceError?></font> </p>
<p> Stop Loss : <input type="number"step="any"min="0" name="stoploss" value="<?php echo $stoploss;?>"/><font color="red"><?php echo $stoplossError?></font></p>
<p> Take Profit : <input type="number"step="any"min="0"name="takeprofit"value="<?php echo $takeprofit;?>"/><font color="red"><?php echo $takeprofitError?></font></p>
</fieldset>
<div align="center">
<input type="submit" value="Submit" Onsubmit =**"return false"**;/><button onmousedown="toggleOverlay()">Close </button>
</div>
<input type="reset" name="Reset" value="Reset" tabindex="50">
<?php endif; ?>
</form>
</script>
</body>
</html></p>
</div>
</div>
<!-- Start Special Centered Box -->
<!-- Start Normal Page Content -->
<div id="wrapper">
<h2>Trade</h2>
<button onmousedown="toggleOverlay();**return false;"**>Create Order</button>
</div>
<!-- End Normal Page Content -->
</body>
</html>
<?php
?>
Unless you are using AJAX, you can't really do this from PHP. Once a form submits, that's it. Simple validation can be done in the browser. Bind a validation function to your form's submit event. That's the thing you return false or true from.
(You would of course validate again on the server.)
It looks from your code like you're trying to run some php code (tradeformresult.php). Loading it this way isn't going to work as expected-that require_once will be run as the page is being built in PHP, not in the browser.
For sending a form without refreshing the page, you should look into AJAX (http://en.wikipedia.org/wiki/Ajax_(programming))
JQuery has a good AJAX method. Here is a simple example of how to use it:
$.ajax({url:"http://www.someserver.com/api/path",
data:{val1:"value",val2:"value"})
.success(function(returnData) {
console.log(returnData);
});
The above will call the given URL with the given data as parameters, then, if successful, will return whatever data the server gave back into the returnData variable.
If you're using AJAX, you don't really even have to use a <form> tag, since you'll be building the query string manually. You can have the function that makes the AJAX call be triggered from the onClick event of a button.

Categories