I am using an input box the select items from a database with ajax autocomplete. I want to remove the selected item so it can not be selected again. My code is as follows:
HTML
<input id='inpSelectRecipient' type='text' class='form-control' placeholder='Type recipient name here' autocomplete='off'></input>
Javascript
$("#inpSelectRecipient").autocomplete({
// Min Lenght Function
minLength: 2,
// Source Function
source: function (request, response) {
// Ajax Call
$.ajax({
url: '../getautocomplete.php',
data: request,
dataType: 'json',
type: 'GET',
success: function (data) {
// Ajax Data
response(data);
// Check if Results Exists
if (data.length === 0) {
// Alert Message/Class
varModalMessage = 'No Results Found'; // Message Text
varAlertClass = '4'; // Error Class
// Alert Message
modalAlert(varModalMessage, varAlertClass);
}
}
});
},
// Search Function
search: function(event, ui) {
},
// Select Function
select: function(event, ui) {
// Variable
var removedRecipient;
// Create Message Recipients
createMessageRecipients(ui.item.id);
// Clear Input
$('#inpSelectRecipient').val('');
// Test
//console.log('Receipients Array: ' + recipientsArray + ' Selected Array: ' + removedRecipient);
},
// Response Function
response: function( event, ui ) {
}
});
PHP
<?php
// Obtain Term
$term=$_GET["q"];
// Query
$query=mysql_query("SELECT * FROM tblUsers WHERE `userFirstName` LIKE '%" . $term . "%' OR `userLastName` LIKE '%" . $term . "%' ORDER BY userFirstName ");
// Json Array
$json=array();
// Array Function
while($contact=mysql_fetch_array($query)){
// JSON Array
$json[]=array(
'id'=>$contact["userID"],
'value'=>$contact["userFirstName"]." ".$contact["userLastName"],
'label'=>$contact["userFirstName"]." ".$contact["userLastName"]
);
}
// Obtain Json
$functionReturn = json_encode($json);
// Echo Function Return
echo json_encode($json);
?>
I have seen other examples however none that are using ajax to obtain the autocomplete array. Thanks so much for any help :)
*you need to send selected items id to server so that in sql query it can exclude that result.
var selectedElm = [];
$("#inpSelectRecipient").autocomplete({
......
});
select: function(event, ui) {
.....
selectedElm.push(ui.item.id);
....
}
source: function (request, response) {
request.exclude = selectedElm ;
$.ajax({
....
data: request,
.....
}
and on server side just use "where not in" query.*
Related
I am a beginner in Ajax. I want to fetch data row from Subject Table consist of only one column Subject as varchar(100), defined in MySQL DB. Following is my php code.
Data.php
<?php
$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: " .mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo $row["SUBJECT"];
//I Want This Value to Be received in my Jquery Page
//So that i can take certain action based on each Subject.
//For example creating a select box child elements,options.
}
?>
Jquery.js
$(document).ready(function()
{
var response='';
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET'
success: function(text)
{
response=text;
}
});
});
$("body").append("<select> /*Get values here as options*/ </select>");
});
But The Desired action is getting values row by row like:-
1st row value comes-> take certain action in jquery;
2nd row value comes-> take sertain action..;
.
.
so on.
Data.php
<?php
$con=#mysqli_connect("","root","root","DBTemp");
# Instead of that use header 500 to let javascript side know there is a real error.
if (mysqli_connect_errno())
{
echo "Could not connect to database : ". mysqli_connect_error();
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit();
}
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
if (mysqli_error($con))
{
echo "Query failed : ".mysqli_error($con);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit();
}
$options = array();
# populate options arrey with using table's id field as key
# and subject field as value.
while($row = mysqli_fetch_assoc($result))
{
$options[$row['id']] = $row['subject'];
}
# return json encoded array to parse from javascript.
echo json_encode($options);
Data.php will output :
{"1":"Subject ID 1","2":"Subject ID 3"}
Jquery.js
$(document).ready(function()
{
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET',
dataType: 'json', // Let jQuery know returned data is json.
success: function(result)
{
$.each(result, function(id, subject) {
# Loop through results and add an option to select box.
$("#ajaxpopulate").append( new Option(subject,id) )
});
}
});
});
});
Page.html , inside the body. This select box will populated from ajax request.
<select id="ajaxpopulate"></select>
I would have the php function return a json response. You could do this in two ways either construct the JSON manually through your while statement server side or use the json_encode PHP function and echo that server side. That way when the data is returned client side in your ajax response you can parse the JSON data to a JSON object JSON.parse(json); and then control row by row the data in a structured way.
Hope this helps!
1) You need to use data structure like an array and pass it as a json response to your ajax call.
2) You need to iterate through your json array and that is where you can process each row separately and create nested select options.
UPDATE
$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: "
.mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
$jsonResult = [];
while($row = mysqli_fetch_assoc($result))
{
$jsonResult[] = $row["SUBJECT"];
}
echo json_encode($jsonResult);
An jquery should look like this
$(document).ready(function()
{
var response='';
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET'
dataType : 'JSON',
success: function(data)
{
//Alert should return an array of your subjects
//If it does then you need to iterate through this array and create options manually.
alert(data);
}
});
});
$("body").append("<select> /*Get values here as options*/ </select>");
});
In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_tags').on("change", function(e) {
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag " + e.added.id + "?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.
I am send a ajax request to php file where i will update the database and and i will select a value according to my condition. But how to return that $variable in ajax callback and show it in input text box.
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
}
});
my PHP file is
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['id']==2) //taking
{
$book_id = $_GET['bookid'];
$startdate = $_GET['startdate'];
$update_validity = "UPDATE booking SET valid = '2',start_date_timestamp = '$startdate' where book_id = '$book_id'";
$query = mysql_query($update_validity);
if($query==TRUE)
{
$get_select_query = "select start_date_timestamp from booking where book_id = '$book_id'";
$get_query = mysql_query($get_select_query);
$row = mysql_fetch_assoc(get_query);
$startdate_return = $row['start_date_timestamp'];
echo $startdate_return;
}
}
?>
You should use json format like:
in your php file
$arrFromDb = array(
'id' => 1,
'bookName' => 'Da Vinci Code'
)
echo json_encode( $arrFromDb ); exit();
in you script
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
var book = $.parseJSON(data) // now book is a javascript object
var bookName = book.bookName;
}
});
I hope this will help you
Create an element in your page like <span> and give it a unique ID like <span id="testspan"></span>. This is where the text gets displayed. Then in your JS;
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
$( "#testspan" ).html(result);
}
});
Just echo in your php file, the output (instead of being shown by the browser as a default PHP page) will be usable in the JS as the result of the ajax call (data)
Try to use val(),
HTML
<input type="text" id="inputId" />
Js
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
$( "#inputId" ).val(data);
}
});
PHP CODE
<?php
echo $bookid= isset($_REQUEST['bookid']) ? $_REQUEST['bookid'] : "No bookid";
// you can use $_GET for get method and $_POST for post method of ajax call
return
?>
In updatenewuser.php
//after all operations
echo $variable_to_pass;
Then in the ajax request :
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
alert(result);//result will be the value of variable returned.
$("#input_box").val(result); //jquery
document.getElementById("input_box").value = result; // Javascript way
}
});
HTML being :
<input type="text" id="input_box" value=""/>
Cheers
I am using the select 2 plugin to search for users. Everything is up an running an my jsons end up with: [{"id":"1","text":"Alex Fagard (afagard) ID: 1"}] .etc.
I am using the following code to build the select 2 interface:
$(document).ready(function(){
$('#username-search').select2({
minimumInputLength: 2,
select: function(event, ui) {
AutoCompleteSelectHandler(event, ui)
},
ajax: {
url: "classes/search.class.php?sType=users",
dataType: 'json',
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
});
However I am stuck on how to make it so that when the admin selects a user (aka clicks on their dropdown area) the page redirects to userview.php?id=1 where 1 is the id from the JSON array.
Search function if anyone is interested:
public function searchUsers($term = '') {
if (isset($term)) {
$term = parent::secure($term);
$params = array( ':searchQ' => $term . '%' );
$sql = "SELECT distinct username as suggest, user_id, name
FROM login_users
WHERE username LIKE :searchQ
OR name LIKE :searchQ
OR user_id LIKE :searchQ
ORDER BY username
LIMIT 0, 5";
$stmt = parent::query($sql, $params);
if ( $stmt->rowCount() > 0 ) {
while($suggest = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'id' => $suggest['user_id'],
'text' => $suggest['name'] . ' (' . $suggest['suggest'] . ')' . ' ID: ' . $suggest['user_id'],
);
}
} else {
$data[] = array('id'=>'0', 'text'=>'No results found!');
}
echo json_encode($data);
flush();
}
}
$searchParam = new Search();
if (isset($_GET['term'])) {
// we secure the term before running the search and querying the database
$term = $_GET['term'];
switch (isset($_GET['sType']) ? $_GET['sType'] : NULL) {
case 'users':
$searchParam->searchUsers($term);
break;
case 'levels':
$searchParam->searchLevels($term);
break;
}
}
Version 4.0 +
Events are now in format: select2:selecting (instead of select2-selecting)
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
Came across the same question a year after posting this and googled something and ended up here forgetting I ever posted it in the first place.
Well found a solution:
<script>
$(document).ready(function () {
$("#search").select2({
ajax: {
url: "users.php",
dataType: 'json',
data: function (term) {
return {
term: term,
};
},
results: function (data) {
return {results: data};
}
}
});
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
});
</script>
Event name is select2:selecting
I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";