Jquery autocomplete source php function - javascript

I would like to attach a php function as a source for my autocomplete functionality, The problem is I am not getting any results back.
PHP function
function getUser(){
$users = R::findAll('users');
foreach ($users as $user) {
echo '<option value="'. $user->name .'" ';
if($_POST['filterUser'] == $user->name){
echo "selected";
}
echo $user->name . '</option>';
}
}
Auto completion
$( "#enterUser" ).autocomplete({
source:'test.php?str=' + $('filterUser').val(),
messages:
{
noResults: '',
results: function() {}
},
select: function( event, ui )
{
var selectedObj = ui.item;
},
autoFocus: true
});
});

In the autocomplete declaration, your source property must be the name of your php file (with some parameters).
Example:
source: 'your_php_file.php?str=' + $('filterUser').val()
In the PHP you must call the function you want to reach, and be sure that it echoes the appropriate JSON string.

Related

Convert PHP variable to JQuery

Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.
Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>

How to make item draggable after ajax call filtering

So I got a list of names which are dragable. I have a list of checkboxes with help them I can filter that names. After checking checkbox I make an ajax call. Here is how my list is look like(it is an accordion):
<div id="myAccordion">
<?php
echo "<h3>Names</h3>";
echo '<ul class="source">';
echo '<div id="getData"></div>';
echo '<div id="hideData">';
$sql = "SELECT * FROM user ORDER BY `username` ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$name = $row["username"];
$user_type = $row["user_type"];
echo"<li class='item'><span class='closer'>x</span>".$name."</li>";
}
}
else
{
echo "0 results";
}
echo '</div>';
echo '</ul>';
?>
</div>
So after calling ajax i call filter.php and print that:
<?php
require_once('inc/database_connection.php');
include 'model/model.project.php';
if($_POST['user_type'])
{
//unserialize to jquery serialize variable value
$type=array();
parse_str($_POST['user_type'],$type); //changing string into array
//split 1st array elements
foreach($type as $ids)
{
$ids;
}
$types=implode("','",$ids); //change into comma separated value to sub array
echo "<br>";
$result = getUserTypeChecked($types);
?>
<div id="getData">
<?php
while($rows=mysqli_fetch_array($result))
{
//echo $rows['username']."<br>";
$name = $rows["username"];
echo '<ul id="source">';
echo"<li class='item'><span class='closer'>x</span>".$name."<div class='green'></div></li>";
echo '</ul>';
}
?>
</div>
<?php
}
?>
So the problem is name stops being draggable after ajax call. How can I achieve this?
EDIT
Ok, so here is my js for accordion:
<script>
$("#myAccordion").accordion({heightStyle:"content", collapsible:true});
$("#myAccordion li ").draggable({
appendTo: "body",
helper: "clone",
refreshPositions: true,
start: function (event, ui) {
sourceElement = $(this);
},
});
</script>
And ajax call:
<script>
$(document).ready(function(){
//$('#getData').hide();
$('.ids').on('change',function(){ //on checkboxes check
//sending checkbox value into serialize form
var hi=$('.ids:checked').serialize();
if(hi){
$.ajax({
type: "POST",
cache: false,
url: "filter.php",
data:{user_type:hi},
success: function(response){
//$('#getData').show();
document.getElementById('getData').style.display = "block";
document.getElementById("getData").innerHTML = response;
$('#hideData').hide();
}
});
}
else
{
document.getElementById('getData').style.display = "none";
$('#hideData').show();
}
});
});
</script>
JS works with loaded DOM on page. This means when ever you call sort function, HTML elements must be present on the page.
Let's try to understand what's going on here?
All html elements loaded first.
JS trigger and all dragging functionality to loaded DOM.
Ajax call to fetch new data and replace old DOMs.
Now drag functionality stops working.
why? because JS drag function run on old DOM and currently it has been removed.
need to call the drag function again on new loaded DOM.
NOTE: make sure elements or HTML must be loaded before calling JS drag function.
reinitialize you plugins after appending the new html in the success function:
document.getElementById("getData").innerHTML = response;
$('#hideData').hide();
$("#myAccordion").accordion({heightStyle:"content", collapsible:true});
$("#myAccordion li ").draggable({
appendTo: "body",
helper: "clone",
refreshPositions: true,
start: function (event, ui) {
sourceElement = $(this);
},
});

php/jQuery get primary key for selected value

I am trying to get key(primary key) for selected value in my form, so I can add key into joining table. I change my form to autocomplete from drop down list. but do not how to do map with jquery.
This is my php for autocomplete
<?php
if (isset($_POST['type']) && $_POST['type'] == 'faculty_id') {
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
$nameID = $_POST['nameID'];
$query = "SELECT FirstName, LastName, FacultyId FROM Test.Faculty where UPPER(FirstName) LIKE '" . strtoupper($name) . "%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['FirstName'] . ' ' . $row['LastName'];
$nameID = $row['FacultyId'];
array_push($data, $name);
}
mysqli_close($con);
echo json_encode($data);
exit;
}
?>
this is form and jQuery page
<form action="Form.php" method="post">
<input type='text' id="faculty_id" placeholder="Instructor" name="faculty_id" value='' />
<input type="submit" value="submit" name="submit" />
</form>
<script type="text/javascript">
$('#faculty_id').autocomplete({
source: function (request, response) {
$.ajax({
url: 'Form.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
nameID: request.term,
type: 'faculty_id'
},
success: function (data) {
response($.map(data, function (item) {
console.log(item);
//var code = item.split("|");
return {
label: item,
value: item,
data: item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
});
</script>
and php insert query
<?php
if (isset($_POST)) {
$faculty_id = $_POST['faculty_id'];
try {
$stat = $db->prepare("Insert into ATCTest.Schedule
(Faculty )
VALUE (':faculty_id' )");
$stat->bindParam(":faculty_id", $faculty_id);
if ($stat->execute()) {
echo "<h5>Faculty-js: " . $faculty_id . "</h5>";
} else {
echo "Problem!!!";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
Stay consistent. Choose either PDO or MySQLi. Not both. Your autocomplete script uses MySQLi, but then in your insert script, you use PDO. Pick one and stick with it.
I'll use PDO as I find it much easier to use than MySQLi.
Use the appropriate request methods. If you are getting something, use GET not POST. If you are adding or updating, use POST.
Let's rewrite your autocomplete script to use PDO:
if (isset($_GET['type']) && $_GET['type'] == 'faculty_id') {
// this will hold your response that gets sent back
$data = null;
$name = trim($_GET['name']);
try {
// because you are passed untrusted data, use prepared statement
$sth = $db->prepare("
SELECT FirstName, LastName, FacultyId
FROM Test.Faculty
WHERE UPPER(FirstName) LIKE UPPER(?)
");
$sth->execute(array($name . '%'));
// set the results (array of objects) as your JSON response
$data['faculties'] = $sth->fetchAll(PDO::FETCH_OBJ);
} catch(PDOException $e){
echo $e->getMessage();
}
// send the results i.e. response
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
I've never used the autocomplete plugin before but I'll take a crack at it based on other answers I've seen.
$('#faculty_id').autocomplete({
source: function (request, response) {
// short syntax for .ajax() using GET method that expects a JSON response
$.getJSON('Form.php', { type: 'faculty_id', name: request.term }, function (data) {
// data.faculties (your AJAX script's response) should now be an array of objects
console.log(data.faculties);
response($.map(data.faculties, function (faculty) {
console.log(faculty);
return {
label: faculty.FirstName + ' ' + faculty.LastName,
value: faculty.FacultyId
}
}));
});
},
autoFocus: true,
minLength: 1,
});
Lastly, when you insert
// check if form was POSTed
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$faculty_id = $_POST['faculty_id'];
try {
// VALUES not VALUE
// don't wrap your placeholders with quotes in your prepared statement
// simplified
$sth = $db->prepare("INSERT INTO ATCTest.Schedule(Faculty) VALUES(?)");
// simplified way to bind parameters
$sth->execute(array($faculty_id));
// use rowCount() not execute() to determine if the operation was successful or not
if ($sth->rowCount()){
echo "<h5>Faculty-js: $faculty_id</h5>";
} else {
echo "Problem!!!";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}

<input> calling a PHP function using AJAX

I am trying to call a PHP function using AJAX to check if the pressed button is the right button.
But I can't seem to figure it out.
I am using this as <input> code :
<?php
$i=0;
while ($i<4){
?>
<input style="background-color: <?php echo $buttonColors[$i]; ?>" onclick="echoHello(<?php echo $i?>)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php $i=$i+1; } ?>
and I'm trying to call a PHP function when the button is clicked. I tried this :
<script>
function echoHello()
{
alert("<?php hello(); ?>");
}
</script>
<?php
function hello() {
echo "Hello World";
}
?>
This worked so I tried to change this to :
<script>
function echoHello(num)
{
alert("<?php hello(num); ?>");
}
</script>
<?php
function hello($num) {
if($num == 1) {
echo "Correct button!!!";
} else {
echo "WRONG BUTTON";
}
?>
But this didn't seem to work. What am I doing wrong?
I think you have quite some thing mixed up here.
I would suggest just writing out the buttons, and pass the buttons value to the javascript:
<?php
$i=0;
while ($i<4){
?>
<input onclick="echoHello(this.value)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php
$i=$i+1;
} ?>
and then in your javascript (after adding all the jQuery goodness):
function echoHello(btnValue) {
$.ajax({
type: "POST",
url: "formhandler.php",
data: { buttonValue: btnValue }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
The javascript above will send the button value to your 'formhandler.php' page, using AJAX.
In the 'formhandler.php', you could then check what the value of $_POST["buttonValue"] is.
Using your setup, together with jQuery, PHP and JSON, it could be something like this:
function echoHello(btnValue) {
$.getJSON('page.php', {
choice: btnValue
})
.done(function(data) {
// based on $_GET["choice"], your PHP could render some JSON like:
// {"background":"image.jpg","fields":["newValue1", "newValue2", "newValue3"]}
// clear the current html
$("#form").html('');
// load a new background
$('body').css({'background-image':data.background})
// set up the new fields:
$.each(data.fields, function( i, item ) {
$("#form").append('<input type="text" value="' + item + '"/>');
});
});
}
This is just a sample, to give you an idea! It's untested also ;)

ajax not able to pass variable to php

I have a slider which uses javascript. I am trying to update the display of my web page based on the slider values. I tried to use ajax function to send the data to another PHP page to update the display. But I am not getting anything in my page. Here is my code so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" onclick="loadXMLDoc()">Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
</script>
<script>
function loadXMLDoc()
{
alert "Am I coming here";
$.ajax({
type: "POST",
url: 'update.php',
data: { value : data.value },
success: function(data)
{
alert("success!");
}
});
}
</script>
I read in another post that javascript variables are available across functions and so I am trying to use the variable data.value inside my another javascript function loadXMLDoc(). But I do not see the value getting displayed in my update.php page. My update.php file is as below.
<?php
if(isset($_POST['value']))
{
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
}
?>
Can someone please help me on this?
In the loadXMLDoc function I don't see data defined anywhere. I think that could be one of the problems. Also, when you're doing jquery ajax requests be sure to have a fail callback. The fail callback will tell you if the request fails which can be very informative.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
To make the data variable accessible in the XMLLoadDoc function you could try putting it in the global scope (kind of a 'no-no', but its OK for a use case like this). So, at the top, declare var masterData, then when you have data in the .bind callback set masterData = data; and then in loadXMLDoc refer to masterData

Categories