Prevent already selected option Jquery autocomplete with MYSQL - javascript

I am using Jquery Autocomplete to fetch a list of tags from a mysql table. When the user picks one tag from the list, it gets saved on the page. I am trying to prevent the already saved tag from being displayed again.
Here is my code:
HTML
<input type="text" id="tag">
<input type="text" id="tags" style="display:none;">
Jquery
$('#tag').autocomplete({
source : function(request, response) {
$.ajax({
url : 'tags.php',
dataType : "json",
method : 'post',
data : {
searchQuery : request.term,
selectedTags: $('#tags').val() //sends already selected terms
},
success : function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label : code[0],
value : code[0],
data : item
}
}));
},
error: function(jqxhr, status, error)
{
alert(error);
}
});
},
autoFocus : true,
minLength : 1,
select : function(event, ui) {
var names = ui.item.data.split("|");
tag_ids = [];
tag_names = [];
tags = $('#tags').val();
if(tags != '')tag_names = tags.split(',');
tag_ids.push(names[1]);
tag_names.push("'" + names[0] + "'");
$('#tags').show();
$('#tags').val( tag_names.join( "," ) );
$('#tag').val('');
}
PHP
$searchQuery = $_POST['searchQuery'];
$selectedTags = $_POST['selectedTags'];
if(!empty($selectedTags))
{ $query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN ?");
$query->execute(array($searchQuery . "%", $selectedTags));
}
else
{
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ?");
$query->execute(array($searchQuery . "%"));
}
When I select the first suggestion, it gets saved in #tags but then no other suggestion is displayed. If there is any other suggestion to achieving this, that'd be great.

I figured it out. I was trying to pass an array to the prepared statement.
PDO doesn't work that way.
To solve this, I declared the number of parameters first and then put them in the prepared statement while using foreach to bindvalue to each parameter.
Here is the final solution:
//exploding the string to an array first
$selectedTags = explode(',', $selectedTags);
//creating another array with parameters equal to the size of the selectedTags
$bindValues = implode(',', array_fill(0, count($selectedTags), '?'));
//putting the parametes
$query = $db->prepare("SELECT * FROM tags WHERE name LIKE ? AND name NOT IN (" . $bindValues .")");
//binding values
$query->bindValue(1, $searchQuery . '%');
//Now, using foreach to bind selected tags values
foreach($selectedTags as $k => $selectedTag)
{
//using k+2 as index because index starts at 0 and first parameter is the search query
$query->bindValue($k+2, $selectedTag);
}
$query->execute();
And this solved the problem. I hope it helps others too.

Related

Check if Value exists inside of an array using PHP (in_array)

I have the insertion of data using php, js, ajax. I'm getting the data from form and will send it to my controller using ajax as post method. My Controller will get all the data requested from my ajax and this data my php code will process to insert it on the database
So this is my way of getting the multiple value of checkboxes in javascript before sending it using ajax.
Here's my sample checkboxes
Html
<input id="chk_RegularShiftTable_rest_mon" class = "chk_RegularShiftTable_rest" type="checkbox" name="chk_RegularShiftTable_rest[]" value="1" disabled>
<input id="chk_RegularShiftTable_rest_mon" class = "chk_RegularShiftTable_rest" type="checkbox" name="chk_RegularShiftTable_rest[]" value="2" disabled>
This how I manage the 2 checkboxes using for
JavaScript
var chkRest = document.getElementsByName('chk_RegularShiftTable_rest[]');
var dataRest = [];
for (var x = 0; x < chkRest.length; x++){
if (chkRest[x].checked){
dataRest.push(chkRest[x].value);
}
}
and this is how I send my data using Ajax and this will go to the controller.
AJAX
$.ajax({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "{{ route('save') }}",
method: "POST",
dataType: "json",
data: {
dataRest:dataRest
},
success:function(data)
{
if(data.error.length > 0){
alert(data.error[0]);
}
if(data.success.length > 0){
alert(data.success[0]);
refresh_Table();
}
},
error: function(xhr, ajaxOptions, thrownError){
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
Now When I get the data that was requested. The controller will validate which values are checked by the user.
The problem in this code is whenever I check the checkboxes it either checkbox 1 with the value of 1 or checkbox 2 with the value of 2 the controller identify which items are selected. Seems like the in_array of PHP doesn't checks if the value is in the array given from the ajax which is the $data_rest
My Controller (PHP)
public function save(Request $request)
{
$message = "";
$result = array();
$error = array();
$success = array();
$data_rest = array($request->dataRest);
if (in_array('1', $data_rest, true)){
$thu = "Success";
$success[] = $thu;
}
else
{
$thu = "Error";
$error[] = $thu;
}
if (in_array('2', $data_rest, true)){
$thu = "Success";
$success[] = $thu;
}
else
{
$thu = "Error";
$error[] = $thu;
}
$result = array(
'error'=>$error,
'success'=>$success,
);
echo json_encode($result);
}
This is the sample Output of array in javascript
Note: The problem is in my controller I'm using the code from the PHP Manual the if(in_array(value,arrayvariable, BOOLEAN)) which doesn't seems do its job to check if the value exist from the post array from ajax
Reference: https://www.php.net/manual/en/function.in-array.php

PHP & Jquery Creating Multiple Dynamic Select Lists with Probable Conditional Behaviors

The title is a bit much so let me break this down. What I am trying to accomplish here is selecting an option from select 1 (onChange) retrieves the prebuilt select for select 2 from an external php script. Same for 2 -> 3 and 3 -> 4. I know how to do this, perhaps not efficiently, but, I can get it done.
The problem I crashed into was, the 3rd select is not always an option. This is a problem because the 4th select is the end result I need. The second select in this case will give me the ID's to create select 4 instead. Make sense?
HTML:
<td>
<select name="collectionID" id="bpCollection" class="form-control">
<option value="">Select Collection</option>
<?PHP echo optionsFromDatabase();?>
</select>
</td>
<td><select name="bpClass"id="bpClass" class="form-control"></select></td>
<td><select name="bpFaction"id="bpFaction" class="form-control"></select></td>
<td><select name="bpID"id="bpID" class="form-control"></select></td>
JQUERY :
<script>
$("#bpCollection").change(function() {
$("#bpClass").load("inc/api/auto.php?type=class&choice=" + $("#bpCollection").val());
});
$("#bpClass").change(function() {
$("#bpFaction").load("inc/api/auto.php?type=faction&choice=" + $("#bpClass").val());
});
$("#bpFaction").change(function() {
$("#bpID").load("inc/api/auto.php?type=blueprint&choice=" + $("#bpFaction").val());
});
</script>
As Previously stated this does work perfectly.
Auto.php
$group = $db->escape($_GET['type']);
$choice = $db->escape($_GET['choice']);
$list = '';
switch ($group) {
case 'blueprint':
$db->where('marketGroupID',$choice);
$db->orderBy('typeName','ASC');
$map = $db->get('invTypes');
foreach ( $map as $val ) {
$list .= '<option value="'.$val['typeID'].'">'.$val['typeName'].'</option>';
}
break;
default:
$db->where('parentGroupID',$choice);
$db->orderBy('marketGroupName','ASC');
$map = $db->get('invmarketgroups');
foreach ( $map as $val ) {
$list .= '<option value="'.$val['marketGroupID'].'">'.$val['marketGroupName'].'</option>';
}
}
echo $list;
This works perfectly, except. #bpFaction is not always an option where it can't populate since #bpClass holds the ID options for #bpID. I can select the #bpClass select option and will need to jump straight to #bpID. I think a good part of the problem I have is that I don't visualize the code needed on either end to make this work properly. Do I need to make the jquery do this, do I need to change auto.php, or both?
Do you have any thoughts on how best to do it?
I recommended using Ajax with JSON above. Here I will go more in-depth of how to do that. I will be writing this sample using States, Cities, and Jurisdictions as the select box types.
We will be using one controller in PHP for all select boxes (just like yours above) except we will be re-writing it to return JSON instead. I don't know what framework you are using so I just wrote a sample of what it would look like:
// if no state passed in, return list
if(!$stateId = $request->get('state')) {
$loadedStatesFromDb = ...; // states loaded from DB
// if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
$states = [];
foreach($loadedStatesFromDb as $state) {
$states[$state->getId()] = $state->getName();
}
// your framework may require a different method of passing json data
return json_encode([
'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
'states' => $states
]);
}
// if no city passed in, load cities for the selected state
if(!$cityId = $request->get('city')) {
$loadedCitiesFromDb = ...; // cities loaded from DB for $stateId
// if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
$cities = [];
foreach($loadedCitiesFromDb as $city) {
$cities[$city->getId()] = $city->getName();
}
// your framework may require a different method of passing json data
return json_encode([
'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
'cities' => $cities
]);
}
// if no jurisdiction selected, load list
if(!$jurisdictionId = $request->get('jurisdiction')) {
$loadedJurisdictionsFromDb = ...; // jurisdictions loaded from DB for $cityId
// if your $loadedCitiesFromDb is an array of classes we need to format it into a flat array for JSON
$jurisdictions = [];
foreach($loadedJurisdictionsFromDb as $jurisdiction) {
$jurisdictions[$jurisdiction->getId()] = $jurisdiction->getName();
}
// your framework may require a different method of passing json data
return json_encode([
'result' => 'ok', // we pass this so the Ajax jquery call can check it returned successfully
'jurisdictions' => $jurisdictions
]);
}
And this is what your view would sort of look like (untested, but generally how you would do it):
<select name="state" id="state-select"></select>
<select name="city" id="city-select"></select>
<select name="jurisdiction" id="jurisdiction-select"></select>
<script type="text/javascript">
function _load_select_boxes(e) {
if(
$("#state-select").val() && $("#city-select").val() && $("jurisdiction-select").val() && // if we have an item selected in all select boxes
typeof e !== 'undefined' && e.target.id == 'jurisdiction-select' // if the select box that triggered the event is the last one
) {
_select_box_completed('jurisdiction', $("jurisdiction-select").val());
}
$.ajax({
url: '/where/you/load/select/boxes',
type: 'POST',
data: $("#state-select, #city-select, #jurisdiction-select").serialize(),
dataType: 'json', // what server will return
success: function (data) {
if (data.result === 'ok') {
if(typeof data.states !== 'undefined') {
// no need to reset options for the first select (unless we will be re-loading it without selecting a value)
// set select box options using the array of cities
for(var stateId in data.states) {
var stateName = data.states[stateId];
$("#city-select").append('<option value="' + stateId + '">' + stateName + '</option>')
}
} else if(typeof data.cities !== 'undefined') {
// reset select box
$('#city-select').find('option').remove();
// set select box options using the array of cities
for(var cityId in data.cities) {
var cityName = data.cities[cityId];
$("#city-select").append('<option value="' + cityId + '">' + cityName + '</option>')
}
} else if(typeof data.jurisdictions !== 'undefined') {
if(!data.jurisdictions.length) {
// no jurisdictions returned so we reached end
_select_box_completed('city', $("#city-select").val());
} else {
// reset select box
$('#jurisdiction-select').find('option').remove();
// set select box options using the array of jurisdictions
for(var jurisdictionId in data.jurisdictions) {
var jurisdictionName = data.jurisdictions[jurisdictionId];
$("#jurisdiction-select").append('<option value="' + jurisdictionId + '">' + jurisdictionName + '</option>')
}
}
}
} else {
// handle error for app
}
},
error: function (jqXHR, textStatus, errorThrown) {
// handle error for app
}
});
}
function _select_box_completed(type, id) {
// fired when we have selected as far as we can go
}
$(function(){
// this runs when page finishes loading, so we can load in the defaults and set events on the select boxes
$("#state-select, #city-select, #jurisdiction-select").on('change', function(e){
_load_select_boxes(e);
});
_load_select_boxes();
});
</script>
The simplest way to do this without changing much code is make your switch a function, build in a condition and call it again with changed parameters if that condition is met.
$list= myswitch($db, $group, $choice);
function myswitch($db, $group, $choice){
$list='';
switch ($group) {
case 'blueprint':
...
break;
default:
$db->where('parentGroupID',$choice);
$db->orderBy('marketGroupName','ASC');
$map = $db->get('invmarketgroups');
//*** CONDITION HERE ***
//IF condition met: set new variables
if($choice === ... && $map === ...)){
$group="xxx";
$choice="yyy";
//call the function again with new values
$list = myswitch($db, $group, $choice);
}
//ELSE create normal list
else{
foreach ( $map as $val ) {
$list.= ....
}
}
return list;
}

Populate Dropdown based on another Dropdown Using Ajax, jQuery and Codeigniter

I just wanna ask how to populate a dropdown based on another dropdown's value.
When I select a Campaign, it will show the names of the people that are in that Campaign in another dropdown but the value must be the id of the name.
Here is my Model
function get_agents($campaign_id)
{
$campaign_id1 = mysqli_real_escape_string($this->db->conn_id,trim($campaign_id));
$query = $this->db->query("SELECT tbl_employee.emp_id, CONCAT(tbl_applicant.fname, ' ', tbl_applicant.lname) AS fullname FROM tbl_applicant INNER JOIN tbl_employee ON tbl_employee.apid=tbl_applicant.apid INNER JOIN tbl_account ON tbl_employee.acc_id=tbl_account.acc_id WHERE tbl_account.acc_id='".$campaign_id1."'");
return $query->result();
}
Here is my Controller
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$this->KudosModel->get_agents($campaign_id);
echo $result;
}
Here is my AJAX
$('#addCampaign').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign').val(),
url : 'controller/method',
success : function(data){
$('#anyname').val(data);
}
});
}); //I dont know what to do here
Thanks in advance guys!
I think you need some manipulation in controller like-
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$employees = $this->KudosModel->get_agents($campaign_id);
/*
foreach($employees as $employee)
{
echo "<option value='".$employee->emp_id."'>".$employee->fullname."</option>"
}*/
// for json
$employeesList = [];
foreach($employees as $employee)
{
array_push($employeeList,array('emp_id'=>$employee->emp_id,'fullnme'=>$employee->fullname));
}
echo json_encode($employeeList, JSON_FORCE_OBJECT);
}
now in ajax success function-
success : function(data){
// anyname should be the id of the dropdown
// $('#anyname').append(data);
// for json
$json = JSON.parse(data);
// empty your dropdown
$('#dropdownId').empty();
$.each($json,function(key,value){
$('#dropdownId').append('<option value="'+key+'">'+value+'</option>');
})
}
You can simply iterate through your data and add options to your second Select
$('#addCampaign').on('change', function(){
$.ajax({
type : 'POST',
data : 'campaign_id='+ $('#addCampaign').val(),
url : 'controller/method',
success : function(data){
//data returns your name, iterate through it and add the name to another select
$.each(data, function($index, $value) {
$('#secondSelect').append($("<option></option>").val($value.id).html($value.name));
});
}
});
});
One thing, if you need a listener on your second <select> lets say on('click'), you need to add it back once you populated it. If not, Jquery won't recognize the new values.
Edit
Also, as #PersyJack stated, you need to asign the variable $result to something if you want to return it.
public function getAgents()
{
$campaign_id = $this->input->post('campaign_id');
$result = $this->KudosModel->get_agents($campaign_id);
echo $result;
}

Submitting form using JQuery, AJAX and PHP

I have a form which submits it to the database using JQuery, AJAX and PHP. The problem is, whenever I click the submit button of the form, the JavaScript alert says that the record (data from the form) has successfully recorded (to the database). I would then check my database but the data is not recorded, leaving the database empty and no changes at all. My question is, there something wrong with the script? Or with the PHP code?
Here's the script addnew.js:
$(document).ready(function() {
$("#submit").click(function() {
var transMonth = $("#transMonth").val();
var transDay = $("#transDay").val();
var transYear = $("#transYear").val();
var voucherNum = $("#voucherNum").val();
var expType = $("#expType").val();
var acctsPayable = $("#acctsPayable").val();
var amount = $("#amount").val();
var dataString = 'transMonth1='+ transMonth + 'transDay1='+ transDay + 'transYear1='+ transYear + 'voucherNum1='+ voucherNum + 'expType1='+ expType + 'acctsPayable1='+ acctsPayable + 'amount1='+ amount;
if(voucherNum=='') {
alert("Please fill a valid voucher number.");
}
else {
$.ajax ({
type: "POST",
url: "addnew.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
Here's the PHP code addnew.php:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("mydb", $connection);
//fetch values
$transMonth2 = $_POST['transMonth1'];
$transDay2 = $_POST['transDay1'];
$transYear2 = $_POST['transYear1'];
$voucherNum2 = $_POST['voucherNum1'];
$expType2 = $_POST['expType1'];
$acctsPayable2 = $_POST['acctsPayable1'];
$amount2 = $_POST['amount1'];
//query
$query = mysql_query("insert into anotherSample(transMonth, transDay, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
echo "Record added successfully";
mysql_close($connection);
I think your dataString in addnew.js should be transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='...,
otherwise the $transDay2,$transYear2..would be null, if your transDay or more set NOT NULL in mysql, there will occur a mysql error. :)
You should check returned result. You can do this by the following code:
$result = mysql_query("insert into anotherSample(transMonth, transDay, transMonth, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
if (!$result) {
die('Invalid query: ' . mysql_error()); // only for development, in production you shouldn't print error to client!
}
echo "Record added successfully";
mysql_close($connection);
PS. Also, I advice you to read about SQL-injections, because your code is vulnerable.
I see a problem in insert statement, insert into anotherSample(transMonth, transDay, transMonth, transYear,....) values ('$transMonth2', '$transDay2', '$transYear2, .....) 'transMonth' is repeated twice and eight columns with seven values.
In your addnew.js file you should use an ampersand (&) between each key/value pair like this:
var dataString = 'transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='+ transYear + '&voucherNum1='+ voucherNum + '&expType1='+ expType + '&acctsPayable1='+ acctsPayable + '&amount1='+ amount;
This way you will ensure that each variable will have a value when you are reading them in your addnew.php file.
Check fetched values in addnew.php
and echo mysql_error($connection) to check if mysql error was occurred.

insert javascript variable into mysql

I have created a quiz page named quiz.php. It contains javascipt which calculates the correct answers of the user (amountCorrect variable). I want to insert this variable to mySql db via scorepage.php but my code doesn't work. Any help ???
Here is the part of javascript
function show_score() {
var amountCorrect = 0;
...
if(radio.value == "right" && radio.checked) {
amountCorrect++;
}
}
alert("Correct " + amountCorrect + " out of 6");
$.ajax({
type: "POST",
url: "http://localhost/Istoselida/scorepage.php",
data: "score1=" + amountCorrect,
success: function () {
$('ul#posts').prepend(wall_post);
}
});
}
And here is the part of the scorepage.php
include('db2.php');
$member_id=$_SESSION['member_id'];
$result=mysql_query("select * from studentstable where id='$member_id'")or die(mysql_error);
$row=mysql_fetch_array($result);
$score1 = mysql_real_escape_string($_POST['score1']);
$sql=mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= $row");
You're trying to pass $row in the UPDATE statement. $row is an array, not a value. Try:
$sql = mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= $row[id]");
put row id $row['filedname']
$sql=mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= ".$row['id']);

Categories

Resources