I'm using Bootstrap Typeahead with PHP to display a list from a database using source.php:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = $row['title'] . ',' . $row['id'];
}
// Return the json array
echo json_encode($array);
}
?>
You can see that I add both 'title' and 'id' to the array. All I want it to display in the typeahead is the title but I need the id for the links. Here is the JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + item.replace(/ /g, '-').replace(/\,/g,'/').toLowerCase() + "/";
return item;
}
});
In the line beginning document.location I replace the comma between the two values with a forward slash and it works e.g. /england/123/. But it's the typeahead display that shows it as England,123 rather than just England.
Any help would be greatly appreciated.
OK managed to get a result with the following:
PHP:
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = array('label' => $row['title'], 'id' =>$row['id']);
}
// Return the json array
echo json_encode($array);
}
JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "http://www.stubowker.com/amex/cms/source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.label] = object;
objects.push(object.label);
});
process(objects);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + map[item].label.replace(/ /g, '-').toLowerCase() + "/" + map[item].id +
"/";
return item;
}
});
Related
I tried the pagination feature for searching data using Select2 4.x, but I haven't been able to achieve it. Does anyone know how to do it on codeigniter 4 by including the CSRF token.
If the user performs a search it will display 20 lines, and return to do so with a scroll of 20 lines.
Can anyone help for my problem.
my template HTML:
<div class="form-group">
<select id="selectData" class="form-control" style="width: 100%;"></select>
</div>
Script:
$(document).ready(function() {
var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
var csrfHash = $('.txt_csrfname').val(); // CSRF hash
$('#selectData').select2({
placeholder: '-- Select --',
minimumInputLength: 3,
ajax: {
url: "<?= base_url('servis/getAjax'); ?>",
type: 'POST',
dataType: 'json',
delay: 250,
data: function(params) {
return {
[csrfName]: csrfHash, // CSRF Token
search: params.term
};
},
prosessResults: function(data) {
return {
results: data
};
},
cache: true
},
});
});
Controller:
$search = $this->request->getPost('search');
$result = new MerekModel();
$results = $result->getDataAjax($search);
$selectAjax['token'] = csrf_hash();
$selectAjax = array();
foreach ($results as $row) {
$selectAjax[] = array(
'id' => $row['id_merek'],
'text' => $row['merek'] . ' ' . $row['model'] . ' ' . $row['tipe'],
);
header('Content-Type: application/json');
echo json_encode($selectAjax);
}
Models:
function getDataAjax($search)
{
$data = $this->db->table('tb_merek_tipe')
->select('id_merek, merek, model, tipe')
->orlike('merek', $search)
->orlike('model', $search)
->orlike('tipe', $search)
->get()->getResultArray();
return $data;
}
I have an AJAX call that makes my JSON look this in my JSON file:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
But I would like to have it like this (and this was before I changed my AJAX call with: id: getUrlParameter('id'):
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
The only thing I want to add is the "id": "new", but when I do so (with id: getUrlParameter('id') it gets the id, but it messes up my code.
This is my AJAX call (my JSON starts looking like the first piece of code when I use this)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: $('#my_form').serialize()
},
dataType: 'json',
}).done(function(response) {
});
});
}
How could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my AJAX call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id').
edit: Since someone said it could be my php code.. here is my php code:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>
you can use parse_str($str, $output); it will help you achieve what you need.
Note that parse_str takes two parameters, the first one is the string (get Parameters), second one is the array to return the result on. you can use the below code
parse_str($str, $output);
echo json_encode($output);
The issue is how you process formData parameter. serialize() is building url encoded string, however you want key-value pairs. Try this:
$("#my_form").on("submit", function(event) {
event.preventDefault();
var myData = {id: getUrlParameter('id')};
for (var pair of formData.entries()) {
myData[pair[0]] = pair[1];
}
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: myData,
dataType: 'json',
}).done(function(response) {
window.location = 'index.php';
});
});
}
My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)
I have 3 table as follow;
Experiments_table
id
method
result loq_value min_clb_value max_clb_value
std_deviation
Items_table
List item
id
experiment_id
related_table
sampling_method
reg_value
Samples_table
sampling_method
related_table,
when i choose sampling_method and related_table in samples_table, I want to automatically create this table;
expirement_id || method || result || std_deviation || reg_value
first, get experiment_ids from items table with samples_table.related_table and sampling_method and fill experiment_id and reg_value in this table.
than, get other parameters (method, result and std_deviation) from experiments_table with experiment_id find in first step from items table.
how to do that in codeigniter 3? please give me a suggestion (view, modal_form, model and controller).
this is my model -> sample_items_model.php
function get_item_suggestion($keyword = "") {
$experiments_table = $this->db->dbprefix('experiments');
$sql = "SELECT $experiments_table.title
FROM $experiments_table
WHERE $experiments_table.deleted=0 AND $experiments_table.title LIKE '%$keyword%'
LIMIT 30
";
return $this->db->query($sql)->result();
}
function get_item_info_suggestion($item_name = "") {
$experiments_table = $this->db->dbprefix('experiments');
$sql = "SELECT $experiments_table.*
FROM $experiments_table
WHERE $experiments_table.deleted=0 AND $experiments_table.title LIKE '%$item_name%'
ORDER BY id DESC LIMIT 1
";
$result = $this->db->query($sql);
if ($result->num_rows()) {
return $result->row();
}
}
this is my controller -> samples.php
/* prepare suggestion of sample item */
function get_sample_item_suggestion() {
$key = $_REQUEST["q"];
$suggestion = array();
$items = $this->Sample_items_model->get_item_suggestion($key);
foreach ($items as $item) {
$suggestion[] = array("id" => $item->title, "text" => $item->title);
}
$suggestion[] = array("id" => "+", "text" => "+ " . lang("create_new_item"));
echo json_encode($suggestion);
}
function get_sample_item_info_suggestion() {
$item = $this->Sample_items_model->get_item_info_suggestion($this->input->post("item_name"));
if ($item) {
echo json_encode(array("success" => true, "item_info" => $item));
} else {
echo json_encode(array("success" => false));
}
}
and this is my modal_form script -> item_modal_form.php
function applySelect2OnItemTitle() {
$("#sample_item_title").select2({
showSearchBox: true,
ajax: {
url: "<?php echo get_uri("samples/get_sample_item_suggestion"); ?>",
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
q: term // search term
};
},
results: function (data, page) {
return {results: data};
}
}
}).change(function (e) {
if (e.val === "+") {
//show simple textbox to input the new item
$("#sample_item_title").select2("destroy").val("").focus();
$("#add_new_item_to_library").val(1); //set the flag to add new item in library
} else if (e.val) {
//get existing item info
$("#add_new_item_to_library").val(""); //reset the flag to add new item in library
$.ajax({
url: "<?php echo get_uri("samples/get_sample_item_info_suggestion"); ?>",
data: {item_name: e.val},
cache: false,
type: 'POST',
dataType: "json",
success: function (response) {
//auto fill the method, unit type and rate fields.
if (response && response.success) {
if (!$("#sample_item_method").val()) {
$("#sample_item_method").val(response.item_info.method);
}
if (!$("#sample_conc_type").val()) {
$("#sample_conc_type").val(response.item_info.conc_type);
}
if (!$("#sample_item_result").val()) {
$("#sample_item_result").val(response.item_info.result);
}
if (!$("#sample_item_loq_value").val()) {
$("#sample_item_loq_value").val(response.item_info.loq_value);
}
if (!$("#sample_item_min_clb_value").val()) {
$("#sample_item_min_clb_value").val(response.item_info.min_clb_value);
}
if (!$("#sample_item_max_clb_value").val()) {
$("#sample_item_max_clb_value").val(response.item_info.max_clb_value);
}
if (!$("#sample_item_std_deviation").val()) {
$("#sample_item_std_deviation").val(response.item_info.std_deviation);
}
}
}
});
}
});
}
I have implemented jQuery autocomplete function for my web, which is working fine. But I want the result of the autocomplete to retrieve only the data of a particular person and not the complete database result.
Below is the jQuery for the autocomplete
jQuery(document).ready(function($){
$('.product_desc').autocomplete({source:'functions/products.php?', minLength:2});
products.php
//Path for the databsae
<?php
include '../include/configuration.php';
if ( !isset($_REQUEST['term']) )
exit;
$rs = mysql_query('select id,item_name,fk_vendor_id from item where item_name like "%'. mysql_real_escape_string($_REQUEST['term']).'%" order by item_name asc ', $con);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['item_name'],
'value' => $row['item_name']
);
}
}
else
{
$data[] = array(
'label' => 'not found',
'value' =>''
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
Any solution will be appreciated.
Try this:
$(".product_desc").autocomplete({
source: "functions/products.php",
minLength: 2,
select: function(event,ui){
//do something
}
});
Try this code, Any text field having class .search the auto complete suggestion will works on server side in ajax.php file you need to return array as below:
$response = ['Computer', 'Mouse', 'Keyboard', 'Monitor'];
echo json_encode($response);
Here is sample code for auto suggest.
$(document).on('keyups','.search',function() {
$(this).autocomplete({
source: function( request, response ) {
if (request.term != "") {
$.ajax({
url: "ajax.php",
dataType: "json",
method: "post",
data: {
name: request.term
},
success: function (data) {
if (data != "") {
response($.map(data, function (item) {
var name = item.name;
return {
label: name,
value: name,
data: item
}
}));
}
}
});
}
},
autoFocus: true,
minLength: 2,
select: function( event, ui ) {
var name = ui.item.data;
$(this).val(name);
}
});
});