Search button not working in instant search with jQuery - javascript

I have tried instant search using jQuery. It is working fine until I click the search button. When I click the search button the page will reload and the results would disappear.
Here's my code:
search.php
<div id="search-container">
<form action="search.php" method="POST">
<input type="text" name="key" id="key" placeholder="search" onkeydown="searchIt();"></input>
<input type="submit" name="search" id="search" value="search"></input>
</form>
</div>
<div id="res-container"></div>
And the script is:
<script type="text/javascript">
function searchIt(){
var text = $("input[name='key']").val();
text = text.trim();
if(text.length>3){
$.post("query.php",{index: text}, function(data){
$("#res-container").html(data);
});
}
}
</script>
query.php
if(isset($_POST['index'])){
$key = mysqli_real_escape_string($con, $_POST['index']);
$key = trim($key);
$result = "";
if(!empty($key)){
$query = "SELECT * FROM users WHERE first_name LIKE '%$key%' OR last_name LIKE '%$key%'";
$query_run = mysqli_query($con, $query);
$row_count = mysqli_num_rows($query_run);
if($row_count == 0){
$result = "No results!!!";
}else{
while($query_row = mysqli_fetch_array($query_run)){
$fname = $query_row['first_name'];
$lname = $query_row['last_name'];
$name = $fname.' '.$lname;
$mail = $query_row['email_id'];
$id = $query_row['emp_id'];
$result .="<div class=\"qitems\"><div class=\"name\">$name</div><div class=\"mail\">$mail</div></div>";
}
}
}else{
$result = 'please enter a word';
}
}
echo ($result);
Until this everthing is working fine, but when I try to click search button the results would disappear.
I tried adding this in the script:
$(document).ready(function(){
$("input[name='search']").click(searchIt());
});
But there is no change. Please help me with this.

This should work:
$(document).ready(function(){
$('body').on('click', 'input[name="search"]', function(event)
{
event.preventDefault(); // This is important, since you are interacting with a valid html form/element
searchIt();
});
});
Update:
I've made a codepen for you. Look at it, it works perfectly fine:
http://codepen.io/dschu/pen/VmRJPZ

The reason is button of type "submit" effectively submits the page to form URL, which is the same page, thus has the same effect, as reloading, - here is your "reset" behaviour. Besides solution above you can also change input type from submit to button, which will avoid submitting the form (and manually preventing the event).

Related

How to delete/edit sql entry using PHP and AJAX?

I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.
Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve. There's login.php page where the only functionality is typing username and password. If info matches info from SQL table, user proceeds to adminpanel.php.
This page should load a list of movies and create a table with that data. At the end of each row I want two buttons, edit and delete. What I'm trying to achieve is to delete current row where delete button is clicked, for delete button. Edit button should show hidden form just for the row where button was clicked. This form would contain button that actually updates data in SQL table after filling form and clicking the button. (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works.
Here's adminpanel.php
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript" src="changes.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
<style type="text/css">
*{text-align: center;}
.skriveni_input{
display: none;
};
</style>
</head>
<?php
require_once('connection.php');
if(!isset($_POST['btnlogin'])){
exit;
}
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";
$res = mysqli_query($conn,$query);
$rows = mysqli_num_rows($res);
if($rows == 1){
echo "Welcome ".$_POST['username']."<br><br>";
} else {
echo "<script>
alert('Wrong login info');
window.location.href='login.php';
</script>";
exit;
}
$query = "SELECT * FROM movies";
$result = $conn->query($query);
echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
echo '<td>'.$row["name"].'</td>';
echo '<td>'.$row["year"].'</td>';
echo '<td>'.$row["genre"].'</td>';
echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
echo "</tr>";
echo "<tr>
<td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
<td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
<td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
</tr>";
}
echo "</tbody></table>";
?>
<h3>Add movie form: </h3>
<form action="" method="POST">
<label for="movie_name">Movie name : </label>
<input type="text" name="movie_name" id="movie_name">
<br><br>
<label for="movie_year">Year: </label>
<input type="text" name="movie_year" id="movie_year">
<br><br>
<label for="movie_genre">Genre: </label>
<input type="text" name="movie_genre" id="movie_genre">
<br><br>
<input type="submit" name="submit_movie" id="submit_movie" value="Submit">
</form>
</html>
Here's my javascript file with ajax calls:
$(document).ready(function(e){
$('#submit_movie').click(function(e){
e.preventDefault();
var movie_name = $('#movie_name').val();
var movie_year = $('#movie_year').val();
var movie_genre = $('#movie_genre').val();
$.ajax({
type: 'POST',
data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
url: "insert.php",
success: function(result){
alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
document.location.reload();
}
})
});
$('.btnedit').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().html();
alert(id);
//unfinished function
})
$('.btndlt').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().prev().html();
e.preventDefault();
$.ajax({
type: 'POST',
data: {id:id},
url: 'delete_row.php',
success: function(result){
alert('Successfully deleted.');
document.location.reload();
}
})
})
});
Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :
<?php
require_once('connection.php');
if($_REQUEST['movie_name']){
$name = $_REQUEST['movie_name'];
$year = $_REQUEST['movie_year'];
$genre = $_REQUEST['movie_genre'];
$sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
$query = mysqli_query($conn, $sql);
}
?>
Here's delete_row.php file for deleting entry with delete button:
<?php
require_once('connection.php');
$id = $_REQUEST['id'];
if(isset($_REQUEST['delete'])){
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.
At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies. However the movie is still there and in SQL database.
When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.
Edit
I should've said that security is not my concern right now, I do this exercise just for functionalities I described. :) Security is my next step, I am aware this code is not secure at all.
When I tried to debug delete_row.php I found out that index "id" is
undefined every time even though I think I'm passing it with ajax
call.
The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.
When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.
On your specific code, the query will never run because of this line:
if(isset($_REQUEST['delete']))
Which is checking for a delete variable that was never sent in the first place, hence will always resolve false
Use this code instead on delete_row.php:
<?php
require_once('connection.php');
if(isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>

It is not able to auto-post with JS & AJAX

I have a formA that posts and saves to the MYSQL DB
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <== first visable form ,Submitting the data into DB
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
I have a hidden form called PayForm that store some var with hidden input method and get the $input_amount as amount from FromA
It is noted that I haven't made the submit button .
This form is going to post to the EPayment Gateway .
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
...
</form>
Here is my idea workflow :
1)User press "Submit" button in FormA ==> info in FormA is going to store into DB .
2)JS is running . Force the PayForm to post automatically . Then, The user is directed to the Payment Gateway .
In short , the Submit button in FormA trigger both forms post
actions .
Here is my JS
<script type='text/javascript'>
var payFormDone = false;
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // THIS WILL TRIGGER THE NEXT CODE
$('#payForm').submit();
}
});
$("#payForm").submit(function(event) {
/* stop form from submitting normally */
//event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, {
merchantId: $('#merchantId').val(),
amount: $('#amount').val(),
orderRef: $('#orderRef').val(),
currCode: $('#currCode').val(),
mpsMode: $('#mpsMode').val(),
successUrl: $('#successUrl').val(),
failUrl: $('#failUrl').val(),
cancelUrl: $('#cancelUrl').val(),
payType: $('#payType').val(),
lang: $('#lang').val(),
payMethod: $('#payMethod').val(),
secureHash: $('#secureHash').val()
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#FormA').submit();
});
});
</script>
Now ,the idea is not working . It can only trigger second form action .
The first form action is not triggered .At least ,the data in FormA has not saved to the DB .
In short ,
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#payFormCcard').submit();
});
Is not working .I think !
update
This is how I post FormA to the server
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=big5");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Phone = $amount= $Purpose= $Ticket = "";
$CName_err = $Address_err = $Phone_err = $amount_err = $Purpose_err = $Ticket_err="";
// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
$input_CName = trim($_POST["CName"]);
if (empty($input_CName)) {
$CName_err = "Please enter a name.";
} elseif (!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z'-.\s ]+$/")))) {
$CName_err = 'Please enter a valid name.';
} else {
$CName = $input_CName;
}
......
if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
Database::disconnect();
}
}
?>
you should not comment event.preventDefault(); from the second form. Currently what happens is it submitting it as default action which is post to url.
Inside posting.done() please remove/detach the onSubmit handler for FormA just before calling the $('#FormA').submit();
posting.done(function( data ) {
alert('success');
$('#FormA').off('submit');
$('#FormA').submit();
});
EDIT:
Okay, why not send the formA fields with AJAX inside its onSubmit handler and submit formB from the posting.done() handler ?
<script type='text/javascript'>
$('#formA').on('submit', function(e){
e.preventDefault();
/* Send the data using post with element id name and name2*/
var posting = $.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>", {
field1: $('#field1').val(),
.....
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
$('#FormB').submit();
}
});
</script>
The submit handler for FormA actually prevents the submission of the form. That's why data is not saved to db.
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // => HERE you are preventing the form from submitting
$('#payForm').submit();
}
});
Here you are in the submit handler for the form, but the call to preventDefault stops the submit for FormA and instead triggers the submit of payForm.
See https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Also instead of having that you trigger via javascript I'd probably send the first one normally. Then as response of the POST in the first form You might print a message to the user with something like: "You are being redirected to the payment gateway.. " and an hidden form with all the fields that is triggered automatically after x seconds. IMHO this approach is easier and more reliable.
So in the first html page I'll remove all your javascript code and leave only:
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
When the user clicks on the button he submits the data to the php page in POST. On the server the data is saved to DB and the server prints a message to the user and redirect to the payment gateway (via javascript this time). Something like:
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') {
.... save data to db
?>
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
<p>You are being redirected to the payment gateway. If the redirect takes too long</p>
<input type="submit" value"click here">
</form>
<script>
// submits the form after 5 seconds
setTimeout(function(){ $('#payForm').submit(); }, 5000);
</script>
<?php } // this ends the POST block ?>
If I correctly understand the question:
<script type='text/javascript'>
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
var $payForm = $("#payForm");
$.post( $payForm.attr('action'), $payForm.serialize(), function(data) {
alert('success');
// redirect to whereever you want
});
});
});
</script>
UPDATE:
case 2) redirecting to payment gateway:
<script type='text/javascript'>
$("#payForm").submit(function(e) {
alert('redirecting to payment gateway');
});
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
$("#payForm").submit();
});
});
</script>
NOTE: replace all your script with just this one, and check in browser if requests are made in the data posted - F12 (Developer tools) - Network tab.
Keep in mind that this code is written on a scratch so it may have some errors, but it shows the way.

How to check if username exists without refreshing page using wordpress

I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>
use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**

can anyone fix this. jQuery $.post

i have a form like this (already add jquery latest)
echo '<form name="chat" id="chat" action="/pages/guicsdl.php" method="post">';
echo bbcode::auto_bb('chat', 'text');
echo '<textarea rows="3" name="text" id="text"></textarea><br/>';
echo '<input type="hidden" name="trave" value="'.$trave.'" /><input type="submit" name="submit" value="Gửi" /></form>';
and the js
$(document).ready(function() {
$("chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
and the file guicsdl.php
if(isset($_POST['submit'])) {
$noidung = functions::check($_POST['text']);
mysql_query("INSERT INTO `status` SET `user_id`='".$user_id."', `text`='".$noidung."', `time`='".time()."'");
mysql_query("UPDATE `users` SET `tongchat`= tongchat+1 WHERE id = '".$user_id."' ");
$trave = isset($_POST['trave']) ? base64_decode($_POST['trave']) : '';
header("Location: $trave");
}
i only want when i submit the form, the page doesn't refresh, the data insert to database. can any one help me fix? pls, and thanks. sorry for bad english.
You have to add return false; so that the browser 'understands' that it should not submit the form directly.
$(document).ready(function(){
$("#chat").submit(function(){
$.post('/pages/guicsdl.php', $("#chat").serialize() );
return false;
});
});
Another way (which I myself prefer) is to tell the event to not do it's default behavior.
$(document).ready(function(){
$("#chat").submit(function(ev){ // note the extra parameter
ev.preventDefault();
$.post('/pages/guicsdl.php', $("#chat").serialize() );
});
});
Wilmer also noticed that you had forgotten to put a # for the jQuery identifier when selecting the chat form.

jQuery Mobile submit with PHP without AJAX and JavaScript

Sorry, I consider myself as a real newbie around jQuery Mobile. I'm not good at all regarding JavaScript. Here's the thing. I want to build a jQuery Mobile site without using AJAX. Just want the nice design from jQuery Mobile and then use PHP to submit forms etc.
I tried to build a simple page that submit first and last name to a MySQL database. It will submit, tell the user that it's submitted and then the user can press [Page 2] to see all the results. Now I use if(isset()) to display the message and else to display the form. So, the user who enter the site will get the form, when press [Submit] he/she will get the message that first and last name was submitted. Then press the button [Page 2] to see all the first and last names.
PHP (index.php)
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add">
</form><br>';
}
Page 2
PHP (page2.php):
$query = $db->query("SELECT * FROM name");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['fname'] . ' ' . $row['lname'] . '<br>';
}
$db = NULL;
echo 'Index';
Let's say I enter "Test" as first and last name. It will echo out "Test Test was added!". If I now press [Page 2] I will see that "Test Test" was added. BUT when I then press [Index] to go back I want it to display the form again, but the message "Test Test was added!" is displayed again instead of the form, why? I have to update the page to get the form. Now, if I enable data-ajax it's working with submitting and back-button. BUT then I have to press update at page2.php when I get there to see all the first and last names. Do I make myself understood what's the problem?
Sorry, really new at jQuery Mobile and I can't find the answer at Google. Everyone is using JavaScript to submit data. Is it possible this way or do I have to learn JavaScript to submit forms? Read somewhere that using buttons instead of submit-buttons affect it.
Thanks in advance! :)
I think you are looking to modify the DOM after the request? So post the form, add the user then display the results without having to click the button.
So on your ajax call use the done function to hide the form and show the results.
Take a look below and let me know if it helps.
EDIT: Added the .on click for the button. You may also want to look at adding a keypress checker to the inputs or an onsubmit on the form.
<div id="content">
<?php
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false" id="contentForm">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add" id="sendButton">
</form><br>';
}
?>
</div>
<script type='text/javascript'>
<!-- https://api.jquery.com/jQuery.ajax/ -->
$('#sendButton').on("click", function(){
$.ajax({
type: "POST",
url: "page2.php",
data: $('#contentForm').serialize()
})
.done(function( msg ) {
$('#content').html( msg );
});
});
</script>

Categories