I want to auto load the text box with some database values. I tried with following code but not getting the values for autocomplete. I used firebug to debug the script but neither it is showing error nor I am getting results.
Here is the code-
<script src="js/jquery1.10.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script>
$('#userlist').autocomplete({
source: function( request, response ) {
//alert('hi')
$.ajax({
url : 'ajax.php',//?action=getUsers',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'users'
},
success: function( data ) {
//alert('in');
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
</script>
<form action="search_result.php" name="searchform" method="post">
<input id="userlist" type="text" class="form-control txt-auto"/>
</form>
You have to wait for $('#userlist') to be created :
$(document).ready(function(){
$('#userlist').autocomplete({
// code ...
});
});
Related
I have autocomplete jQuery script working for pulling suggestions from MySQL database when typing in form fields on the page (3 input fields).
That is working fine, but what I would like is to when I select suggested option in the first field - all 3 fields should be filled.
Fields that I have right now is first name, last name, and company. When I select the first name - last name and company should be automatically filled with data.
Here's php:
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function()
{
$( "#first_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#last_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#company" ).autocomplete({
source: 'autocomplete.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="ui-widget">
<p>First name</p>
<input type="text" id="first_name">
</div>
<div class="ui-widget">
<p>Last name</p>
<input type="text" id="last_name">
</div>
<div class="ui-widget">
<p>Company</p>
<input type="text" id="company">
</div>
</div>
</body>
</html>
And here's the autocomplete.php file:
<?php
$host="localhost";
$username="user";
$password="password";
$databasename="dbname";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$searchTerm = $_GET['term'];
$select =mysql_query("SELECT * FROM jemployee WHERE first_name LIKE '%".$searchTerm."%'");
while ($row=mysql_fetch_array($select))
{
$spojeno = $row['first_name'] . ' ' . $row['last_name'] . ' ' . $row['kompanija'];
$data[] = $spojeno;
}
//return json data
echo json_encode($data);
?>
So, when the suggested option from "first_name" is selected - "last_name" and "company" should be filled with corresponding data from a database. Any suggestions?
Use something Jquery likes:
$(document).on('keyup', '#firstname', funtion(){
$.ajax({
type:"POST",
url:"ajax.php",
data:$("#firstname").val();
},
success:function (res){
$("#lastname").val(res.lastname);
$("#company").val(res.company);
},
)};
});
And PHP ajax.php file:
<?php
\\Select lastname, company with $_POST['data']
echo json_endcode($result);
Should check and handle the ajax response. If you can you this solution, please make it better.
What I did is passing the ajax "item" result as the autocomplete "value" :
It looks like this :
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id, //the data that will be shown in the list !
value: item //item holds "Id" and "Name" properties
};
}))
}
I then subscribe the autoComplete "select" event to prevent it's default behaviour.
I then fill the different fields I need to :
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
here's the entire autocomplete call, in case it helps ;)
$("#CustomerId").autocomplete({
source: function (request, response) {
$.ajax({
url: "/.../../GetAvailablePartnerInformations",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id,
value: item
};
}))
}
})
},
change: function (event, ui) {
//Forces input to source values, otherwise, clears
//NOTE : user could still submit right after typing => check server side
if (!ui.item) {
//http://api.jqueryui.com/autocomplete/#event-change -
// The item selected from the menu, if any. Otherwise the property is null
//so clear the item for force selection
$(event.target).val("");
$(event.target).addClass("is-invalid");
}
else {
$(event.target).removeClass("is-invalid");
}
},
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
//Note : the "value" object is created dynamically in the autocomplete' source Ajax' success function (see above)
debugger;
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
messages: {
noResults: "",
results: function (resultsCount) { }
},
autoFocus: true,
minLength: 0
})
I am trying to get the query results by hitting the enter button on the drop down of the autocomplete results. It works fine if I use the mouse to click the result i want but wont work if i use the enter key.
The first function gets the autocomplete results and the second submits the result to get the data from that particular id.
JQUERY
$(document).ready(function () {
$("#equipment").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
$('#eq_id').val(ui.item.id);
}
});
$(document).off("keypress", "#equipment");
$(document).on("keypress", "#equipment", function(event) {
//if (!e) e = window.event;
if (event.keyCode == '13'){
$('#loading').show();
var eq_id = $("#eq_id").val();
var dataString = 'eq_id=' + eq_id;
$.ajax({
type: "POST",
url: "updateForm.php",
data: dataString,
success: function(html){
$("#formAddEquip").hide();
$("#showuserresult").show();
$("#showuserresult").html(html);
$("#equipment").val("");
$('#loading').hide();
}
});
return false;
}
});
});
And here is the form
<form action="" method="post" id="#somesearch">
<label for="equipment" id="eq_id_label">Search Equipment</label>
<input type="text" id="equipment" name="equipment" />
<input type="hidden" id="eq_id" name="eq_id" />
</form>
Start with these improvements
$(function() { // only one "load"
$("#equipment").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
$('#eq_id').val(ui.item.id);
}
});
$("#somesearch ").on("submit", function(e) {
e.preventDefault(); // stop submission
});
$(document).on("keypress", "#equipment", function(event) {
//if (!e) e = window.event;
if (event.keyCode == '13') {
$('#loading').show();
var eq_id = $("#eq_id").val();
var dataString = 'eq_id=' + eq_id;
$.ajax({
type: "POST",
url: "updateForm.php",
data: dataString,
success: function(html) {
$("#formAddEquip").hide();
$("#showuserresult").show();
$("#showuserresult").html(html);
$("#equipment").val("");
$('#loading').hide();
}
});
}
});
});
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});
I have a dialog box that loads from an ajax call.. It works good. I want to have a link inside my dialog box that updates a DB and loads the results via ajax to the parent page, without my dialog closing. Is this even possible? Here is what I have so far.
This is what my parent page called deals_calendar.php looks like. The ajax call works fine and opens a dialog box that is loaded with content from get_deals.php.
<script type="text/javascript">
$("#calendar td").on('click', function() {
var data = $(this).data();
$.ajax({
type:"GET",
url: "get_deals.php",
data: { monthID: data.month, dayID: data.day, yearID: data.year },
success: function(data){
var title = $( "#dialog" ).dialog( "option", "title", "Deals" );
$('#dialog').dialog({
open: function (event, ui){
$('a').blur();
$(this).scrollTop(0);
}
});
$("#dialog").html(data).dialog("open");
}
});
$("#dialog").dialog(
{
bgiframe: true,
autoOpen: false,
height: 450,
width:900,
modal: false,
closeOnEscape: true
}
);
});
</script>
<div id="dialog" title="Dialog Title"> </div>
<div id="return"></div>
Then in my get_deals.php script I have this
<script type="text/javascript">
$('#click').live('click', function(){
$.ajax({
type:"POST",
url: "deals_add_to_queue.php",
data: { monthID: data.month, dayID: data.day, yearID: data.year },
success: function(data){
alert("Please work!");
("#return").html(data);
}
});
});
</script>
<a id="click" href="#">click me</a>
I can't get this ajax call to fire and update the content on deals_calendar.php. Any help would be great. thanks
If the event is not being fired, you need to use event delegation.
$('body').on('click', '#click' function(){
$.ajax({
type:"POST",
url: "deals_add_to_queue.php",
data: { monthID: data.month, dayID: data.day, yearID: data.year },
success: function(data){
alert("Please work!");
("#return").html(data);
}
});
});
Really not familiar with jQuery. Is there anyway I can pass form data to a PHP file using jQuery?
FORM:
<div id="dialog-form" title="Fill in your details!">
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name"/>
<label for="email">Email</label>
<input type="text" name="email" id="email" value=""/>
<label for="phone">Phone</label>
<input type="phone" name="phone" id="phone" value=""/>
</fieldset>
</form>
It's a pop-up dialog with jQuery and gets submitted with:
$("#dialog-form").dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid) {
$.ajax({
url: 'process-form.php',
success: function (response) {
//response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
}
});
$(this).dialog("close");
}
}
}
});
What I want to do is to send the form data that the user enters into process-form.php, where it will be processed and sent as an email (which I can do). Just not to sure on the jQuery side of things. Is it even possible?
You can use the .serialize() function
$('yourform').serialize();
Docs for .serialize() here
You would use it like this :
$.ajax({
url: 'process-form.php',
data: $('form').serialize(), // **** added this line ****
success: function (response) { //response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
}
});
Yes, you can use the jQuery .post() method, which is detailed here
$.post( "process-form.php", $( "#dialog-form" ).serialize( ) );
Given your current code the easiest way is to serialize the form into the data property:
[...]
url: 'process-form.php',
data: $('#dialog-form').serialize()
You're on the right lines with $.ajax, but you need to actually pass the data with the submission, which you haven't done so far. You're best off setting the 'type' as well.
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid ) {
$.ajax({
url: 'process-form.php',
type: "post",
data: {
name: $('[name=name]').val(),
email: $('[name=email]').val(),
phone: $('[name=phone]').val(),
},
success: function (response) { //response is value returned from php
$( "#dialog-success" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
});
$( this ).dialog( "close" );
}
These variables should now be available in your PHP script as $_POST['name'], $_POST['email'] and $_POST['phone']
Whats the point for form if you're sending with ajax?
On the problem now, get the inputs by:
var fields = [];
$("#dialog-form form fieldset > input").each(function() {
fields.push( $(this)[0].value );
});
...
$.ajax({
url: 'process-form.php',
data:fields
...