Get two terms (values) from a form in AJAX - javascript

I want to run an AJAX script witch queries my database based on two parameters.
That is the form I've got
<form id="search-box" action="search.php" method="post">
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" id="username" name="username" size="31" placeholder="username ..." />
/
<input type="text" id="surname" name="surname" size="31" placeholder="surname..." />
<input type="submit" id="submit-button" name="sa" value="search" />
</form>
That is the java script for the AJAX:
<script type="text/javascript">
$(function() {
$("#surname").autocomplete({
source: "ajax-user.php",
minLength: 2,
});
});
</script>
And that is the php for the which does the query
<?php
require_once('connection.php');
try {
$conn = new readPDO("test");
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$ac_term2 = "%".$_GET['term2']."%";
$query = "
SELECT
surname
FROM
worker
WHERE
lower(username)
LIKE lower(:term)
AND
lower(surname)
LIKE lower(:term2)
";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->bindValue(":term2",$ac_term2);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['value'] = $row['repoName'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what I was not able to do is to get $ac_term2 value passed. Any suggestions?

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();
})

How to add onkeypress save in php form

**This is my php index.php file. I want to type first name and last name type and auto it has to be save the database. I wrote the code using ajax. but, this is not working properly. Please can any one help me. **
index.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script type="text/javascript">
$(document).on('keyup','firstName','lastName',function(){
var rel = $(this).attr('rel');
var flatvalue = $(this).val();
$("#firstName"+rel).val(flatvalue);
});
</script>
</head>
<body>
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
</body>
</html>
onKeyPress event not proper because it call many times as per user hit.
Use onBlur event instead of onKeyPress for submit the form and save it to MySql users table.
Try below example,
PHP
<?php
$connection = mysql_connect("localhost", "jaydeep_mor", "jaydeep_mor");
$db = mysql_select_db("jaydeep_mor", $connection);
if(isset($_POST['firstName']) && isset($_POST['lastName'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
if($firstName != '' || $lastName != ''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
header("Location: test.php?msg=Data Inserted successfully...!!");
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection);
?>
HTML / JAVASCRIPT
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta><title>Home Page</title>
<script type="text/javascript">
function saveData(){
document.forms["userDataForm"].submit();
}
</script>
</head>
<body>
<?php if(isset($_GET['msg']) && trim($_GET['msg'])!=""){ ?>
<br /><div><?php echo $_GET['msg']; ?></div><br />
<?php } ?>
<form action="test.php" method="post" name="userDataForm">
<label for="firstName">First Name</label>
<input type="text" name="firstName" value="<?php echo isset($_POST['firstName'])?$_POST['firstName']:''; ?>" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" value="<?php echo isset($_POST['lastName'])?$_POST['lastName']:''; ?>" onblur="return saveData();" ><br><br>
<!--input type="submit" id="Submit" name="Submit" value="submit"/-->
</form>
</body>
</html>
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("type", $connection);
if(isset($_REQUEST['firstName'])){
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
if($firstName !=''||$lastName !=''){
//Insert Query of SQL
$query = mysql_query("insert into users(firstName, lastName) values ('$firstName', '$lastName')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
die();
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
die();
}
}
//mysql_close($connection);
?>
<html>
<head>
<meta><title>Home Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){ alert('d');
var firstname = $('#firstName').val();
var lastname = $('#lastName').val();
$.ajax({
url:'',
data:{'firstname':firstname,'lastname':lastname, },
type: 'POST',
success: function(data){
alert("Data Save: " + data);
}
});
});
});
</script>
</head>
<body>
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName"><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName"><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</body>
</html>
may be this can help you,
if you want to do it via form submit then just you need to give the url of your controller function in the action method of the form
<form action="" method="post">
<label for="firstName">First Name</label>
<input type="text" name="firstName" ><br><br>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" ><br><br>
<input type="submit" id="submit" name="submit" value="submit"/>
</form>
if you want to do it via ajax then you can add id attribute for first_name and last_name input and can do it in following way,
$('#submit').on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$.ajax({
url: url of your controler, //url of your controller function
type: "POST",
data: {'first_name' : first_name,'last_name':last_name},
success: function (data) {
//whatever you want to do on success
} else {
//in case of no data
}
}
});
});
in the same way you can give a class attribute to the input box and on keyup event can save the data via class
have you try doing it this way
$('body').delegate('input[type="text"]', 'keypress keydown keyup change propertychange paste', function(event) {
event.stopImmediatePropagation();
if (event.type === 'keydown' || event.type === 'keypress') {
return;
}
//insert what you want to do here
//perform some ajax
/*
$.ajax({
url: 'index.php',
method: 'POST',
data: {
'firstName' : $('input[name=firstName]).val(),
'lastName' : $('input[name=lastName]).val()
},
success: function(mResponse) {
alert(mResponse);
}
});
*/
});

Display custom error message in login

I want to implement a simple login with PHP. But, also I want to customize the error message when the login is incorrect, for example display a error message in red color.
Login.php
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result = mysql_query($sql, $con);
if ($fila = mysql_fetch_array($result)) {
header('Location: menuclient.php');
} else {
/* How customize my message error */
}
?>
In the Login.php file, when the username or password are not correct, i want to display, for example, in id=error : "Login Incorrect" in red.
I dont know if I can do it with php.
Thanks for your help.
You can use session. Try following way.
Login.php
<?php
session_start();
if($_SESSON['error']): ?>
<span>Error : <?php echo $_SESSION['errorMsg']; ?></span>
<?php endif; ?>
<form id="frmlogin" name="frmlogin" method="POST" action="validarUsuario.php">
<p><input type="text" name="usuario" id="usuario" class="required" maxlength="50" placeholder="Nombre Usuario"></p>
<p><input type="password" name="password" id="password" class="required" maxlength="50" placeholder="Password"></p>
<p id=error> </p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
validarUsuario.php
<?php
session_start();
include("connection.php");
conectar_bd();
$usr = $_POST['usuario'];
$pw = md5($_POST['password']);
$sql = "SELECT usr FROM Client WHERE usr = '$usr'AND password ='$pw'";
$result=mysql_query($sql,$con);
if( $fila=mysql_fetch_array($result) )
{
header('Location: menuclient.php');
}
else {
$_SESSION['errorMsg'] = "Wrong username or Password";
$_SESSION['error'] = true;
header('Location: Login.php');
}
?>

SESSION variable slow to update textfield in php

I have a form, contained 3 fields, which when the submit button in submitted,
it will changes the session variable values according to the fields, in this case there are 3 variables. then i echo back the variable onto the fields.
For the first time submit, it stores the value beautifully and display in the fields correctly, the problem is that, when i submit the second time, the values are still the same. after i refresh the page, then the values in the fields are changed.
this is partially the codes i'm using now.
<?php
session_start();?>
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
}
?>
After i refresh(F5), then the value changed. i want it to be, when i clicked the submit button, it will change to the new value.
PHP Code:
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
echo '<script type="text/javascript">'
, 'jsfunctionToPrintUpdatedValues();'
, '</script>'
;
}
?>
Javascript Sample Code
function jsfunctionToPrintUpdatedValues()
{
/* retrieve the updated session variables in javascript variables */
var acc_main_js = <?php echo $_SESSION['acc_main']?>
var acc_id_js = <?php echo $_SESSION['acc_id']?>
var acc_cat_js = <?php echo $_SESSION['acc_cat']?>
document.getElementById("main").value=acc_main_js;
document.getElementById("id").value=acc_main_js;
document.getElementById("cat").value=acc_main_js;
}
in the input fields you have to write like this
`
Below
`
<input type="text" name="acc1" value="<?php if(isset($_SESSION['acc_main'])) echo $_SESSION['acc_main']" />
Use if(isset($_POST['submit']) != '') before the form. Change your code to this:
<?php
session_start();
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
}else{
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
<?php } ?>

ajax comment form not posting data to mysql

I am using ajax to post a comment to a mysql table. When I post the comment, the javascript is loading but it doesnt submit the data to the mysql database.
$(document).ready(function(){
$('#commentform').on('submit',function(e) {
$.ajax({
url:'ajax.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
ajax.php
$id = $_POST['id'];
$comment = $_POST['comment'];
$username = $_POST['username'];
$array = $pdo->prepare("INSERT INTO `comments` (id, comment, user)
VALUES (:id,:comment,:username);");
$array->execute(array(':id' => $id, ':comment' => $comment, ':username' => $username));
html
<form method="post" name="commentform" id="commentform">
<textarea name="comment" name="comment"></textarea><br>
<input type="hidden" value="<?php echo "$id"; ?>" name="id" id="id" />
<input type="hidden" value="<?php echo "$username"; ?>" name="username" id="username" />
<input type="submit" name="submit" id="submit" value="REPLY" />
</form>
You have issue in html form, you have used multiple " around php variables which causes to break the value attribute, use updated html
HTML
<form method="post" name="commentform" id="commentform">
<textarea name="comment" name="comment">test comment</textarea><br>
<input type="hidden" value="<?php echo $id; ?>" name="id" id="id" />
<input type="hidden" value="<?php echo $username; ?>" name="username" id="username" />
<input type="submit" name="submit" id="submit" value="REPLY" />
</form>
Ajax script is fine
here is fiddle which is making ajax request fine
ajax.php looks fine as well
$id = $_POST['id'];
$comment = $_POST['comment'];
$username = $_POST['username'];
$array = $pdo->prepare("INSERT INTO `comments`
(id, comment, user)
VALUES
(:id, :comment, :username)"
);
$array->execute(array(
':id' => $id,
':comment' => $comment,
':username' => $username));

Categories

Resources