Why doesn't my page refresh on form submit? - javascript

I've made a simple quiz application with one question to answer; when the user submits the form the answer is posted to a MySQL database. Then a function is run that does a database query and translates the data in the database table to JSON, which I then visualize using a D3 script.
The full code is here on github and I've included snippets below.
My question: index.php page first loads, a D3 script takes the JSON and builds a small bar chart which is displayed next to the from. Screenshot is here.
The problem I am having is that after the user submits the form, although the database is updated correctly, the page isn't refreshed. This means the JSON and the bar chart aren't updated.
I have to manually refresh (command-r) in order to see the correct (updated) visualization.
What I am trying to accomplish: to get the chart to refresh when "Submit" is pressed so the updated results are presented to the user.
I don't know what I'm doing wrong and could use a pointer on whether I need to be looking at the PHP or JavaScript side to get the chart to refresh (and the page to reload the updated JSON) on form submit.
Index.php:
<form action="form.php" method="post">
<fieldset>
<legend>Choose your favourite option:</legend>
<label>Susan <input type="radio" name="author" id="Susan" value="Susan"></label><br/>
<label>Camile <input type="radio" name="author" id="Camile" value="Camile"></label><br/>
<input type="submit" value="Save" />
</fieldset>
</form>
main.js
var ele = document.getElementById("form");
if(ele.addEventListener){
ele.addEventListener("submit", reload, false); //Modern browsers
}
else if (ele.attachEvent){
ele.attachEvent('onsubmit', reload); //Old IE
}
function reload() {
window.location.reload();
console.log("reloaded");
drawChart();
};
form.php
include "toJson.php";
$link = mysqli_connect("localhost", "root", "root", "quiz");
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ')' . mysqli_connect_error());
}
$update = "INSERT INTO `quiz`.`answers` (`name`) VALUES ('" . mysqli_real_escape_string($link, $_POST['author']) . "')";
mysqli_query($link, $update);
updateJson();
mysqli_close($link);
toJson.php
$location = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("Location: " . $location);
function updateJson () {
$link = mysqli_connect("localhost", "root", "root", "quiz");
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ')' . mysqli_connect_error());
}
$result = mysqli_query($link, "SELECT * FROM `answers`");
$arr = array();
while($row = mysqli_fetch_array( $result )) {
$arr[] = $row;
print_r($row);
echo "<br/>";
}
//write to json file
$fp = fopen('data.json', 'w');
fwrite($fp, json_encode($arr));
fclose($fp);
mysqli_close($link);
}
updateJson();

Force the javascript to reload, just in case it's trying to read the cache or something:
window.location.reload();
to
window.location.reload(true);
forcedReload Is a Boolean flag, which, when it is true, causes the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

Instead of fixing current solution, i would like to propose a better solution. if you use ajax to post your data to server and get a json response back, which you can use to render your chart. you can also use ajax form plugin to apply to your current form.

Related

How to refresh page and send variable

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.

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).

PHP - How to redirect to the same page and change DOM's

I have an HTML login form and when a user logs in I want to redirect that user to another page and change some DOM's on it.This redirection is done with a PHP script that verifies the user and password.
I have this:
<?php
set_time_limit(0);
header('content-type: text/html; charset=utf-8');
header("access-control-allow-origin: *");
include 'connect.php';
$pass= $_POST['pass'];
$sql = "SELECT password FROM users WHERE password ='$pass'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result);
if($row[0]!='') {
$query = mysql_query("SELECT user FROM users WHERE password ='$pass'");
$user = mysql_fetch_array($query, MYSQL_ASSOC);
$user=$user["user"];
echo "<script>window.location = 'http://localhost/public_html/as/index.php?pass=$pass';document.getElementById('log').innerHTML = 'LOGGED WITH: $user';$('#login-form').slideUp();document.getElementById('logout').style.display='';$('#log').unbind('click');</script>";
} else {
echo "<script>document.getElementById('text').value = ''; document.getElementById('text').placeholder = 'Type a valid key';</script>";
}
?>
This is just to learn how to deal with login-forms, so don't mind about the security thing.
My problem is here:
echo "<script>window.location = 'http://localhost/public_html/as/index.php?pass=$pass';document.getElementById('log').innerHTML = 'LOGGED WITH: $user';$('#login-form').slideUp();document.getElementById('logout').style.display='';$('#log').unbind('click');</script>";
This code redirects to the window.location page but doesn't changes the other DOM's in HTML page.
How can I fix this?
Thanks in advance!
you cant use that link. you have 2 solution for this problem.
use SESSION[] array in php to define user is loged in and in target page , check if your variable in session array was set, echo your javascript on page to do what you want.
use query string to tell target page that user logged in and with php in target page, echo your javascript code.
i think you have better solution for your problem. but in order to your request, that's my offer. :)
EDITED:
in first line of your php file use:
session_start();
when your username and password was pass, set session array like this:
$_SESSION["userName"]=$username;
and the end of php script use it like this:
if(isset($_SESSION["userName"]))
echo "<script>....your code that you want run when user login...</script>";

Script visit not recorded in navigation history and session info not correctly stored

I am developing a custom CRUD for MySql DB´s.
(Please excuse my english)
Note: Edited scripts which were not correctly copied (One was a dupplicate of the first one..
I am trying to prevent Backspace navigation to Insert, update and delete scripts because those can produce insconsitent DB entries.
The CRUD produces list, insert, view, update and delete scripts and additionaly insert_DB, update_DB and delete_DB scripts which carry the appropriate DB functions or would alert the user of an ilegal call to the script and redirect him to the home page.
In order to prevent double execution of those pages, the Insert, update and delete pages record a session variable $_SESSION['Process'] with the intended next process to be executed.
The DB scripts checks for an appropriate $_SESSION['Process'] value and proceed to execute the DB operation. If succesfull the will redirect the browser to the List page for the specific table.
Going forward this works fine. But after the user has been redirected to the table List script, if the user hits "backspace", the user is not redircted to the DB script (which would silently fail and alert the user), but to the calling insert, view or update script, skiping the DB script. The DB script is not recorded in the browser history. Furthermore, The initial List script does not show the correct session value.
For example:
(The examples are limited to show the intended functionality, and do not cover best pratices, nor DB connection,etc...)
ListTest.php
<?php
session_start();
$_SESSION['DBName'] = "segucom_Responsive";
echo"Request DB Data collection form <br />";
echo "Session(Insert) as Received: ", print_r($_SESSION), "<br/>";
$_SESSION [ 'Process' ] = "";
session_write_close();
echo "Session(Insert) as Set: ", print_r($_SESSION), "<br/>";
?>
<form method="post" name="InsertCheck" action="ListFormTest.php" >
<p><input type="hidden" name="ListRequest" value="1" ></p>
<input type="submit" value="submit" />
</form>
ListFormTest.php
<?php
session_start();
echo"Collect data and sent to DB Insert script <br />";
echo "Session(Insert) as Received: ", print_r($_SESSION), "<br/>";
$_SESSION [ 'Process' ] = "Insert";
session_write_close();
echo "Session(Insert) as Set: ", print_r($_SESSION), "<br/>";
?>
<form action="ListDBTest.php" method="post" name="InsertCheck" >
<p>Input Some data <input type="text" name="Data" ></p>
<input type="submit" value="submit" />
</form>
ListDBTest.php
<?php
session_start();
echo"Receive data and insert in to DB, Chek for Scorrect Session Process value <br />";
echo "Session(Insert) as Received: ", print_r($_SESSION), "<br/>";
if ($_SESSION[ 'Process' ] != "Insert") {
$_SESSION [ 'Process' ] = "Ilegal";
session_write_close();
echo "Session(Insert) as Set: ", print_r($_SESSION), "<br/>";
echo '<script type="text/javascript"> alert ("ILEGAL FORM ACCESS,");
window.location="ListTest.php";</script>';
}
$_SESSION [ 'Process' ] = "Legal";
echo "Session(Insert) as Set", print_r($_SESSION), "<br/>";
include "../../cgh/tcl.txt";
$conn = connect();
$sql = "INSERT INTO Test (`Data`) VALUES ('" . $_POST[ 'Data' ] . "');";
$res = $conn->query($sql) or die("Could not write Record, $sql " . print_r($conn->errorInfo()));
if ($res != FALSE ) {
$_SESSION[ 'Process' ] = "Processed";
/*sleep(10);*/
session_write_close();
echo "Session(Insert) as Set: ", print_r($_SESSION), "<br/>";
echo '<script type="text/javascript"> alert ("Record Inserted");
window.location= "ListTest.php"; </script>';
} else {
$_SESSION [ 'Process' ] = "DB_Error";
/*sleep(10);*/
session_write_close();
echo "Session(Insert) as Set: ", print_r($_SESSION), "<br/>";
echo '<script type="text/javascript"> alert ("Record Not Inserted");
window.location= "ListTest.php";
</script>';
die();
}
?>
What can I do to have those scripts working as intended?
I searched StackOverflow and Googled on the issue with no helpful advise, some leading to the use of timers and delays but refered to AJAX or uploading delays.
I tried to no avail, several aproaches to warrant Session writting and HTML Refresh like:
session_write_close();
sleep(10);
<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
<body onLoad="document.location.reload();">
Thanks in advance
A combination of facts made the code inoperable...
+) I was expecting a ListDBTest.php to be recorded in the browser history, where ListDBTest.php was basically a Server side script, so there were no headers sent to the browser just an alert and as such the browser did not "visit a page"...
+) Navigating back to the page, produced varible results depending on which browser it was run, and it is difficult to have the page relod 100% clean on all browsers.
The correct answer to my problem, was to implement a PGR (Post Get Redirect) Pattern.
https://en.wikipedia.org/wiki/Post/Redirect/Get
That is not so easily understood at first glance, but examples on:
http://solidlystated.com/design/best-way-to-process-forms-with-php/
and http://phptutorial.codepoint.net/php_redirection will get you more than half the way.
Being here, it is important to note that although the PGR pattern, solves most of the dupliction record issues, it is still very good practice to include a "nonce" field with your request as stated in the first article.
In Cases where server responses or internet responses are slow, you might like to have the "submit button" disabled after making the "Post", so the user can not send the form twice in the first instance. Take a look at this one: http://www.the-art-of-web.com/javascript/doublesubmit/

Submit, mysql query + http request to a SMS gateway using JavaScript

I am receiving some data to my confirm.php file. The confirm.php file contains the below code.
I am stuck on the javascript and would really appreciate all input and help.
What I want my javascript to do is: When the user click the submit "Approve & SMS" button, a query is sent to my DB (with customer, tasks and user data) and at the same time a http request is sent to a SMS gateway. After the user has clicked the "Approve & SMS" button, an alert box pops up and when the user click OK in the alert box, I want to redirect the user to my index.php.
Note: I do not need suggestion on the actually mysql query, just on how to make the magic trigger to send a query + the http request with javascript (it do not have to be purely javascript suggestions,, all solutions are welcome as long as they solve my problem).
CONFIRM.PHP
<?php
//check session to get customer
if(!isset($_SESSION['customer'])) {
die('$'."_SESSION['customer'] Session ended");
} else {
$customer = $_SESSION['customer'];
echo $customer;
}
?>
<?php
if(isset($_POST['submit'])) {
// Fetching variables of the form which travels in URL
$tasks = $_POST['tasks'];
$user = $_POST['user'];
?>
SMS API stuff
<?php
//Create $sms_url to send sms to customer
// The necessary variables
$sms_message = ("this is a text");
$sms_url = "http://the.domain/sms/";
$sms_url .= "?message=" . urlencode($sms_message); //messages
$sms_url .= "&recipient=$customer"; // Recipient
$sms_url .= "&from=" . urlencode("name company."); // Sendername
//echo $sms_url;
?>
SOME HTML
<form id="sms_insert_data" action="???" method="POST">
<input class="submit" name="showWordCard" type="submit" value="Approve & SMS"></input>
</form>
JAVASCRIPT
$(document).ready(function(){
$('.submit').click(function(){
var foo = alert('Card created and SMS sent to: <?php echo json_encode($customer); ?>');
window.location = "..//index.php"
});
});
You can use jQuery ajax to send a http request to a php script and/or to your sms gateway.
http://api.jquery.com/jquery.ajax/

Categories

Resources