Autocomplete form with data from json array - php

I have a booking event script that works perfectly fine. I had to make a change to pass the client_id to get added to the appointment. This is where I'm stuck. I had the first & last names working without an array, but noticed that wasn't a good approach so I added an array.
fetch.php
$clientarray = array();
while($row =mysqli_fetch_assoc($result))
{
$clientarray[] = $row;
}
echo json_encode($clientarray);
The above outputs: [{"id":"57","first_name":"JEFFERSON","last_name":"ANDREAS"}];
index.php
$(document).ready(function(e)
{
$("#title").keyup(function()
{
$("#here").show();
var x = $(this).val();
$.ajax(
{
type:'GET',
url:'fetch.php',
data: 'q='+x, /// start search only when first character is entered. q not empty.
success:function(data)
{
$("#here").html(data); /// display results in <div id=here>
}
,
});
});
});
The script above displays the search results in a where I want to click on a result and autocomplete 3 input boxes: client_id, first_name, last_name.

Related

How to send data back in AJAX in response from PHP?

I want to make dynamic select options based on database values.
I am getting id when user select an option, I get this id in ajax and then this id is passed in PHP. In PHP I run SQL query based on provided id. Now I want to send response back in AJAX and then I will append my next select option with the given response.
This is my AJAX, from this code I am passing selected_val in PHP.
`
$(document).ready(function() {
$(".sdpt").change(function(){
let deptid = $(this).val();
console.log(deptid);
$.ajax({
method: "POST",
url: "joins.php",
data: { selected_val: deptid },
success: function(response){
console.log(response);
}
});
});
});
`
In PHP, I am getting data (pro_name) from database and adding it in an array. I want to return this array in ajax and then I will use it there. Now it is return the whole PHP code in response. Please guide where I am doing mistake and what is the alternative.
`
if (isset($_POST['selected_val']) ) {
$value = $_POST['selected_val'];
$myq = new Database();
$result = $myq->sql("SELECT * FROM programs where dept_id=$value");
$arr = array();
while($row = mysqli_fetch_assoc($result)){
$arr[] = $row['pro_name'];
};
echo json_decode("Google");
}
`

jQuery autocomplete is showing empty results

I have this PHP script to get all patient name from my database:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
header("Content-type:application/json");
$cid = $_SESSION['clinic_id'];
$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid ORDER BY patient_id DESC";
$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();
$i = 0;
foreach($getPatientsResult as $result)
{
$res[$i] = $result;
$i++;
}
echo json_encode($res);
?>
And I have a text box where I want to display the patient_name as autocomplete using jquery-ui autocomplete library.
Here is my jQuery script:
$(document).ready(function()
{
$( "#searchTxt" ).autocomplete({
source: "../php/autoComplete.php"
});
})
I can see that if a type a name at the network tab I can see a returned array:
But at the text box I see that the autocomplete are empty like in the following image:
And it is showing 2 white boxes instead of one that of the returned array
This is nice plugin for that kind of results: https://twitter.github.io/typeahead.js/
I think its because the data you have passed, it seems there are multiple columns, you need to specify label and value or it should be simple array (as per your code it should be this kind of data)like
var availableTags = [
"ActionScript",
"COBOL",
"ColdFusion",
];
You can check more about custom field passing
Twitter typeahead.js is the best option to implement this feature.
Please take a look into this to achieve it with PHP, AJAX, and TypeAhead.js
<script>
$(function() {
$("#searchTxt").typeahead({
source: function(query, process) {
var textVal=$("#searchTxt").val();
$.ajax({
url: '/php/autoComplete.php', // Please add full URL here
type: 'POST',
data: 'term=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
link to TypeAhead.js
Let me know if you need any help.
Because you need label and value filed in your json array so your sql would be,
$getPatients = "SELECT *, name as label, id as value FROM patient WHERE clinic_id = :cid ORDER BY patient_id DESC";

PHP/MySQL How to send result back to form?

So I got this form which lets the user enter up to 10 item IDs and then check for the status or apply changes right away. If the user clicks check status the item IDs will be sent to another PHP.
What is the easiest way to send the result back to the form and display it in the red area?
if ($_POST['action'] == 'Check Status/Shelf') {
$itemids = "$itemID1, $itemID2, $itemID3, $itemID4, $itemID5, $itemID6, $itemID7, $itemID8, $itemID9, $itemID10";
while ($row = mysql_fetch_array($all)) {
$hyllplacering = $row['Hyllplacering'] . "";
$all = mysql_query("SELECT Hyllplacering, itemID FROM booking WHERE itemID IN ('$itemids')");
}
}
If you don't want to use Ajax, then save the details into a $_SESSION[] and upon submission the form is posted and then the details can be populated into SESSION and displayed back out to the form upon reloading, but it's a bit of a fiddle for not much return.
And use MySqli or PDO.
For that you have to use ajax
Give id to Apply Changes & Check Status/Self button
<script type="text/javascript">
$(document).ready(function(){
$('#apply').click(function() {
var id1 = $('#id1').val();
var id2 = $('#id2').val();
//same for all your 10 field
var cstring = "id1="+id1+"&id2="+id2 // etc;
$.ajax({
type: "POST",
url: "your file url to do database opration & fetch detail back to here",
data: cstring,
cache: false,
success: function(result) {
$('.resultdata').html(result)
}
});
});
});
</script>
<div class="resultdata"></div>

Store li order in Mysql DB with Jquery sortable

I have a sortable list in my site which saves the order of the list items with an ajax request to a php page.
The problem is when the id of the LI (which is generated by the database) gets above 999 or so it begins to error as the array I'm sending to the PHP page becomes too long.
Is there a better way of doing this?
Currently my Jquery/ ajax is:
$(function() {
$('#sortable').sortable({
update: function(event, ui) {
var order = [];
$('#sortable li').each( function(e) {
order[ $(this).attr('id') ] = $(this).index() + 1;
});
var request = $.ajax({
url: "ajax/save_order.php",
type: "POST",
data: {positions : order},
dataType: "json"
});
}
});
});
My PHP page is:
$positions = $_POST['positions'];
foreach ($positions as $id_section => $order)
{
$sql = sprintf("
UPDATE section_order
SET id_order = %d
WHERE id_section = %d
",
$order,
$id_section
);
$result = mysql_query($sql);
}
I've been trying to work out how to get the data from the sortable into a multidimensional array in jquery, but currently am drawing a blank.
OK I see. Seems a bit unwieldy for a user to manually drag and drop items in a list of over 1000 items. But I don't know how/why you are doing this so will assume it works for your application.
The below solution is actually from this SO question jQuery UI Sortable, then write order into a database
jQuery Sortable has a serialize function that takes care getting the order for you. Use it like below:
$('#sortable').sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'save_order.php'
});
}
});
And in the save_order.php file, just check what the posted data looks like and loop though it, should be able to do something like:
<?php
foreach ($_POST['each_item_whatever...'] as $value) {
// Database stuff
}
?>

Post form input to PHP using AJAX for multiple autocomplete query conditions

I'm using jquery autocomplete on an input form 'city' but i would like the query in my 'autocity.php' file to only suggest cities in the pre selected country i.e. WHERE City LIKE '%$term%'" AND CountryID = '%$country%'. The form action submit uses a separate PHP file (create-business.php) for inserting the form data to the database so the usual $_POST['Countries_CountryId'] wouldn't work in the autocity.php. that's why i'm now using AJAX to post 'country' to autocity.php. Also it would be great to have a way to echo/alert/print_r from the the autocity.php file so i can confirm that the $_POST['$country'] from the ajax post reaches the autocity.php file.
I have two input boxes in the form
<pre>`
<form id="input" action="php/create-business.php" method="post">
<select name="Countries_CountryId" id="country">
<input type="text" id="city" name="City">`
</pre>
Here is the script from the form
<script>
$(function () {
var country = $("#country").val();
$.ajax({
type:"POST", url:"autocomplete/autocity.php", data:"country",
beforeSend:function () {
// alert(country);
}, complete:function () { // is there any need for this?
}, success:function (html) { // is there any need for this too?
}
});
$("#city").autocomplete(
{
source:'autocomplete/autocity.php'
})
});
</script>
And here is autocity.php
`
//database connection works fine and autocomplete
//suggestion works without the AND CountryID = '%$country%' part.
$country = "";
if (isset($_POST['country'])) {
$country = trim($_POST['country']);}
echo "window.alert($country);"; //This did nothing no alert
$term = $_REQUEST['term'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>`
So the question is basically:
1 - how can i use a text input from a form using AJAX in a .php file that queries a MySQL db that is not the submit form action .php file
2 - how can i alert the post variable from the PHP file when ajax is used to show that the php file recieves my ajax post. In my brief experience echo and print_r only work on form submit when the web page changes showing the result of my form submit ont the form action.
3- how is my syntax?
Thank you very much in advance for helping this novice out :D
Ok here is my update on things i've tried. I think i'm close. i'm using Jquery UI -
//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js
here is the script method 1:
$(document).ready(function () {
var country = $('#country').value();
alert(country + " complete");
$("#city").autocomplete(
{
source:'autocomplete/autocity.php?country='+country,
minLength:1
});
});
here is the script method 2:
$(document).ready(function () {
$('#city').autocomplete({
// source: function() { return "GetState.php?country=" + $('#Country').val();},
source:function (request, response) {
$.ajax({
url:"autocomplete/autocity.php",
//dataType:"json",
data:{
term:request.term,
country:$('#country').val()
},
success:function (data) {
response(data);
}
});
},
minLength:2
});
});
I like method 2 more since it will allow me to add more than one parameter.
Finally here is my latest autocity.php code
<?php
$term = $_REQUEST['term'];
$country = $_REQUEST['country'];
$req = "SELECT City
FROM cities
WHERE City LIKE '%$term%' AND CountryID = '%$country%' ";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = array('label' => $row['City']);
}
echo json_encode($results);
?>
I'm still totally stuck though. can anybody see the problem with the code? Ive looked everywhere online for the right syntax. Thanks again
For the first problem, your approach is essentially correct. You can bind to the blur event for a particular field and use your function to get that field's value and submit to the php script much in the manner that you are doing so. $.blur() is what you're looking for.
For the second problem the error_log function will write stuff to php's error log. IF you use print_r to dump variables to this log, make sure to set print_r's second argument to true to output the result as the return value.

Categories