Making jQuery autocomplete work with database as source - javascript

I'd like to use the autocomplete widget to make a search bar that will go through a userlist which is stored in a database. I'm using MySQL.
I tried the autocomplete with a local source (a JS array), and it works. But with my PHP script, it doesn't.
Why ?
Here's my HTML code :
<form method="get" action="" class="form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="InputSearch">Search Engine</label>
<input type="email" class="form-control" id="InputSearch" placeholder="Search a member...">
<button type="submit" class="btn btn-success">Search</button>
</div>
</form>
Here's my jQuery code :
$(document).ready(function() {
$(function() {
$( "#InputSearch" ).autocomplete({
source: "search.php",
dataType: 'json'
});
});
});
And here's my search.php code :
$term = trim(strip_tags($_GET['term']));
$sQuery = "SELECT `name` FROM `user` WHERE `name` LIKE '%$term%'";
$aUsers = DBOperation::queryGetMulti($sQuery);
echo json_encode($aUsers);
DBOperation is a class I use for Database queries, in this case it will simply return an array containing every line it reads in subarrays. It has been used in many other cases and works fine.
Thanks.

Related

How do I pass a program name from php/html, as a variable to javascript rather than hard coding it in the ' $.get' statement

I have a dropdown that uses JQuery/Javascript within my php/html program.
This works fine if I hard code the name of the program that runs the SQL to load data into the dropdown list.
I would like this code to be re-usable rather than duplicate it for each dropdown list (I want 2 in the current instance) so I would like to know how to pass different program names as each dropdown list accesses different files. Example: ClubID dropdown requires data from clubs using clubsSearch.php but MemberTypeID requires data from memtyp using memtypSearch.php.
Here is the Javascript including my latest effort to pass the program name as a variable:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("click input", function()
{
/* Get input value on change */
var srchName = <?php echo $SearchName?>;
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get(srchName, {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
If I use
$.get("clubsSearch.php", {term: inputVal}).done(function(data){
it works fine.
The relevant section of the form is:
<div class="col-6 col-md-4">
<div class="form-group <?php echo (!empty($ClubIDer)) ? 'has-error' : ''; ?>">
<label>Club ID:</label>
<div class="search-box">
<input type="hidden" name="clubID" value="<?php $SearchName = "\"clubsSearch.php\"";?
>" >
<input type="text" name="ClubID" autocomplete="off" class="form-control"
value="<?php echo $ClubID; ?>" >
<?php echo $SearchName?>
<div class="result">
</div>
<span class="help-block"><?php echo $ClubIDer;?></span>
</div>
</div>
</div>
The **$SearchName** displays as "clubsSearch.php" but in Chrome's developer tools I can see the javascript has not recognised the variable var srchName = ; x and no dropdown list appears.
Can anyone tell me how to present the search name to the javascript as I am completely unfamiliar with it. Any assistance would be appreciated.
Pass the program name in the data- attr like
<select name="WHATEVER" id="WHATEVER" data-program="YOUR_PROGRAM_NAME">
in JS get it like
var srchName = $(this).attr("data-program");
Resolved: In the html
<input id="ClubID" data-pgm="\"clubsSearch.php\"">
and in the Javascript
var srchName =input.dataset.pgm

prevent result, show through AJAX, after reload browser

I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.

Get value from input text in php without pressing Enter

Hay I'm new to php and I have made php code like this :
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
</div>
<br/><br/>
<?php
echo $myValue;
?>
</form>
When I want to show the echo message, I need to hit enter on my keyboard first in order to get the value of $_POST['nama_tamu'];. My question is can I get the value of nama_tamu input without pressing enter, or maybe without using POST or GET and then assign it to $myvalue?
You will need to use Javascript. You can use the Jquery events :
<script>
$( "#nama_tamu" ).keyup(function() {
alert( $this.val() );// alerting the value of the input field
});
</script>
Web development is all about communication. In this case, communication between two (2) parties, over the HTTP protocol:
The Server - This party is responsible for serving pages.
The Client - This party requests pages from the Server, and displays them to the user. In most cases, the client is a web browser.
Each side's programming, refers to code which runs at the specific machine, the server's or the client's.
You cannot get values without submitting for the user has not entered any yet. PHP is a server side language. To get values before submit and do certain actions with them you will need javascript (a client side programming language).
The simplest method to get a value is using the getElementById().
var something = document.getElementById('someid');
<input type="text" name="something" id="someid">
You can also use jQuery:
var something = $('#someid').val();
Conclusion
The simple answer to your question is: This is not possible.
Why not? I hear you asking. Because PHP doesn't know the values of your form before you send the form to your webserver.
Use keyup().
function check(id)
{
document.getElementById("result").innerHTML = id;
}
<input type="text" name="test" id="test" onkeyup="check(this.value);">
Your value: <span id="result"> </span>
$(document).ready(function() {
$("#check").keyup(function(){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="check" >
For this purpose you should use .keyup function/event. Following are the snippet :
$(document).ready(function () {
$("#nama_tamu").keyup(function(){
$("#enterdata").html($("#nama_tamu").val());
$.ajax({
type: 'POST',
url: "getdata.php",
data: "nama_tamu="+$("#nama_tamu").val(),
success: function(res)
{
$("#outputdata").html(res);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
<br> You press following character:<div id="enterdata"> </div>
</div>
<br/><br/>
<div id="outputdata"></div>
<?php
echo $myValue;
?>
</form>
Also create one file for the required output.
Now in getdata.php file
echo $nama_tamu=$_POST['nama_tamu'];

Add HTML form on button click

I have an HTML form in my website/application.
The form has lots of fields of input text, select, and PHP code, as well, to fill drop down values.
Is there any way I can clone/create the same form when the user clicks on the Add button? Let's say, if the user clicks 5 times, it would have five forms on the UI.
HTML
<form id = "buyerForm" role="form" method="POST" enctype="multipart/form-data" style="margin-top:30px;">
<span class="customerno" style="font-size: 22px;">Buyer 1 (Form 2)</span>
<div class="form-group">
<label>APPLICANT DETAILS</label>
</div>
<div class="form-group">
<label>Mr. / Mrs</label>
<select class="form-control" name="jnameTitle" id="jnameTitle">
<option>Please Select One</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="MS">MS</option>
</select>
</div>
// similar fields are omitted to reduce the complexity
<div class="form-group">
<label>Address</label>
<textarea name="jaddress" id="jaddress" class="form-control" cols="80" rows="5" ></textarea>
</div>
<button type="submit" name="jointCustomers" id="jointCustomers" class="btn btn-success btn-lg btn-flat">Save</button>
<button type="reset" class="btn btn-default btn-lg">Reset</button>
</form>
if you're using jQuery (or dont mind using it) you could just use clone to add the form again to the parent container
$("#youButton").click(function(){
$("#buyerForm").clone().appendTo("#yourParentWrapper");
});
see this fiddle
Yes, there is a way.
Lets say you have the main page -> mainPage.php, where you can have a list and the button (addForm).
Then you will have your myform.php page that will generate a form it self.
The process is very simple.
You press the btn AddForm
You make a request using AJAX against your function that generate the form in the myform.php page.
Inside your AJAX code, you will add your form inside the list object.
Note: This is only a basic idea. You must adapt the code to your needs.
//Your main page, will contain a list.mainPage.php
<ul id="myFORMS">
<li><button id="idBtnElement" type="button">AddForm</button></li>
</ul>
//Your php code to create the form. You can create a function if you want
$arrToJSON = array(
"myFormHtml"=>"You will put your HTML form code here"
);
return json_encode(array($arrToJSON));
//Your javaScript code
$(document).on("event", "#idBtnElement", function(){
//Data you want to send to php evaluate
var dt={
ObjEvn:"btn_ADDFORM"
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "myFormGenerator.php",
type: "POST",
data: dt,
dataType: "json"
});
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
formStrHtml=dataset[index].myFormHtml;
}
//JavaScript
//Here you can grab formStrHtml in apped at the end of the list in your main page.
$("#myFORMS ul").append('<li>'+formStrHtml+'</li>');
});
//Ajax Fail
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}

My ajax code don't send the data to the database

I want to use ajax to add data in the database but nothing happens
i don't know whats wrong is it in the ajax!or in the php
This is part of my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#commentForm").submit(function(){
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context},
});
});
});//end of document ready function
</script>
this the html form:
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name = "context" class="form-control" id="inputmessage" rows="3" placeholder="Enter your comment here . . "></textarea>
</div>
</div> <!-- End of /.form-group -->
<input type="hidden" value = "$Item['Item_Name']" name="I_name"/>
<input type="hidden" value ="$U_N" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary" ;>Send</button>
</div>
</div>
</form>
and this is a part of the php page for adding to the database
extract($_POST)
if(isset($context))
{
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}
var U_N = $("input#U_N").val();
var I_name = $("#I_name").val();
var context = $("#context").val();
The jQuery selectors are wrong, you're not selecting anything. The # selector stands for id attribute, but you're trying to select by value of name attribute. You should either add/change id attributes of your input fields, or use
var U_N = $("input[name=U_N]").val();
var I_name = $("input[name=I_name]").val();
var context = $("[name=context]").val();
Tip: next time use developer console inside your browser, you can easily test if selectors are correct. You can type in javascript code as you would inside .js file and test if it's working like you expect.
Also, don't do this in your PHP, use prepared statements.
Did you included you Database conection on your Backend script?
extract($_POST)
'if(isset($context)) {
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}'
i think here you should include you database info, 'include_once("database info.php"); , also make sure you ajax will return a result, and echo php errors, just to be sure its an ajax or php error,
I have few comment regarding your issue :
Replace $("document").ready(function(){ with
$(document).ready(function(){
Before extracting in PHP ,
try var_dump($_POST)
Based on your HTML code use:
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
Here is final working example. Just add "ev" argument to submit callback function , then use ev.preventDefault() in it.
$(document).ready(function(){
$("#commentForm").submit(function(ev){
ev.preventDefault();
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context}
});
});
});//end of document ready function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name="context" class="form-control" id="inputmessage" rows="3"
placeholder="Enter your comment here . . "></textarea>
</div>
</div>
<input type="text" value="" name="I_name"/>
<input type="text" value="" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary">Send</button>
</div>
</div>
</form>

Categories

Resources