Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
<html><head>
<script>
function submit() {
document.getElementById("myform").submit();
}
</script>
</head>
<body>
<form id="myform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1> AWB_NO</h1>
<input type=text name="excel" onchange="submit()" >
</br>
</form>
<?php
session_start();
$vars = $_COOKIE['var1'];
//$vars=$_GET['doc'];
if(!isset($_SESSION['items'])) {
$_SESSION['items'] = array();
}
$var='';
if(isset($_POST['submit']))
{
$host="localhost";
$user="root";
$password="";
$db="greenmobiles";
$table="manifest";
$var=$_POST['excel'];
//$vars=$_POST['doc'];
mysql_connect("$host","$user","$password") or die("Cannot Connect");
mysql_select_db("$db") or die("Cannot select DB!");
/*$sqlcommand="SELECT document_no FROM manifest WHERE (document_no = '$vars')";
$doc_res = mysql_query($sqlcommand);
while($col = mysql_fetch_array($doc_res)){
if($col['document_no']==$vars)
{
echo "Document number is correct</br>";
break;
}}
if($col['document_no']!==$vars)
{
echo "Please check the document no entered";
exit(0);
}*/
if (in_array($var,$_SESSION['items']))
{
echo "<script>alert('oops! This item has already been scanned!')</script>";
}
else
{
$sql = "SELECT * FROM manifest WHERE (awb_no = '$var')";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
echo "tracking id present in the manifest</br>";
}
else {
echo "<script>alert('Tracking id is not present in the manifest!')</script>";
}
$sqli = "SELECT * FROM manifest WHERE (awb_no = '$var') AND (document_no='$vars')";
$result1 = mysql_query($sqli);
if (mysql_num_rows($result1))
{
echo "The tracking id matches with the document no.";
# code...
}
else
{
echo "<script>alert('Tracking id does not belong to the document number entered.')</script>";
exit(0);
}
while ($row = mysql_fetch_array($result)) {
$_SESSION['data'][] = $row['awb_no'];
$_SESSION['items'] = $_SESSION['data'];
}
echo"The new value has been scanned!</br>";
echo "<hr>";
echo "The tracking id's of the currently scanned items are given below<br><hr>";
foreach ($_SESSION['items'] as $x => $value)
{
echo "$value";
echo "<br>";
# code...
}
}
}
else
{
session_destroy();
}
?>
</body>
</html>
Hey! I am new to javascript,php and html. Here when i am trying to use the javascript submit instead of the submit button,my php script does not seem to execute.How to go about this problem?Please do help! P.S I do not want to use the submit button.
You have many errors on your script.
Active your php errors displays :
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
First, the session must be started BEFORE to send headers.
So begin the file with :
<?php
session_start();
?>
<html>
...
Second, the global $_POST contains an array with 'name' attributes
<input type=text name="excel" onchange="submit()" >
<?php
if(isset($_POST['excel'])) { ... }
if(isset($_POST['submit'])) is wrong type `if(isset($_POST['name']))`
Related
I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've looked through the existing questions and i don't believe they are answering my question.
I have created a table that gets populated using PHP and MySQL. I have got my add function working so the user can ADD a new row, however I would like the user to remove specific rows. Each row has a remove icon that I would like when clicked to remove ONLY that row.
Home.php (where table is created)
<table class="table table-bordered table-striped table-responsive">
<tr class="header">
<td>id</td>
<td>Rep</td>
<td>Date</td>
<td>Name</td>
<td>P_O</td>
<td>Due Date</td>
<td>Terms</td>
<td>Aging</td>
<td>Open Balance</td>
<td>remove</td>
</tr>
<?php
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button></td>";
}
?>
</table>
This is the remove button:
<button type='button' class='btn btn-link'><i class='iconhover fa fa-check-circle fa-2x'></i></button>
I would like it to remove the row that its currently part of when clicked. Any help?
Here is my new code, however it still doesn't seem to be deleting the row
home.php:
while($row = mysql_fetch_array($query))
{
$className ="";
if ($row['Aging'] >= 45) {
$className="danger";
}
else if($row['Aging'] >= 25 && $row['Aging'] <= 44) {
$className="warning";
}
echo "<tr class='$className'>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['Rep']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['P_O']."</td>";
echo "<td>".$row['Due_Date']."</td>";
echo "<td>".$row['Terms']."</td>";
echo "<td>".$row['Aging']."</td>";
echo "<td>".$row['Open_Balance']."</td>";
echo "<td><button action='deletepage.php' method='POST' value='" .$row['id']. "' class='btn btn-danger'> Delete</button></td>";
}
deletepage.php:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_GET['id'])){
$userID = (int) $_GET['id'];
if(!empty($_GET['id'])) {
$delete = mysql_query("DELETE FROM Book1 WHERE id='$userID'");
}
if($delete) {
echo "Record deleted successfully";
}
else {
echo "Sorry, record could not be deleted";
}
}
You can do by directing it to the delete page like this:
Delete
Or with javascript AJAX call:
Delete
and use $.post to the deletion page
UPDATE:
the deletion page deletepage.php may contain the following:
<?php
require('dbconn.php');
if(isset($_POST['id'])){
$userID = (int) $_POST['id'];
if(!empty($_POST['id'])){
$delete = mysql_query("DELETE FROM users WHERE id='$userID'");
}
if($delete){
echo "Record deleted successfully";
}else{
echo "Sorry, record could not be deleted";
}
}
?>
users.php
<?php
require('dbconn.php');
$get = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($get)) {
echo '<p>';
echo $row['id'] . ' - ' . $row['user'];
?>
Delete
</p>
<?php } ?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function confirmDeletion(id){
$.post('deletepage.php', { id:id }, function(data){
alert(data);
location.reload();
});
}
</script>
P.S:
It's very recommended to quit using mysql_query() in this way and instead use PDO to avoid SQL injection
I would change the button to include the value of the row id, by adding a value attribute to the button html:
value='" .$row['id']. "'
You can then capture the click event using jquery / javascript, and use an ajax call to remove the record from your database. It would look something like:
$('.btn-lnk').on('click',function() {
var id = $(this).val();
$.ajax({
type: "POST",
url: "yourPageThatDeletesRow.php",
data: { id: id },
success: function(response) {
if(response === 'success') {
//delete row showing on the page
$(this).closest('tr').remove();
} else {
//handle error
}
} //consider handling ajax error case
});
});
The ajax call will execute the code on yourPageThatDeletesRow.php. You can get the row id using $_POST['id'] and delete the data using that id. If the delete is successful, echo the string 'success'. Consider returning the error from the database if it's not successful, and handling that case in the return of the ajax
Here is a simplified JS Fiddle showing how the passing of the id and row deletion work.
You will need a delete button if your going to do it the way ive done it.
if (isset($_POST['delete'])){
$userid = $_POST['userid'];
$sql = "DELETE FROM users WHERE userid = '$userid';";
if ($conn->query($sql) === true){
//echo 'Click here to view modified patients';
}
}
Use this code:
<?php $temp_pre_ID = $row['id'];?>
<INPUT TYPE="button" onClick="window.location='home.php?Action=del&CusID=<?php echo $temp_pre_ID;?>'" value="Delete">
I want to show JavaScript alert after successful data insertion in MySQL. How to do this? I have written this code but it shows JavaScript alert everytime I open this page and as soon as i click on OK of JavaScript alert it redirects me to finalmem.php, without the action of taking values from users!
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
Thanks in advance.
Use is set isset($_POST['submit']) to check whether user submits the form or not
<?php
include 'SQLIDB.php';
if(isset($_POST['submit'])){
$name=$_POST['name'];
$email=$_POST['email'];
$ybr=$_POST['ybr'];
$ach=$_POST['ach'];
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>
<form action="" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="ybr">
<input type="text" name="ach">
<input type="submit" name="submit" value="Submit">
</form>
You need to know two things, one of them it's to confirm if your data it's saved succefully.
For this you can play with
mysql_affected_rows()
and this function will return the number of rows affected by your query. If zero, it was not inserted. If >= 1, it was.
So:
if ( mysql_affected_rows() >= 1 ){ /* inserted! now do something... */ }
If you are using an auto-incrementing column for row ID, you can use mysql_insert_id() as well:
if ( mysql_insert_id() > 0 ) { /* inserted! now do something... */ }
Then you can work with jQuery UI for show a dialog like this:
[https://jqueryui.com/dialog/][1]
You need tot load the .css and .js files to run jQuery and inside your code put this:
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
And this in your view:
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
Normally this it's super ugly to do for me, because the best way it's doing this by AJAX.
You can try like this
<?php session_start();
//Include database detail here
if(isset($_POST['name'])){
$name = mysqli_real_escape_string($_POST["name"]);
$ybr = mysqli_real_escape_string($_POST["ybr"]);
email = mysqli_real_escape_string($_POST["email"]);
$ach = mysqli_real_escape_string($_POST["ach"]);
//Do your data validation here
$_SESSION['sname'] = $name;
$_SESSION['sybr'] = $ybr;
$_SESSION['semail'] = email;
$_SESSION['sach']= $ach;
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>
My test.php page is as under:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h3>Setting</h3>
<form>
<p>Name:<input type="text" id="updatetherone1"/></p>
<p>Email:<input type="text" id="updateotherone2"/></p>
<p><input id="updateone" type="button" value="Save"/></p>
</form>
<span id="updateotherotherone"></span>
<script src="js/jquery.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
My ini.php page is as under:
<?php
session_start();
$_SESSION['state'] ='2';
$conn=new mysqli('localhost','root','','people');
?>
My test1.php page is as under:
<?php
include 'ini.php';
if (isset($_POST['name'], $POST['email'])){
$name = mysqli_real_escape_string(htmlentities($POST['name']));
$email = mysqli_real_escape_string(htmlentities($POST['email']));
$update = mysqli_query("UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
if($update === true){
echo 'Setting have been updated.';
}else if ($update === false){
echo 'There was an error updating your setting.';
}
}
?>
My ajax.js page is as under:
$('[id=updateone]').click(function(){
var name=$('[id=updateotherone1]').val();
var email=$('[id=updateotherone2]').val();
$('[id=updateotherotherone]').text('Loading...');
$.post('test1.php',{name:name,email:email},function(data){
$('[id=updateotherotherone]').text(data);
});
});
Ultimately code is not working nor do it is displaying any error, I suspect there is something wrong with test1.php page, can anybody guide please:
Take note that the procedural interface of mysqli_query(), the first parameter need the connection.
$update = mysqli_query($conn, "UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
If these are typos $POST, then it should be fixed in your code. It's supposed to read as $_POST. (unless its a typo on the question.) It is a superglobal.
I suggest you just use the object oriented interface. So that you wouldn't need to add it everytime:
<?php
include 'ini.php';
if (isset($_POST['name'], $_POST['email'])){
$name = $conn->real_escape_string(htmlentities($_POST['name']));
$email = $conn->real_escape_string(htmlentities($_POST['email']));
$update = $conn->query("UPDATE state SET Name='$name', email='$email' WHERE Id = " . $_SESSION['state']);
if($conn->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
?>
Might as well use prepared statements since mysqli supports it:
if (isset($_POST['name'], $_POST['email'])){
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$sql = 'UPDATE state SET Name = ?, email = ? WHERE Id = ?';
$update = $conn->prepare($sql);
$update->bind_param('ssi', $name, $email, $_SESSION['state']);
$update->execute();
if($update->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
On the JS part:
You also have a typo on the form id and the JS:
<p>Name:<input type="text" id="updatetherone1"/></p> <!-- missing o -->
var name=$('[id=updateotherone1]').val();
Should be: <p>Name:<input type="text" id="updatetherone1"/></p>
Sidenote:
If you want to avoid those kind of silly typos, just id and label them properly. Example:
<p>Name:<input type="text" id="name_field"/></p>
<p>Email:<input type="text" id="email_field"/></p>