How to refresh page and send variable - javascript

i have a php page where i press a button to edit on another page the mysql db records:
page name 'distintaBase.php'
here there is a list of names that are products name. Each product cointains a list of components.
When i press the edit button for one product i'm redirect to the new page 'modifDistBase.php'.
the $dist_base variable is passed to the new page. I use it on the page title
<h2>Modifica distinta base <?php echo $_GET['dist_base']; ?></h2>
and then to load the mysql db
<?php
$dist_base = $_GET['dist_base'];
$sql = "SELECT $dist_base.Id, $dist_base.Designator, $dist_base.Quantity, $dist_base.Description, $dist_base.Package,
$dist_base.Manufacturer, $dist_base.Pn_Manufacturer, $dist_base.Pn_Utterson, $dist_base.Mounted
FROM $dist_base";
?>
pressing ADD button i add a new component
if(isset($_POST['add_item'])){
$designator = $_POST['designator'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$package = $_POST['package'];
$manufacturer = $_POST['manufacturer'];
$pn_manufacturer = $_POST['pn_manufacturer'];
$pn_utterson = $_POST['pn_utterson'];
$mounted = $_POST['mounted'];
$sql = "INSERT INTO $dist_base (designator,quantity,description,package,manufacturer,pn_manufacturer,pn_utterson,mounted)
VALUES ('$designator','$quantity','$description','$package','$manufacturer','$pn_manufacturer','$pn_utterson','$mounted')";
if ($conn->query($sql) === TRUE) {
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
} else {
echo "Errore: " . $sql . "<br>" . $conn->error;
}
}
there is something wrong probably on the javascript.
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
the new component is added to the database (for example with #5 id) but do not appear on the page modifDistBase.php
if i press refresh on the browser or f5 now i can see the new component (#5 id) but on the database a new one is added #6 with the same items as #5
PS
- header is already sent by menĂ¹ page
- have tried window.location.href with same result

Why don't you try with:
header('Location: modifDistBase.php?dist_base='.$dist_base);
instead of echo javascript you can redirect immediatelly to the page + the variable

there are some thing to fix on your code
Note the javascript you output with
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
will be precisely
<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>
Without checking the correctness of the js related to your goal, it's immediate to see you should write instead
echo '<script>window.location.replace("modifDistBase.php?dist_base="' . $dist_base . '")</script>';
to inject the php value into the javascript string.
(you've also forgot a double quote b.t.w)
If you have doubts regarding your javascript, you can inspect the page on the browser and look at it (right click and "inspect element" or "analyse element").
Mind it is not recommended that you take the user input and use it as it is in an SQL instruction. You should do some sanification and use a prepared statement or escape the values before putting them in the sql.
That said, the javascript redirection you do looks a bit odd, maybe you can redirect from the php script without asking the client to do so. Look at the header php function for instruction about redirection done server side.

Related

A safety concern about clicking a div and then updating mysql database with ajax

I'm using php to instantiate a number of divs depending on how many folders there are in a directory.
And each such directory has a number of pictures in there and I'm just getting the first one to set as image in the currently instantiated div.
<?php
$dir = "../assets/wallpapers/pc/";
$themes = array_diff(scandir($dir), array('.', '..'));
foreach ($themes as $t) { ?>
<?php
$tdir = $dir . $t;
$imgdir = $tdir . "/" . scandir($tdir)[2];
?>
<div class="div_5" onclick="select_theme('<?=$t;?>');">
<img src="<?=$imgdir;?>">
<div><span><?=ucwords($t);?></span></div>
</div>
<?php } ?>
I know it's a bit confusing but my concern is that on the div onclick event, I call a javascript function (select_theme) and as it's parameter I'm passing a php variable $t. The select_theme function basically gets the parameter and sends a ajax post to update the database. My concern is that when I go F12 on the browser I can change the select_theme parameter manually and therefore I'm scared that in that way the person would be able to type anything and the ajax would send whatever string the person wants.... and so on. Is this the proper way to do this?
SOLVED! Look at Nick's comment.

Sql queries doesnt work when inside a php function

So the main problem is, when i make some query just after a post[] or whatever and its just in the main code of the php (not in a function) it works perfectly fine..
But, when i try and have that query inside a php function,it never works, and kinda hiding any other code on the rest of the page... I have a few divs after that php and sql query code, and they just dont show when i try to query through the function..
<script type="text/javascript">
function callPhpVoteAdd(name) {
var result = <?php voteAdd(name); ?>;
alert(result);
return false;
}
</script>
<?php
echo '</br>';
$allsql = "SELECT * FROM voting ORDER BY votes DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo '<form method="post">
name: "' .$name. '" - votes: "' .$votes. '" <input type="submit" name="'.$name.'" value="'.$name.'" onclick="callPhpVoteAdd(this.name)"/><br>
</form>';
}
}
function voteAdd($name) {
if($conn->query("UPDATE voting SET votes = votes + 1 WHERE name = '".$name."' ") === TRUE) {
echo "<script>alert('fuck yeah');</script>";
}
echo "shit";
}
So the button pressed calls the js function, which calls the php function
I guess you're misunderstanding the way JS and PHP works. PHP works server side, and JS, in your case, client side. And so, PHP generate the script/page before it's sent to the browser, so when JS runs it, all the <?php ?> are already replaced by static data.
So, to put it shortly and simply, you just can't call a PHP function from JS after your page is loaded, the way you tried to (because the call isn't there anymore - check your source code from your browser).
You need either to :
use a form with an "action" attribute ; this will send the data to server, and call the php script set in "action", where you can handle the sent data, and then reload the page with the new/updated data,
use ajax (almost the same thing : this sends data to server and call a php script to handle them, but instead of reloading the page, the output of the PHP script - with the data you need - will be sent back to JS, to a callback function, where you'll be able to use them to modify the page).

Using php no captcha recaptcha code in Smarty

i have a custom website, no CMS, and this website uses Smarty. The website allow users to register and uses an old image captcha system.
To disallow bots registrations, i will implement new Google No Captcha Recaptcha plugin, ( more info here: https://www.google.com/recaptcha/ ).
So i decided to follow this tutorial: https://webdesign.tutsplus.com/tutorials/how-to-integrate-no-captcha-recaptcha-in-your-website--cms-23024
I have no problem in first steps: register on Google and obtain Site Key and Secret Key.
Also no problem in following steps: insert JavaScript API and div box in register.tpl smarty template file .
My problem is in the final steps, send to Google response so it can verify it.
This was no problem in normal website to put php code in register.php normal php page.
But on Smarty Template, so in register.tpl, it gives me fatal errors, also if i use {php}{/php} special tags
<?php
// grab recaptcha library
require_once "recaptchalib.php";
// your secret key
$secret = "0000000000000000000000000000000000";
// empty response
$response = null;
// check our secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
?>
And this:
<?php
if ($response != null && $response->success) {
echo "Hi " . $_POST["name"] . " (" . $_POST["email"] . "), thanks for submitting the form!";
} else {
?>
<?php } ?>
I think the solution is to put this code in register.php page and import it in register.tpl page, but i am a beginner, can you please transform this code for me ?
I am sure this code will be useful for many users around the web.
php
require_once ('recaptchalib.php');
$mypublickey = "456723345";
$smarty->assign("captcha", recaptcha_get_html($mypublickey));
tpl
{$captcha}
http://devcodepro.com/view/22/8/reCaptcha-with-smarty

PHP refreshing using jQuery doesn't work in IE

I wanted to create a function in javascript/jQuery, that uses php script to refresh some data on my website. I'm using it like this:
function aval()
{
...
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d);
setTimeout(aval,200);
}
where #dost refers to some div at the end of my site
Then, my readadmin.php file looks like this:
<?php
$diff=$_GET["diff"];
$name = $_GET["date"];
$dtyg = $_GET["dtyg"];
$plik = fopen("myfile","r");
$tekst = fread($plik,filesize("myfile"));
fclose($plik);
$bookings = explode(";;;;", $tekst);
for ($i=0; $i<(sizeof($bookings)-1); $i++)
$data[$i] = explode(":::",$bookings[$i]);
echo "<script>";
// here I'm echoing some javascript code, that basically changes styles on my page,
//depending on my variables and data from a file
echo "</script>";
?>
Also, on my site (admin.php) I use login, so my site looks like this:
<?php
session_start();
if(!session_is_registered('pass'))
header('location: login.php');
?>
...html code
login.php:
..something not important, forms to get $_POSTs etc..
<?php
if ($_POST["login"] == $login && $_POST["pass"] == $pass)
{
session_register('login');
session_register('pass');
header("location: admin.php");
}
?>
Now, everything works great on Chrome or Firefox, but not on IE. When I change data in my file, IE doesn't react to this, and keep displaying old data. When I put session_start() and session_destroy() at the begining and end of readadmin.php, then data is refreshing properly, but whatever action I do, it logs me out. Nothing strange here, I start a new session every 200ms so I get kicked.
One more thing: when I'm changing data that goes to readadmin.php from site, it displays proper data back, and then immediately changes to old data.
Please help.
You can add timestamp to url so the browser will not cache the file:
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d+"&t="+Date.now());

how could I automatically update a query php or javascript

I am making a php mysql query, what I want is that actualize automatically each time you enter a data and not have to do it for the browser
this is the query in php:
<?php
include "conexion.php";
$consulta ="SELECT subject,tid,username FROM mybb_threads ORDER BY tid DESC LIMIT 15";
$resultado = mysql_query($consulta)
echo "<table border='0'><td>";
while($fila = mysql_fetch_array($resultado)){
echo " <div >
<a target='_parent' href='showthread.php?tid=".$fila['tid']."'> " . $fila["subject"] ."</a></td><tr><td>Por: " .$fila["username"]."</div><br>";
}
echo '</td></table>';
mysql_close($enlace);
?>
How could I do that automatically actualize?
regards
excuse is that I speak Spanish almost do not understand the English
if you update data automatically
If I understand you correctly, you want the query to be executed automatically each time there is new data in your table or database. Meaning, if you get new information in the table "mybb_threads", you want the user to see this new data without updating the browser.
To achieve this you need to work with Javascript, and something called Ajax. Bascally what you do is that every minute or whatever, you force the browser to call a php file.
You can read more here about the jQuery .ajax() function which is a great place to start:
http://api.jquery.com/jQuery.ajax/
You can also check out the Wiki that explain the method quite good:
http://en.wikipedia.org/wiki/Ajax_(programming)

Categories

Resources