Jquery Array - AJAX PHP Autocomplete input - php

I am trying to create an autocomplete input using AJAX / PHP but the array returned from PHP seems to be breaking it.
The idea is to have the flavour name and flavour company name show in a dropdown / expanded div that the user can select.
The Array as it is returned to AJAX success (data):
The Array as JSON:
I want to get the flavour_name value and the flavour_company_name value to put in the box as a string, then on selection grab them both as an array consisting of - flavour_name / flavour_company_name to put into a DB later.
I've tried using JSON.stringify, creating a var obj I have got it to return 1 value but not a list like I want.
All help appreciated, thanks in advance.
My AJAX
$("#flavour-name-input").keyup(function(){
var token = '<?php echo json_encode($token); ?>';
var search = $(this).val();
$.ajax({
type: "POST",
url: "controllers/recipeControl.php",
data: { token: token, search: search },
beforeSend: function(){
$("#search-box").css("background","#FFF no-repeat 165px");
},
success: function(data){
//var obj = JSON.parse(data);
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
//$("#suggesstion-box").html(obj['flavour_name']);
$("#search-box").css("background","#FFF");
}
});
});
My PHP Controller
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
echo json_encode($flavours->getAllFlavoursSearch($search));
}
}
My PHP Function
/**
GET ALL FLAVOURS FOR SEARCH
*/
public function getAllFlavoursSearch($search) {
$query = 'SELECT flavour_name, flavour_company_name FROM flavours WHERE flavour_name LIKE :search ORDER BY flavour_name ASC LIMIT 0,100';
$stmt = $this->queryIt($query);
$stmt = $this->bind(':search', '%'.$search.'%', PDO::PARAM_STR);
return $this->resultset();
}

I think that you have to achieve this in your controller. Now you are returning the json and this is treated like a string. I would create an array in the controller and then you loop it and create the html.
<?php
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
$html = '<ul>';
$content = $flavours->getAllFlavoursSearch($search);
foreach ($content as $con) {
$html .= '<li>'.$con['flavour_name'].'-'.$con['flavour_company'].'</li>';
}
$html .= '</ul>';
echo $html;
}
}
?>
I have not tested it but is something like this, maybe you have to check that the query returns an array.
Regards.

Related

Get multiple filter value parameters

I'm using this SO question to handle my filter search using checkbox.
This is the JS
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
// get all keys.
var keys = Object.keys(data);
var fdata = "";
// iterate over them and create the fdata
keys.forEach(function(key,i){
if (i>0) fdata += '&'; // if its not the first key add &
fdata += key+"="+data[key].join(',');
});
$.ajax({
type: "get",
url: "/ajax/get",
data: {
"_token": "{{ csrf_token() }}",
"fdata": fdata
},
success: function (response) {
$('#d2d-results').html(response);
}
});
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
And now I try to get the value of fdata to PHP.
On PHP I get this value of variable echo $_GET['fdata'];:
discount=Y&brand=BR0006,BR0003
What I want
$discount="Y";
$brand="BR0006,BR0003";
Is it possible to do like that?
To do what you want, you have to do two steps:
parse the query string into an array:
parse_str($_GET['fdata'], $result);
And then, extract the array as variables:
extract($result);
A few things to note:
Using extract is very insecure (and somewhat ugly). The user can put things like (for example) isAdmin=1 in the URL and the will affect your code. Basically, you cannot trust your variables anymore.
I would skip step 2 (the extract thingy), and use $result directly, for example echo $result['discount'].
it sounds like you are mixing post and get, is it something like this that you're after?
via GET:
if(isset($_GET['discount'])) {
$discount = $_GET['discount'];
} else {
$discount = '';
}
if(isset($_GET['brand'])) {
$brand = $_GET['brand'];
} else {
$brand = '';
}
POST method:
if(isset($_POST['discount'])) {
$discount = $_POST['discount'];
} else {
$discount = '';
}
if(isset($_POST['brand'])) {
$brand = $_POST['brand'];
} else {
$brand = '';
}
in one way , you can use explode function in php to separate your item from fdata
you can define some character in your client JS app for example ( , ) and then in explode function in php you must set separator equal comma character
explode function in PHP
explode(separator,string,limit)
in your example separator is comma and string is fdata ( limit optional
)
$fdata = $_GET['fdata'];
$arr_ = explode('&',$fdata);
and if you have some thing like this in fdata string
para1=223&para2=4353&para3=234
then $arr_ variable like this
$arr_ = [para1=223 , para2=4353 , para3=234];
and if you want separate value and key , you can do this again and use loop

Trying to have pass variables on select change action

I am trying to to an on the fly database update of a select field but there can be more than one instance on the page of this field. I had this working for a single on change select field change, but with more than one I am simply passing the values for the first one.
I have in the past dealt with creating unique DOM ids for these on the page, but in this instance with a select field and using the change function I am a bit befuddled. Also most of the situations I found in searching this were not for select fields or dealing with passing variables in this way. I am fully aware this is crude and probably there is a much better way to accomplish this task.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $('.preferenceData').val(), data2: $('#userID').val()}, // this second data element not really needed but is passing var
dataType: 'text',
success: function(html){
if(html) {
$("div#updateDisplay").replaceWith('<div id="updateDisplay">' + html + '</div>');
}
})
});
The form bit:
echo '<div id="userPref"><select class="preferenceData" name="preferenceData'.$row['uid'].'">';
$prefs = enum_select($db,'db_table_name','email_preferences');
foreach($prefs as $pref)
{
echo '<option value="'.$pref['value'].'-'.$data['topicid'].'-'.$row['uid'].'"'.($row['email_updates'] == $pref['value'] ? ' selected' : '').'>'.$pref['display'].'</option>';
}
echo '</select></div>';
The function it's passed to:
function save_preferences()
{
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
$db = new db(0);
$vars = $_POST['data1'];
$data = explode("-", $vars);
// Update Database
$data = $db->Exec('UPDATE km_vendors_users SET email_updates = "'.$data[0].'" WHERE vid = "'.$data[1].'" AND uid = "'.$data[2].'"');
if($data==false)
{
echo $db->log;
//return false;
}
else
echo '<img src="/images/icons/success_check_animated.gif">';
}
}
For your code, you are trying to pass $('.preferenceData').val() for data1, which will be fairly unexpected results (and usually not a value).
Instead you can use $(this).val() which refers the specific element that changed, and its value.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $(this).val()},
...etc...
});
});

Ajax - variables are seen in chrome network tab but they don't seem to pass to the PHP function

I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database

autocomplete value in textbox codeigniter

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";

code igniter php and jquery - how to get data from multiple tables and return it via ajax

I am currently using jquery to get JSON data via ajax from a codeigniter backend / mySQL database, which works fine. The problem I'm having is that, along with the data that gets returned to the jquery function, I also need to run a PHP loop for some data in another table. Currently what I'm doing is waiting for an ajax success from the first function, then making another ajax call to the second function - but I know there is a way to do it with just one function, I'm just not sure how. Here are the two database queries:
function get_selected_member($member = null){
if($member != NULL){
$this->db->where('id', $member); //conditions
}
$query = $this->db->get('members'); //db name
if($query->result()){
$member_result = $query->row();
return $member_result;
}
}
AND
function get_all_groups(){
$query = $this->db->get('groups');
$result = $query->result();
return $result;
}
and then in the javascript function, what I'm doing is saying:
var post_url = "/index.php/control_form/get_selected_member/" + selected_member_id;
$('#chosen_member').empty();
$.ajax({
type: "POST",
url: post_url,
success: function(member)
{
//Add all the member data and...
var post_url2 = "/index.php/control_form/get_all_groups/";
$.ajax({
type: "POST",
url: post_url2,
success: function(group)
{
//Create a dropdown of all the groups
}
});
}
});
In PHP you can combine both in one then echo it to ajax as json variable. So in php you will need a change like following
function get_member_with_group($member = null){
$data['member'] = $this->get_selected_member($member);
$data['group'] = $this->get_all_groups();
echo json_encode($data);
}
Then in javascript something like below..
var post_url = "/index.php/control_form/get_member_with_group/" + selected_member_id;
$('#chosen_member').empty();
$.getJSON(post_url, function(response){
var member = response.member;
//do with member
var group = response.group;
// do with group
});
Hope this will help you :)

Categories