Display alert when user input is less than specified value. - javascript

i want to display alert box when value inserted by user is less than specified value.and this specified value is taken from database. I am new in php so that i m not getting whats wrong with this code.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gunjanbid", $con);
$username=$_SESSION['userName'];
$id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM bids WHERE id =$id");
//$query=mysql_query("SELECT * FROM bid
$numrow = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
]
$bidfee=$row[5];
}
?>
<?php
echo '<script type="text/javascript">';
echo "function validateForm1()";
{
echo "var c=document.forms['auction1']['fir'].value";
echo "var d=document.forms['auction1']['bidamount'].value";
if echo "( c==null || c=="" )";
{
echo "alert('UserName must be filled out')";
echo "return false";
}
echo "else";
{
echo "if(c<$bidfee)"
{
echo "alert('Bid can not be less than Bid fee')";
echo "return false";
}
}
echo "if (d==null || d=="")";
{
echo "alert('UserName must be filled out')";
echo "return false";
}
echo "else";
{
echo "if(d<$bidfee)";
{
echo "alert('Bid can not be less than Bid fee')";
echo "return false";
}
}
}
echo "</script>";
?>
<form action="multiplebid.php" name="auction1" onsubmit="return validateForm1()" method="post" >
<input type="hidden" name="description" value="" >
<input type="hidden" name="closing_date" value="" >
<input type="text" name="fir" value="" size="5" >
<input type="text" name="sec" value="" size="5" ></td><td> </td><td><input type="submit" name="submit" class="button" value="Bid Now" ></form>
The above code is not displaying alert box and showing error that syntax error, unexpected T_ECHO, expecting '(' in C:\wamp\www\old\detailproduct.php on line 426
or if there be any another way to display alert box then plz help me.

Try below code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gunjanbid", $con);
$username=$_SESSION['userName'];
$id=$_SESSION['id'];
$result = mysql_query("SELECT * FROM bids WHERE id =$id");
$numrow = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$bidfee=$row[5];
}
?>
<script type="text/javascript">
var bidfee = '<?php echo $bidfee;?>';
function validateForm1(){
var c=document.forms['auction1']['fir'].value;
var d=document.forms['auction1']['bidamount'].value;
if ( c==null || c=="" ){
alert('UserName must be filled out');
return false;
}else{
if(c<bidfee){
alert('Bid can not be less than Bid fee');
return false;
}
}
if (d==null || d==""){
alert('UserName must be filled out');
return false;
}else{
if(d<bidfee){
alert('Bid can not be less than Bid fee');
return false;
}
}
}
</script>
<form action="multiplebid.php" name="auction1" onsubmit="return validateForm1()" method="post" >
<input type="hidden" name="description" value="" >
<input type="hidden" name="closing_date" value="" >
<input type="text" name="fir" value="" size="5" >
<input type="text" name="bidamount" value="" size="5" ></td><td> </td><td><input type="submit" name="submit" class="button" value="Bid Now" >
</form>

Related

Form insertion into database not working asynchronously

I'm trying to get a text area's value inserted asynchrnously into my database, however it keeps redirecting to the PHP processing page, and echoing a result there. How would I get it to echo the result of the PHP script on the current HTML page?
JS:
$("#sub").click(function() {
$.post( $("#text").attr("action"), $("#text :input").serializeArray(),
function(info) { $("#result").html(info);});
});
$("#text").submit( function(){
return false;
})
PHP:
$sql = "UPDATE text
SET text_content = ? WHERE (id = 40) AND (number = $Number);";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql))
{
header("Location: ../create_text.php?error&prepare1111");
exit();
}
else
{
$stmt->bind_param("s", $content);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$connection->close();
echo "successfully saved";
}
HTML:
<form type="text" method="post" onSubmit="return validateText(); toHTML();" action="processing.php" id="text">
<textarea name="content" rows="45" id="auto-expand" class="text-box" type="text"><?php echo stripslashes($content) ?></textarea>
<input type="hidden" name="id" id="id" value="<?php echo $id ?>">
<input type="hidden" name="number" id="number" value="<?php echo $number ?>">
<input type="hidden" name="updated" value="<?php echo $updated ?>">
<button type="submit" id="sub" name="submit">Save</button>
<button type="button" onClick="validateText(); toHTML();">Check</button>
<span id="result"></span>
</form>
Any help would be so great! :)
Try preventDefault:
$("#text").submit( function(e){
e.preventDefault();
})

displaying ajax results in textbox

From my code, it displays the hall input type tag inside the textbox.
I want only the value to be displayed.
ajax function:
function load_data(query)
{
$.ajax({
url:"php_action/newfetchorder.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#firstName').val(data);
}
});
}
html:
<input type="text" id="firstName" name="firstName" />
php:
if(isset($_POST["query"])) {
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM product
WHERE Barcode LIKE '%".$search."%'
";
$result1 = mysqli_query($connect, $query);
if(mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_array($result1)) {
$output1 .= '<input type="text" name="item_name" value="'.$row["product_name"].'">';
// $output2 .= '<input type="text" name="item_price" value="'.$row["Retail_price"].'">';
}
echo $output1;
}
else {
echo 'Data Not Found';
}
}
output:
expected output:
write $output1 .=$row["product_name"] instead of $output1 .= '<input type="text" name="item_name" value="'.$row["product_name"].'">';
simple store value to $output1 variable and echo it no need to assign textbox here
change this code line
$output1 .= '<input type="text" name="item_name" value="'.$row["product_name"].'">';
to
$output1 = $row["$product_name"];

PHP - MySQL - Sign Up Trouble [blank data]

I've a website since 2013. I've signed up quite 12k users. From 5 months I have noticed some blank users. They receive a user-code but "name" "surname" and "email" fields are blanks.
This event happen every 50/100 users registrations. Why? I have tried everything, but in all test I can't sign up without data. Also other people that have made tests can't sign up without insert data.
This is the form:
<form action="script/****.php" method="post" onsubmit="return validate()">
<label for="name">Name</label>
<input type="text" id="name" name="name" <?php if($_REQUEST['name'] != "") echo "value='".$_REQUEST['name']."'"; ?> />
<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" <?php if($_REQUEST['surname'] != "") echo "value='".$_REQUEST['surname']."'"; ?> />
<label for="email">Email</label>
<input type="email" id="email" name="email" <?php if($_REQUEST['email'] != "") echo "value='".$_REQUEST['email']."'"; ?> />
<label for="c_email">Retype Email</label>
<input type="email" id="c_email" name="c_email" />
<label for="password">Password</label>
<input type="password" id="password" name="password" />
<label for="c_password">Retype Password</label>
<input type="password" id="c_password" name="c_password" />
<input type="submit" value="registrati" />
</form>
This is the code that stores data on db:
<?php
function mt_rand_str ($length, $available = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789') {
for ($string = '', $i = 0; $i < $length; ++$i) {
$string .= $available[mt_rand(0, strlen($available)-1)];
}
return $string;
}
include('connection.php');
$con = connection();
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$bonus = 10;
$today = new DateTime();
$signUpDate = $today->format('Y-m-d');
if(strpos($name,' ') !== false) {
echo "
<script>
alert('Nome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($surname,' ') !== false) {
echo "
<script>
alert('Cognome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($email,' ') !== false) {
echo "
<script>
alert('Email non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($password,' ') !== false) {
echo "
<script>
alert('Password non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
connectionCheck($con);
userDbCheck($con);
$checkEmail = mysqli_query($con,"Select * from Users_DB where email = '$email'");
if(!mysqli_fetch_assoc($checkEmail)) {
do {
$userCode = mt_rand_str(8);
}
while(mysqli_fetch_assoc(mysqli_query($con,"select * from Users_DB where binary UserCode = '$userCode'")));
$value = 20;
mysqli_query($con,"Insert into User_DB (UserCode,Name,Surname,Phone,Email,Password,SignUpDate,bonus)
values ('$userCode','$name','$surname','','$email','$password','$signUpDate','$bonus')");
}
else {
echo "
<script>
alert('Email exists already!');
window.location.href = '../signup.php';
</script>";
}
?>
I hope you can find what I have not. As you can see, I've put in php code some data check too.
So I have
1) HTML5 check: type="email". I'm thinking to put also "pattern match" in all fields
2) JavaScript check
3) PHP check
I'm so desperate...
Thank you before.

Ajax jQuery retrieving data from previous query

I'm currently using Ajax & jQuery for my chat, some might say its stupidly complex but so long as I can get it working.
It works on the first friend result, how ever not on the other. What its doing is the chat-load.php (Ajax part) is creating a new query to select the friends details, which are then being put into a result query on the chat.php page.
Therefore it only displays one "Working" chat window for the 1st friend. I tried grabbing the previous friend_id from the chat.php query and using it in the chat-load.php query but it didn't seem to notice any data.
Here is an example of what I'm getting, 1st result full width meaning its working, other results not full width as not working with ajax.
This is my current setup:
chat.php
<?php $users = $db->query("SELECT DISTINCT users.id, users.firstname, users.lastname,
message.date, message.time, message.message, message.recipient, message.sender
FROM users
JOIN friends
ON users.id IN (friends.sender, friends.recipient)
JOIN message
ON (users.id = message.sender)
AND 75 IN (message.sender,message.recipient)
ORDER BY message.date DESC, message.time DESC"); ?>
<!-- Friends query -->
<?php $users = $db->query("SELECT IF(friends.sender = ".$_SESSION["user"]["id"].", friends.recipient, friends.sender) AS user_id
FROM friends
WHERE friends.sender = ".$_SESSION["user"]["id"]."
OR friends.recipient = ".$_SESSION["user"]["id"].""); ?>
<?php while($friend = $users->fetch_object()): ?>
<?php $friends = $db->query("SELECT firstname, lastname, id FROM users WHERE id = $friend->user_id "); ?>
<?php while($FriendName = $friends->fetch_object()): ?>
<div class="chat-box">
<div class="header">
<?= $FriendName->firstname ?> <?= $FriendName->lastname ?> <?= $FriendName->id ?>
</div>
<script>
$(window).load(function() {
$("#chat-box, #messages").animate({ scrollTop: $(document).height() }, 1000);
});
</script>
<script>
function loadlink(){
$('#messages').load('chat-load.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 100);
</script>
<div id="messages" class="messages">
</div>
<div class="input-box">
<form id="SendForm" class="SendMsg" role="form" method="post">
<input type="text" id="s_firstname" name="s_firstname" class="MsgInputHidden" value="<?= $_SESSION["user"]["firstname"] ?>" />
<input type="text" id="s_lastname" name="s_lastname" class="MsgInputHidden" value="<?= $_SESSION["user"]["lastname"] ?>" />
<input type="text" id="sender" name="sender" class="MsgInputHidden" value="<?= $_SESSION["user"]["id"] ?>" />
<input type="text" id="r_firstname" name="r_firstname" class="MsgInputHidden"value="<?= $FriendName->firstname ?>" />
<input type="text" id="r_lastname" name="r_lastname" class="MsgInputHidden"value="<?= $FriendName->lastname ?>" />
<input type="text" id="recipient" name="recipient" class="MsgInputHidden" value="<?= $FriendName->id ?>" />
<input type="text" id="ip" name="ip" class="MsgInputHidden" value="<?= $_SERVER["REMOTE_ADDR"] ?>" />
<input type="text" id="date" name="date" class="MsgInputHidden" value="<?= date('Y-m-d') ."\n" ?>" />
<?php
$now = time();
$utc_time = $now - intval(date('Z', $now));
?>
<input type="text" id="time" name="time" class="MsgInputHidden" value="<?= '' . date('H:i:s', $now) . '' ?>" />
<input id="message" type="text" name="message" style="width: 100%; overflow: scroll;">
<input id="submit" class="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
<script>
$("#submit").click(function(e) {
e.preventDefault();
var message = $("#message").val();
var s_firstname = $("#s_firstname").val();
var s_lastname = $("#s_lastname").val();
var sender = $("#sender").val();
var r_firstname = $("#r_firstname").val();
var r_lastname = $("#r_lastname").val();
var recipient = $("#recipient").val();
var ip = $("#ip").val();
var date = $("#date").val();
var time = $("#time").val();
var dataString = '&message=' + message + '&s_firstname=' + s_firstname + '&s_lastname=' + s_lastname + '&sender=' + sender + '&r_firstname=' + r_firstname + '&r_lastname=' + r_lastname + '&recipient=' + recipient + '&ip=' + ip + '&date=' + date + '&time=' + time;
$.ajax({
type:'POST',
data:dataString,
url:'sendmessagefriend.php',
});
});
</script>
<script>
$("#submit").click(function(e) {
$("#SendForm").get(0).reset();
});
</script>
<script>
$("#submit").click(function(e) {
$("#chat-box, #messages").animate({ scrollTop: $(document).height() }, 1000);
});
</script>
<?php endwhile; ?>
<?php endwhile; ?>
chat-load.php
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
if(!isset($_SESSION["user"]) or !is_array($_SESSION["user"]) or empty($_SESSION["user"])
)
// redirect to index page if not superuser
header('Location: index.php');
?>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','****','****','****');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT message, sender, recipient, date, time, IF(recipient = ".$_SESSION["user"]["id"].", 'received', 'sent') AS direction FROM message WHERE recipient IN (".$_SESSION["user"]["id"].", ".$friend->user_id.") AND sender IN (".$_SESSION["user"]["id"].", ".$friend->user_id.")";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<ul>";
echo "<li>";
echo "<span class='". $row['direction'] ."'>". $row['message'] ."</span>";
echo "<div class='clear'></div>";
echo "</li>";
echo "</ul>";
}
mysqli_close($con); ?>
</body>
</html>
Try using $.ajax() instead of $.load(). Set cache: false.
Example:
function loadlink(){
$.ajax({
url:'chat-load.php',
cache: false,
success: function(result){
$('#messages').html(result);
}
});
}

Redirect back to a page with field values submitted earlier

I have this sign-in page...
<!doctype html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<form action="signin_process.php" method="post">
Name: <input type="text" name="name">
<br />
SID: <input type="text" name="sid">
<br />
Nick Name: <input type="text" name="nn">
<br />
Email: <input type="text" name="email">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
The signin_process.php file...
<!doctype html>
<html>
<head>
<title>Signin_process</title>
</head>
<body>
<?php
include ("connection.php");
$name = $_POST['name'];
$sid = $_POST['sid'];
$nn = $_POST['nn'];
$em = $_POST['email'];
$pw = $_POST['pw'];
$result = mysqli_query($con, "SELECT * FROM student_table WHERE SID='$sid'") or die('Query failed');
if(mysqli_num_rows($result)){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Invalied SID')
window.location.href='welcome.php';
</SCRIPT>");
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE nickname='$nn'") or die('Query failed');
if(mysqli_num_rows($result)){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Nickname Takken!')
window.location.href='welcome.php';
</SCRIPT>");
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE email='$em'") or die('Query failed');
if(mysqli_num_rows($result)){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Email already in use!')
window.location.href='welcome.php';
</SCRIPT>");
}
?>
</body>
</html>
Now if SID, Nick name or email is not valid, i want to redirect to the sign-in page and the field values will be there which were given earlier. So that in don't have to input all the values all over again. Like we see in many sites, we just had to change the input that was not excepted and submit again.
Thanks!
You can use like this:
if ($_POST['name'] == '') {
echo "<script type='text/javascript'>window.history.back();</script>";
}
By this way field values will be there which were given earlier.
<?php
session_start();
if(isset($_POST['nam']) && (isset($_POST['sid']) && (isset($_POST['nn'])){
if(($_POST['name']=== 'user')&& ($_POST['sid']==='sid')&&($_POST['nn']==='sid')){
echo "correct";
$_SESSION['us'] = "YES";
$_SESSION['sid'] = "YES";
$_SESSION['nn'] = "YES";
header("location: userpage.php"); //directs to user area
}else {
echo "Wronge Password/Name/Nickname";
$_SESSION['us'] = $_POST['name'];
$_SESSION['sid'] = $_POST['sid'];
$_SESSION['nn'] = $_POST['nn'];
header("location: userpage.php"); //userpage redirects to this page
}}
?>
<!doctype html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<form action="" method="post">
Name: <input type="text" name="name" <?php echo isset($_SESSION['us']) ? $_SESSION['us'] : ""; ?> >
<br />
SID: <input type="text" name="sid" <?php echo isset($_SESSION['sid']) ? $_SESSION['sid'] : ""; ?> >
<br />
Nick Name: <input type="text" name="nn" <?php echo isset($_SESSION['sid']) ? $_SESSION['sid'] : ""; ?> >
</form>
</body>
</html>
A basic example:
Your login form:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<ul>
<?php
$errors = isset($_SESSION['errors']) && is_array($_SESSION['errors']) ? $_SESSION['errors'] : [];
foreach ($errors as $error):
?>
<li><?php print $error; ?></li>
<?php endforeach; ?>
</ul>
<form action="signin_process.php" method="post">
<label for="name">Name: </label>
<input type="text" id="name" name="name" value="<?php print !isset($_SESSION['name']) ?: $_SESSION['name']; ?>" />
<label for="sid">SID: </label>
<input type="text" id="sid" name="sid" value="<?php print !isset($_SESSION['sid']) ?: $_SESSION['sid']; ?>" />
<label for="nn">Nick Name: </label>
<input type="text" id="nn" name="nn" value="<?php print !isset($_SESSION['nn']) ?: $_SESSION['nn']; ?>" />
<label for="email">Email: </label>
<input type="text" id="email" name="email" value="<?php print !isset($_SESSION['email']) ?: $_SESSION['email']; ?>" />
<label for="pw">Password: </label>
<input type="text" id="pw" name="pw" value="<?php print !isset($_SESSION['pw']) ?: $_SESSION['pw']; ?>" />
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
Your PHP form submission:
<?php
session_start();
include ("connection.php");
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_SESSION['name'] = mysqli_real_escape_string($con, $_POST['name']);
$sid = $_SESSION['sid'] = mysqli_real_escape_string($con, $_POST['sid']);
$nn = $_SESSION['nn'] = mysqli_real_escape_string($con, $_POST['nn']);
$em = $_SESSION['email'] = mysqli_real_escape_string($con, $_POST['email']);
$pw = $_SESSION['pw'] = mysqli_real_escape_string($con, $_POST['pw']);
$_SESSION['errors'] = [];
$result = mysqli_query($con, "SELECT * FROM student_table WHERE SID='$sid'") or die('Query failed');
if (mysqli_num_rows($result) > 0) {
$_SESSION['errors'][] = 'Invalid SID.';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit();
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE nickname='$nn'") or die('Query failed');
if (mysqli_num_rows($result) > 0) {
$_SESSION['errors'][] = 'Nickname already in use.';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit();
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE email='$em'") or die('Query failed');
if (mysqli_num_rows($result) > 0) {
$_SESSION['errors'][] = 'E-mail already in use.';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit();
}
}
header('Location: index.php');
exit();
?>
That should work.
P.S. You should look into prepared statements and input filtering. Safety should always come first.

Categories

Resources