I am using select2 and ajax to query my database for terms under a certain taxonomy, but when I search the search boxes just hangs on "searching" without retrieving any results.
This is my html
<select multiple="" name="regions1[]" id="regions1" class="job-manager-multiselect select2-hidden-accessible" required="" tabindex="-1" aria-hidden="true"></select>
My jquery:
<script>
jQuery(function($) {
$(document).ready(function() {
$( "#regions1" ).select2({
ajax: {
url: "/ajax/connect.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
minimumInputLength: 2
});
});
});
</script>
and my php code to query the database, I am looking to get all the term names under the taxonomy "job_listing_region"
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// strip tags may not be the best method for your project to apply extra
layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
// Do Prepared Query
$query = $conn->prepare("
SELECT * FROM (
SELECT wp_terms.name
FROM wp_terms
JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE taxonomy = 'job_listing_region'
AND count = 0
) as T"
);
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['name'], 'text' => $value['name']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
And as you can see, I am retrieving my data, but the search just hangs.
Thanks in advance.
Found the solution here How to load JSON data to use it with select2 plugin
Needed to recreate my results like this
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
}
So you need to change processResults to success and put the following into that function:
for(i=0;1<data.length;++i){
var currentObject = data[i];
var id = currentObject.id;
var text = currentObject.text;
//do what you need to here (Put things in a div, etc)
}
And from there, you can do something like this:
document.getElementById("search").innerHTML = document.getElementById("search").innerHTML+"<br />"+id+text;
Related
I am using mysql database to retrieve data and show it into Select2. Right now, the search data is being showed in the preview of the get call. But not in the options of the Select2. Even though I am receiving the correct response, i can't get it added into the options of the select box
Below is my Javascript code
$("#selecter").select2({
ajax: {
url: "index.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2
});
and here is the php code
if(isset($_GET['q'])){
$urlparam_name = $_GET['q'] ."%";
$link = mysqli_connect('localhost', 'root', '', 'customerdatabase_13030') or die("Error " .mysqli_error($link));
$sql = "
SELECT `customer_13030`.`custID`, `customer_13030`.`name`
FROM `customer_13030`
WHERE `customer_13030`.`custID` like '$urlparam_name' OR `customer_13030`.`name` like '$urlparam_name'
GROUP BY `customer_13030`.`custID` ASC
";
$result = mysqli_query($link, $sql) or die("Error " .mysqli_error($link));
$rows = array();
while ($row = mysqli_fetch_assoc($result))
{
$rows[] =array(
'id' => $row['custID'],
'name' => $row['name']
);
}
echo json_encode($rows);
}
I have a form where the user has to enter their reservation id and last name. If these two values match in the database then I need to return the corresponding values from the database.
So far, everything seems to work. The correct values are being retrieved from the database. I would like to show the values inside paragraphs. I am just not sure how to archive that. ValidateReservation gets called once the button is clicked.
Here is my code:
<p id='guest_full_name'></p>
<p id='unit_number'></p>
<p id='floor'></p>
<script>
function validateReservation(){
var reservation_id = document.getElementById("reservation_id").value;
var guest_last_name = document.getElementById("guest_last_name").value;
$.ajax({
type: 'POST',
url: 'test06.php',
// dataType: 'json',
data: {
'reservation_id': reservation_id,
'guest_last_name' : guest_last_name
},
success: function(json) {
console.log(json);
$('#reservation_id').val(json.reservation_id);
$('#guest_last_name').val(json.guest_last_name);
$('#guest_full_name').val(json.guest_full_name);
$('#unit_number').val(json.unit_number);
$('#floor').val(json.floor);
$('#key_sa').val(json.key_sa);
},
error: function(err) {
console.log(err);
} }); }
test06.php
<?php
$conn = mysqli_connect("","","","");
$reservation_id=$_POST['reservation_id'];
$guest_last_name=$_POST['guest_last_name'];
$stmt = $conn->prepare("SELECT reservation_id, guest_last_name, guest_full_name, unit_number, floor, key_sa FROM reservations2 INNER JOIN guest ON (reservations2.reservation_id=guest.reservation_idg) INNER JOIN unit USING (unit_id) WHERE reservation_id=? AND guest_last_name=?");
$stmt->bind_param("ss", $reservation_id, $guest_last_name);
$stmt->execute();
$stmt->bind_result($reservation_id, $guest_last_name, $guest_full_name, $unit_number, $floor, $key_sa);
if ($stmt->errno) {
die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
echo json_encode(array("reservation_id" => $reservation_id,
"guest_last_name" => $guest_last_name,
"guest_full_name" => $guest_full_name,
"unit_number" => $unit_number,
"floor" => $floor,
"key_sa" => $key_sa));
} else {
echo "No matching rows returned.";
}
$stmt->close();
?>
Please use .html() instead of .val()
$('#guest_full_name').html(json.guest_full_name);
$('#unit_number').html(json.unit_number);
$('#floor').html(json.floor);
You can also use the below code without jQuery
document.getElementById('guest_full_name').innerHTML = json.guest_full_name;
document.getElementById('unit_number').innerHTML = json.unit_number;
document.getElementById('floor').innerHTML = json.floor;
UPDATE:
Convert your response into json object in success function,
var json = JSON.parse(json);
I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#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: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#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({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: 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: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#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({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
I am trying to use a PHP page hosted on a MySQL server that generates a JSON feed that I want to use as in the "eventSources" array of Fullcalendar in my Ionic application. The calendar is rendering, but it isn't displaying the dates in the feed. I have been working at this for a couple of days and none of the documents on the Fullcalendar site aren't working.
Here's the JSON String:
{"success":1,"message":"Details Available!","events":[
{"ID":"1","title":"Example Class","start":"2014-08-29 09:00:00","end":"2014-08-29 17:00:00","all_day":"0"},
{"ID":"2","title":"Example Class 2","start":"2014-08-13 00:00:00","end":"2014-08-13 00:00:00","all_day":"0"},
{"ID":"3","title":"Example Event with Time","start":"2014-08-13 12:00:00","end":"2014-08-13 13:00:00","all_day":"0"},
{"ID":"11","title":"Testing 123","start":"2014-08-13 00:00:00","end":"2014-08-13 23:59:00","all_day":"1"}]}
Here is the PHP Page generating the JSON above:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
header("Content-Type:application/json");
header("Access-Control-Allow-Origin: *");
$user="user";
$pass="password";
$table="database";
$db=new PDO("mysql:host=localhost;dbname=$table", $user,$pass);
//initial query
$query = "Select * FROM table";
//execute query
try {
$stmt = $db->query($query);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Details Available!";
$response["events"] = array();
foreach ($rows as $row) {
$post = array();
$post["ID"] = $row["ID"];
$post["title"] = $row["title"];
$post["start"] = $row["start"];
$post["end"] = $row["end"];
$post["all_day"] = $row["all_day"];
//update our repsonse JSON data
array_push($response["events"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Events Available!";
die(json_encode($response));
}
?>
Here is the the controller for the calendar:
App.controller('LogHomeCtrl', function($scope, $log, $state)
{
$scope.TimeTabl = function()
{
$state.go('timetable');
}
});
App.controller('calCtrl', function ($scope, $log, $state)
{
$scope.eventSources = [
{
events: {
url: 'url/calendarConnect.php',
type: 'POST',
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
}
];
});
I have tried using different methods of calling the PHP page, but none of it is working. If someone could point out where I am going wrong that would be great.
Exists few ways how you can set events for calendar:
1.as array:
events: [
{
title: 'Example Class',
start: '2014-08-29 09:00:00',
end: '2014-08-29 17:00:00'
},
{
title: 'Example Class 2',
start: '2014-08-13 00:00:00',
end: '2014-08-13 00:00:00'
}
]
2.as json object:
events: 'url/calendarConnect.php' //must to return json similar to previous example
3.as function:
events: function(start, end, timezone, callback) {
$.ajax({
url: 'url/calendarConnect.php',
dataType: 'json',
success: function(response) {
//get your events from response.events
console.log(response);
}
});
}
4.as custom function:
$.ajax({
url: 'url/calendarConnect.php',
dataType: 'json',
success: function(response) {
//just example
$('.calendar').fullCalendar({
events: response.events
});
}
});
In your case 3-rd way is more appropriate. For more details, please, see official Fullcalendar documentation about events.
Try changing this (add [] after ["events"]):
array_push($response["events"][], $post);