How to make auto_search using ajax jquery, php and mysql - php

I have created auto suggest using Javascript AJAX now I want to create auto suggest using Jquery AJAX here is the code I have written using jquery AJAX
This is my indexa.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#search_input").keyup(function(){
var txt = $("#search_input").val();
$.get("search.inc.php?search_username="+document.search_form.txt, {suggest: txt}, function(result){
$("searchResults").html(result);
});
});
});
</script>
</head>
<body>
<form id="search" name="search_form" action="<?php $_SERVER['PHP_SELF']; ?> " method="post">
Search For Names : <input type="text" id="search_input" name="search_text"><br/><br/>
<!-- <input type="submit" > -->
</form>
<div id="searchResults"></div>
</body>
</html>
and this is my search.inc.php
<?php
if (isset($_GET['searched_username'])) {
$username = $_GET['searched_username'];
}
if (!empty($username)) {
if (#$db_connect=mysqli_connect('localhost', 'root', '')) {
if (#mysqli_select_db($db_connect,'my_databse')) {
$query_like = "SELECT `user_name` FROM `members_data` WHERE `user_name` LIKE '%". mysqli_real_escape_string($db_connect,$username)."%'";
$query_like_run = mysqli_query($db_connect,$query_like);
$query_num_rows = mysqli_num_rows($query_like_run);
if ($query_num_rows == NULL) {
echo 'No Result Found';
} else {
if ($query_num_rows == 1) {
echo $query_num_rows ." Result found<br/><br/>";
} else {
echo $query_num_rows ." Results found<br/><br/>";
}
foreach ($query_like_run as $searched_members) {
$searched_results = ''.$searched_members['user_name']."<br/>";
echo $searched_results;
}
}
}
}
}
?>
what I am doing worng . Please Help me

Remove the values from the url and change the key to search_username
Do the following:
<script type="text/javascript">
$(document).ready(function(){
$("#search_input").keyup(function(){
var txt = $(this).val();
$.get("search.inc.php", {searched_username: txt}, function(result){
$("#searchResults").html(result);//don't forget the # for the id
});
});
});
</script>

The param name is different between your indexa.php and search.inc.php files.
You should use
if (isset($_GET['search_username'])) { $username = $_GET['search_username']; }
or
if (isset($_GET['suggest'])) { $username = $_GET['suggest']; }
To get the value your wanted in search.inc.php file
or change search.inc.php?search_username="+document.search_form.txt
to
search.inc.php?searched_username="+document.search_form.txt

Related

How to view live search results in a selectable list?

I am totally new in jQuery so hope my question be simple:
I wrote a simple jQuery live search program with PHP and mySQL and it works good.
My question is: I want to show search results in a list then select one of the showing results to be written in the text box.
HTML code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function (){
$(document).on('keyup', '[name="state"]', function() {
var partialState = $(this).val();
$.post("getStates.php",{partialState:partialState}, function(data){
$("#results").html(data);
});
});
});
</script>
</head>
<body>
<input type = "text" name = "state" autocomplete = "off"/>
<br>
<div id = "results"> </div>
</body>
</html>
My php code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$con = mysqli_connect("localhost", "root", "")
or die("Failed to connect to the server: " . mysql_error());
mysqli_select_db($con, "airlines")
or die("Failed to connect to the database: " . mysql_error());
$partialStates = strtoupper($_POST['partialState']);
if(!$partialStates)
{
echo "";
}
else
{
$states = mysqli_query($con,"select distinct source from flights where source like '%$partialStates%'") or die(mysql_error());
while($row = mysqli_fetch_array($states))
{
echo "<div>" . $row['source'] . "</div>";
}
}
?>
Any help?
First look into prepared statement to prevent sql injection at where source like '%$partialStates%'.
Then, instead of returning HTML,
while($row = mysqli_fetch_array($states))
{
echo "<div>" . $row['source'] . "</div>";
}
it would be more convenient to work with JSON:
$sources = array();
while($row = mysqli_fetch_array($states)) {
$sources[] = $row['source'];
}
header('Content-Type: application/json');
echo json_encode($sources);
To select the first returned state, and update the input box. change
$.post("getStates.php",{partialState:partialState}, function(data){
$("#results").html(data);
});
to
$.getJSON( "getStates.php", { partialState: partialState }, function( states ) {
$('input').val(states[0]);
});
<?php
//PHP Code
error_reporting(E_ALL);
ini_set('display_errors', 1);
$con = mysqli_connect("localhost", "root", "root")
or die("Failed to connect to the server: " . mysql_error());
mysqli_select_db($con, "dedecms")
or die("Failed to connect to the database: " . mysql_error());
$partialStates = strtoupper($_GET['partialState']);
if(!$partialStates)
{
echo "###";
}
else
{
$states = mysqli_query($con,"select typename from dede_arctype where typename like '%$partialStates%'") or die(mysql_error());
$sources = array();
while($row = mysqli_fetch_array($states)) {
$sources[] = $row['typename'];
}
header('Content-Type: application/json');
echo json_encode($sources);
}
?>
HTML Code:
<html>
<meta charset="utf-8">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function()
{
$(document).on('mouseout', '[name="state"]', function(){
var html;
var partialState = $(this).val();
$.getJSON("getStates.php",
{
partialState: partialState
}, function(states)
{
$('input').val(states[0]);
$.each(states, function(i, value)
{
html += value;
$("#results").html(html);
});
});
});
});
</script>
</head>
<body>
<input type="text" name="state" autocomplete="off" />
<br>
<div id="results"> </div>
</body>

What is wrong with my AJAX login management code? login.php is working, but ajax.js wont

What is wrong with my AJAX login management code?
When I try to login using my username and password, it goes perfectly with PHP, but my AJAX code wont to be work at all! What is the problem?
(NOTE: I'm new in jQuery and AJAx)
I have this code for index.php:
<html>
<head><title>Login form</title></head>
<body>
<form id="myForm" action="testlogin.php" method="post">
username: <input type="text" name="username"> <br />
password: <input type="password" name="password"> <br />
<button id="submit">Login</button>
</form>
<div id="ack"></div>
<script type="text/javascript" src="jquery-2.0.2.js" ></script>
<script type="text/javascript" src="testajax.js"></script>
</body>
</html>
And I have this code for testlogin.php:
<?php require_once("includes/connection.php"); ?> // starting the session.
<?php
$username = mysql_real_escape_string( $_POST["username"]);
$password = mysql_real_escape_string( ($_POST["password"]));
$sql = "SELECT * FROM users2 WHERE (username='$username' AND password='$password')";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if($res === FALSE) {
die(mysql_error()); // TODO: better error handling
}
if( $row[0] > 0)
echo "Login Successful";
else
echo "Failed To Login";
?>
<?php include("includes/footer.php"); ?> //closing the session
finally I have this testajax.js code:
$ ("button#submit") .click(function() {
if ( $( "#username") .val() == "" || $( "#password") .val() == "" )
$("div#ack") .html("Please enter both username and password");
else
$.post ($("#myForm") .attr("action"),
$ ("#myForm :input") .serializeArryay(),
function(data) {
$("div#ack") .html(data);
});
$("#myForm") .submit(function) {
return false;
}
});
Try using this:
$("#myForm").submit(function(e){
e.preventDefault();
if ($('input[name="username"]').val() == "" || $('input[name="password"]').val() == "")
$("#ack").html("Please enter both username and password");
else
$.post($(this).attr("action"), $(this).serialize())
.done(function(data) { $("#ack").html(data); })
.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
I fixed your spacing (may have happened when you copy and pasted) and cut your code down a bit.
When you submit the form it will either be successful and run .done(...) or it will fail and run .fail(...). This should help you work out exactly where the script is failing.

print_r($_REQUEST) not showing all datas after showing few datas

print_r($_REQUEST) is not showing all the datas after redirecting from a page from which form is being submitted. In the redirected page it is showing some datas but not all.In the localhost all the requested datas are showing fine,but in the server the problem is occurring.
I have created a php.ini & put max_execution_time = 160; post_max_size = 250M; into the file & uploaded it in the server. But still couldn't get any solution.
Here is code. Actually some page are included after checking condition and then the form is being submitted after filling fields.
include("configuration.php");
if(isset($_REQUEST["save_update"]) && $_REQUEST["save_update"]!="")
{
include("quotation_save.php");
header("location:http://mpsinfoservices.com/projects/topline/quotation.php?enquiry_id=".$_REQUEST["enquiry_id"]."&displaying_id=".$_REQUEST["displaying_id"]);
}
$enqid = $_REQUEST["enquiry_id"];
$displaying_id = $_REQUEST["displaying_id"];
$len_of_disp = strlen($displaying_id);
/*if(preg_match('/E/',$displaying_id))
{
echo substr($displaying_id,0,6);
echo "<br/>".substr($displaying_id,strlen(substr($displaying_id,0,6)));
if(preg_match('/F/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
$ch_from_find_str = 'F';
$find_str = substr($displaying_id,0,7);
$ch_from_find_str = substr($find_str,6,1);
}
if(preg_match('/PKG/',$displaying_id))
{
$find_str = substr($displaying_id,0,9);
echo $find_str;
}
*/
$sql_enquiry = mysql_query("SELECT * FROM `enquiry_master` WHERE `id`='".$enqid."' AND `displaying_id`='".$displaying_id."'");
$row_enquiry = mysql_fetch_assoc($sql_enquiry);
$sql_client_info = mysql_query("SELECT * FROM `client_info` WHERE `client_id`='".$row_enquiry['customer_id']."'");
$row_client_info = mysql_fetch_assoc($sql_client_info);
?>
<link type="text/css" href="css/cupertino/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<link type="text/css" href="css/jquery.dataTables_themeroller.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/function.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<link type="text/css" href="css/style.css" rel="stylesheet">
<style>
.client_name
{
border:none;
}
.client_name_mouseover
{
border:1px solid #000;
}
</style>
</head>
<body>
<?php include("includes/header.php"); ?>
<div id="page-container">
<?php
include("includes/left_menu.php");
?>
<div id="page_content" style="float:left;">
<div style="margin-top:25px;">
<div style="padding-top:10px;">
<div style="color:#000;font-weight:bold;font-size:12px;font-family:verdana;">Client Details</div>
<div>Name:- <input type="text" name="client_name" id="client_name" class="client_name" value="<?php echo $row_client_info["client_firstname"].$row_client_info["client_middlename"].$row_client_info["client_lastname"];?>" readonly="readonly"/></div>
<div>Email:- <?php echo $row_client_info["client_email_id"]; ?>
</div>
<div>
<?php
$sql_quotation_insert_status = mysql_query("SELECT `status` FROM `quotation_insert_status` WHERE `enquiry_id`='".$enqid."'");
if( mysql_num_rows($sql_quotation_insert_status)>0)
{
$res_quotation_insert_status = "insert";
}
else
{
$res_quotation_insert_status = "";
}
?>
<form name="quotation" class="quotationfrm" method="post" enctype="multipart/form-data" action="quotation.php">
<input type="hidden" name="displaying_id" value="<?php echo $displaying_id; ?>"/>
<input type="hidden" name="enquiry_id" value="<?php echo $enqid; ?>"/>
<input type="hidden" name="save_update" <?php if($res_quotation_insert_status=="insert"){?>value="update" <?php } if($res_quotation_insert_status==""){?> value="save_quotation" <?php } ?>/>
<?php
if(preg_match('/E/',$displaying_id))
{
if(preg_match('/F/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/flight_quotation.php");
}
if(preg_match('/T/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/train_quotation.php");
}
if(preg_match('/H/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/hotel_quotation2.php");
}
if(preg_match('/CC/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/carrental_quotation.php");
}
if(preg_match('/I/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/insurance_quotation.php");
}
if(preg_match('/V/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/visa_quotation.php");
}
if(preg_match('/CR/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/cruise_quotation.php");
}
}
if(preg_match('/PKG/',$displaying_id))
{
if(preg_match('/H/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/hotel_quotation2.php");
}
include("quotation/package_quotation.php");
if(preg_match('/F/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/flight_quotation.php");
}
if(preg_match('/V/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/visa_quotation.php");
}
if(preg_match('/T/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/train_quotation.php");
}
if(preg_match('/CC/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/carrental_quotation.php");
}
if(preg_match('/I/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/insurance_quotation.php");
}
if(preg_match('/CR/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/cruise_quotation.php");
}
}
?>
<input type="button" class="save_quotation" <?php if($res_quotation_insert_status=="insert"){?> value="Update" <?php } if($res_quotation_insert_status==""){ ?> value="Save The Quotation" <?php } ?> style="margin-top:20px;" <?php if($res_quotation_insert_status=="insert"){ ?> name="save" <?php } if($res_quotation_insert_status==""){ ?> name="update" <?php } ?>/>
<?php if($res_quotation_insert_status=="insert"){?>
<input type="button" class="sendQuotation" value="Send Quotation"/>
<?php
}
?>
</form>
</div>
</div>
<script>
$(function(){
var no=0;
$("form").each(function(){
no++;
});
var suc = 0;
$("#client_name").live("mouseover",function(){
$(this).removeClass("client_name");
$(this).addClass("client_name_mouseover");
});
$("#client_name").live("mouseout",function(){
$(this).removeClass("client_name_mouseover");
$(this).addClass("client_name");
});
$(".mail_to_client").live("click",function(){
$.post("flight_quotation_mail.php?enquiry_id=<?php echo $enqid; ?>",$(".flight_quotation_frm").serialize(),function(data){
if(data=="success")
{
suc++;
}
if(no==suc)
{
$.post("mail_to_client.php?enquiry_id=<?php echo $enqid; ?>");
}
});
$.post("train_quotation_mail.php?enquiry_id=<?php echo $enqid; ?>",$(".train_quotation_frm").serialize(),function(data){
if(data=="success")
{
suc++;
}
if(no==suc)
{
$.post("mail_to_client.php?enquiry_id=<?php echo $enqid; ?>");
}
});
/*$.post("hotel_quotation_mail.php?enquiry_id=<?php echo $enqid; ?>",$(".hotel_quotation_frm").serialize(),function(data){
if(data=="success")
{
suc++;
}
if(no==suc)
{
$.post("mail_to_client.php?enquiry_id=<?php echo $enqid; ?>");
}
});*/
});
$(".save_quotation").live("click",function(){
$(".quotationfrm").submit();
});
$(".sendQuotation").live("click",function(){
for(var instanceName in CKEDITOR.instances)
CKEDITOR.instances[instanceName].updateElement();
var formData = $(".quotationfrm").serialize();
$.post("quotation_pdf.php",function(){
window.open("quotation_pdf.php?"+formData);
});
});
});
</script>
In some cases due to html elements in the data it will render only few, try checking View Source of that page.
The content and order of $_REQUEST is affected by variables_order directive in php.ini (see Description of core php.ini directives)
So, it is possible, that on your production environment value of variables-order directive differs from that in your development environment (localhost).
For example, set variables_order = "GPCS" in order to have G-$_GET, P-$_POST, C-$_COOKIE, S-$_SERVER arrays and all values from that arrays in $_REQUEST.

How can I use jQuery to submit a form using Ajax and then get the output of the page it submitted to?

I'm learning PHP and JavaScript, and I'm building a blogging platform. I'm working on the comment system. I want to check if the name field matches any users in the database, and if it does, then I want to display a message that the name is taken.
Here's the page that contains the form. (fullpost.php)
<!DOCTYPE html>
<html>
<?php
include ('functions.php');
connectDB();
$id = $_GET['id'];
$result = queryDB('SELECT * FROM posts WHERE id='.$id);
$post = mysql_fetch_array($result);
?>
<head>
<title><?php echo $post['title']; ?> - SimpleBlog</title>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".commentform").validate();
});
</script>
</head>
<body>
<div id="header">
SimpleBlog
</div>
<div id="wrapper">
<?php
//post found, display it
if (mysql_num_rows($result) >0) {
echo '<div class="post">';
echo '<div class="postheader">';
echo '<h1>'.$post['title'].'</h1>';
echo '<h5>by '.$post['author'].' at '.$post['date'].' in '.$post['category'].'</h5>';
echo '</div>';
echo '<p>'.$post['fullpost'].'</p>';
echo '</div>';
//display comments form
?>
<div id="commentform">
<form action="commentsubmit.php" method="POST" class="commentform"/>
<?php
//if not logged in, display a name field
if (!loggedIn()) {
echo '<label for="author">Name: </label><br />';
echo '<input type="text" name="author" class="required"/><br />';
}
?>
<label for="comment">Comment: </label><br />
<textarea type="text" name="comment" class="required"></textarea><br />
<input type="hidden" value="<?php echo $id; ?>" name="postid"/>
<input type="submit" name="submit" Value="Submit" id="sendbutton" class="button"/>
</form>
</div>
<?php
}
else {
//no posts found
echo "That post doesn't exist!";
}
$result = queryDB('SELECT * FROM comments WHERE postid='.$id.' ORDER BY date DESC');
$numcomments = mysql_num_rows($result);
//comments found, display them
if (mysql_num_rows($result) >0) {
if (mysql_num_rows($result) == 1) {
echo '<h5>'.$numcomments.' Comment:</h5>';
}
if (mysql_num_rows($result) > 1) {
echo '<h5>'.$numcomments.' Comments:</h5>';
}
while($comment = mysql_fetch_array($result)) {
echo '<h6> by '.$comment['author'].' on '.$comment['date'].'</h6>';
echo '<p>'.$comment['text'].'</p>';
}
}
else {
//no comments found
echo '<h4>No comments</h4>';
}
?>
</div>
</body>
</html>
Here's the page it submits to. (commentnew.php)
<?php
//creates a new comment
include('functions.php');
//form submitted
if (isset($_POST['submit'])) {
//set $author if not logged in
if(!loggedIn()) {
//check if username is taken
connectDB();
$result = queryDB("SELECT * FROM users WHERE username='".$_POST['author']."'");
if (mysql_num_rows($result) > 0) {
die('That name is taken!');
}
else {
//username is not taken
$author = mysql_real_escape_string($_POST['author']);
}
}
else {
//user is logged in, set author to their username
$author = $_SESSION['username'];
}
//$author is set, submit
if (!empty($author)) {
$postid = mysql_real_escape_string($_POST['postid']);
$comment = mysql_real_escape_string($_POST['comment']);
$date = mysql_real_escape_string(date("Y-m-d")." ".date("H:i:s"));
queryDB('INSERT INTO comments (postid,date,author,text) VALUES ("'.$postid.'","'.$date.'","'.$author.'","'.$comment.'")');
echo 'Comment Sent!';
}
}
?>
I tried using $.ajax in the script tags, but it seems to do nothing. Can I get an example of how to properly use it? How do I get it to pull the message from commentnew.php? Am I going about checking for the username the wrong way? Should I be using jQuery's validation plugin somehow?
in general:
var form = $("form.commentform");
$.post(form.attr('action') , form.serialize(), function(data) {
alert("Response: " + data);
});
Try this
$("form.commentform").submit(function(e){
e.preventDefault();
$.post({
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(reponse){
//here response will contain whatever you send from the server side page
}
});
}):
Look into jquery ajax function. That's what I use. http://api.jquery.com/jQuery.ajax/

error in login- php/ajax

i have a simple form to validate if an user exists in the db, and permit the login to another page (yes i remove the password validation to simplify the code, and i test without pass and the script always show Your login is not valid).
Database: emprego, table: users, fields: id, username, email, pass
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#login_form").submit(function () {
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.post("ajax_login.php", {
name: $('#name').val(),
}, function (data) {
if (data == 'yes') {
$("#msgbox").fadeTo(200, 0.1, function () {
$(this).html('Logging in.....').addClass('messageboxok').fadeTo(900, 1, function () {
document.location = 'secure.php';
});
});
} else {
$("#msgbox").fadeTo(200, 0.1, function () {
$(this).html('Your login is not valid').addClass('messageboxerror').fadeTo(900, 1);
});
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="" id="login_form">
User Name : <input name="name" type="text" id="name">
<div class="buttondiv">
<input name="Submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px">
<span id="msgbox" style="display:none"></span>
</div>
</form>
file: ajax_login.php
<?php
include("includes/f_banco.php");
conecta ();
$check = mysql_query("SELECT username FROM users WHERE username ='".mysql_real_escape_string($_POST['name'])."'")or die(mysql_error());
$row=mysql_fetch_array($check);
if ($row['username'] == $_POST['name']) {
echo "yes";
$_SESSION['name']=$row['username'];
}else{echo "no";}
?>
EDIT: updated code
what is the possible cause?
i see lots of problems
<?php
//removed the # from the post
$name = mysql_real_escape_string($_POST['name']);
//whys this here?
$row=mysql_fetch_array($check);
//name cant be used (common mistake)
$check = mysql_query("SELECT name FROM users WHERE name ='".$name."'")or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 == 1) {
echo "yes";
$_SESSION['name']=$name;
}
else
echo "no";
?>
try something like this
<?php
session_start();
include("includes/f_banco.php");
conecta ();
if(isset($_SESSION['name'])){echo "yes";}else{
$check = mysql_query("SELECT username FROM users WHERE username ='".mysql_real_escape_string($_POST['name'])."' LIMIT 1")or die(mysql_error());
$row=mysql_fetch_array($check);
if ($row['username'] == $_POST['name']) {
echo "yes";
$_SESSION['name']=$row['username'];
}else{echo "no";}
}
?>
Perhaps the use of the field name "name"? See jQuery issue with live click and input named "name"

Categories