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>
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'm trying to use a get statement in a variable to add data to a data base, when i try to do this nothing is added under folder however if i add plain text it is added. (i'm trying to add to the folder section)
My entire html document is provided below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="newfile.css">
<title>Folder</title>
</head>
<body>
<?php
include_once 'dbh.php';
echo $_GET["data"];
if(isset($_GET["data"])) {
$location = $_GET["data"];
$sql = "SELECT * FROM posts WHERE folder LIKE '%$location%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result))
{
echo $row['content'];
}
} else {
echo "There are no results matching your search!";
}
}
?>
<?php
$uploadpath = 'postimages/'; // directory to store the uploaded files
$max_size = 3116718; // maximum file size, in KiloBytes
$alwidth = 100000; // maximum allowed width, in pixeli
$alheight = 100000; // maximum allowed height, in pixeli
$allowtype = array('bmp', 'gif', 'jpeg', 'jpg', 'jpe', 'png', 'docx', 'psd', 'pdf', 'pptx', 'html', 'php', 'css', 'js', 'mp4', 'mp3'); // allowed extensions
if(isset($_FILES['fileup'])) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$name = basename( $_FILES['fileup']['name']);
$type = end(explode('.', strtolower($_FILES['fileup']['name'])));
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = '';
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*900000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x
'. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_GET['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
if($result !== false) {
header("Location: fold.php?data=Math");
}else{
echo "fail";
}
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div class="upform">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="image-upload">
<label for="file-input">
<img src="add-file.png" />
</label>
<input id="file-input" type="file" name="fileup"/>
</div>
<input class="noshow" type="text" id="wow" placeholder="<?php echo $_GET['data']; ?>" name='name'>
<input type="submit" id="submit" name='submit' value="U P L O A D" />
</form>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$("#submit").show();
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
)
});
</script>
</body>
</html>
url= http://localhost/smart%20assist/fold.php?data=Math
Any help would be awesome, Thanks
So, if you doing file uploading you are using post method in your form with multi-part, right.
now, if you want to send something with your url as query params, then you have to use $_REQUEST. In your case,
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_REQUEST['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
If you facing the same problem, I need to check your HTML form, to help you in a better way.
I think you made below mistakes.
You are not posting "data" field value in your HTML.
You must put the name field for get data.
You are posting the form for using post method. So you should be used $_POST[] or $_REQUEST[].
please verify your HTML.
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 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']))`
I'd appreciate some help in getting a simple demo working of the Twitter typeahead.js library as I've struggled with it over the last two days.
I'm using a MAMP development server on my Macbook, and have a (large) MySQL database table that I'd like to query to use with a typeahead field on a Web page.
This is my main HTML file that I'm using. It literally has one field in it.
type-ahead.php
<?php
// HTML5 Header stuff
echo '<!DOCTYPE html>'.PHP_EOL;
echo '<html>'.PHP_EOL;
echo '<head><meta charset="UTF-8">'.PHP_EOL;
echo '<title>Typeahead Example</title>'.PHP_EOL;
// include the two libraries for typeahead to work
echo '<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '</head>'.PHP_EOL;
echo '<body>'.PHP_EOL;
echo '<h2 class="myclass">Typeahead testing</h2>'.PHP_EOL;
echo 'Type in a search: <input type="text" name="user_search">'.PHP_EOL;
echo "<script type='text/javascript'>".PHP_EOL;
echo "$('#user_search').typeahead({".PHP_EOL;
echo " name: 'user_search',".PHP_EOL;
echo " remote: './type-ahead-ajax.php?query=%QUERY',".PHP_EOL;
//echo " minLength: 3,".PHP_EOL;
//echo " limit: 10".PHP_EOL;
echo "});".PHP_EOL;
echo "</script>".PHP_EOL;
echo '</body></html>'.PHP_EOL;
?>
The source of this from the browser looks OK, but I'll paste it here too just in case.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<title>Typeahead Example</title>
<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>
</head>
<body>
Type in a search: <input type="text" name="user_search">
<script type='text/javascript'>
$('#user_search').typeahead({
name: 'user_search',
remote: './type-ahead-ajax.php?query=%QUERY',
});
</script>
</body></html>
I've tested my call back script separately, and it is definitely connecting to the database and pulling back some results. For example if I use '/type-ahead-ajax.php?query=bleach' as a URL, I get all the products containing the word 'bleach'
type-ahead-ajax.php
<?php
// Connect to the database
try {
$dbh = new PDO('mysql:host=localhost; dbname=menu;', 'root', 'root');
$query = '%'.$_GET['query'].'%'; // add % for LIKE query later
//$query = '%milk%'; //debug
echo $query.PHP_EOL;
// do query
$stmt = $dbh->prepare('SELECT title FROM waitrose WHERE title LIKE :query');
$stmt->bindParam(':query', $query, PDO::PARAM_STR);
$stmt->execute();
// populate results
$results = array();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
$results[] = $row;
echo strtolower($row).PHP_EOL; //debug
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// and return to typeahead
return json_encode($results);
?>
Basically, when you type into the input field nothing happens. It's as though either the callback isn't being called, it's returning nothing, or it's not registered properly in the first place.
Any suggestions?
When you do $('#user_search'), you're referring to an element with id user_search. You haven't, however, given your input any id. Add it:
<input type="text" name="user_search" id="user_search">
If that doesn't work, make sure you get the data you assume by accesssing ./type-ahead-ajax.php?query=%QUERY manually with some query, and check for JavaScript errors in your browser console.