On remove select2 option trigger ajax remove from mysql - php

i am trying to build an crud operation with php and js(ajax) and i have some filters which user can add more filters to a category works fine on adding operation, but on edit i did with ajax and on click is retriving from databse and fill the inputs but on select2 i retrive data like this:
var main_id = $(this).attr("id");
$.ajax({
url:"<?php echo $site_url;?>/actions/get_filters.php",
method:"POST",
data:{main_id:main_id},
dataType:"json",
success:function(data){
var fl = [];
var nr = [];
$.each(data, function(i, field){
fl.push(field.fil_opt+","+field.txt_fil);
nr.push(field.id);
});
for (i = 0; i < nr.length; ++i) {
$('#filters_cat_update > option').each(function() {
$(this).attr('data-id', nr[i++]);
});
}
$('#filters_cat_update').val(fl);
$('#filters_cat_update').trigger('change'); // Notify any JS components that the value changed
}
});
I detect when i remove an option like this:
//remove from edit options
$('#filters_cat_update').on('select2:unselecting', function (e) {
console.log(e.params.args.data.id);
});
My html looks like this:
<div class="col-lg-6 col-md-12 col-sm-12">
<select class="js-example-basic-multiple custom-select mr-sm-2" name="filters_update[]" multiple="multiple" id="filters_cat_update">
<?php
$sqlf = mysqli_query($conn, "SELECT * FROM filtre WHERE vizibil=1 ORDER BY pozitie");
while ($rf = mysqli_fetch_assoc($sqlf)) {?>
<option data-id="" value="<?=$rf['id'];?>,<?=$rf['nume'];?>"><?=$rf['nume'];?></option>
<?php } ?>
</select>
</div>
What i want to do is when i click one option for example "color" to go with ajax and delete from table mysql where i have filters saved for each category and remove it.
As you see in my option i have concatenaded id of filter and name of filter coming from another table where user can create filters.
Thank you in advance.

You can get data-id using $("#filters_cat_update option:selected") which will give you selected option using this you can use .attr and .val() to get required values .
Demo Code :
$('#filters_cat_update').select2();
$('#filters_cat_update').on('select2:unselecting', function(e) {
var code = $("#filters_cat_update option:selected").attr('data-id'); //getting id
var values = $("#filters_cat_update option:selected").val(); //get values
var datas = values.split(',');
var id = datas[0]; //id
var color = datas[1]; //color
console.log("id - " + id + " color - " + color + " data-id -" + code)
//ajax call
$.ajax({
url: "your url",
method: "POST",
data: {
id: id,
color: color,
code :code
}, //send data
success: function(data) {
console.log("done")
}
});
});
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select class="js-example-basic-multiple custom-select mr-sm-2" name="filters_update[]" multiple="multiple" id="filters_cat_update">
<option data-id="2" value="1,Color">Color</option>
<option data-id="7" value="2,Color2">Color2</option>
<option data-id="77" value="3,Color3">Color3</option>
</select>

Related

Why select input field is not working in laravel view?

I have facing an weird problem in my laravel application. In my view file there are a select input field where values are fetched from database table. I have checked that data successfully passed to the view and tried with below code which is not working
<div class="row form-group">
<div class="col col-md-3">
<label for="text-input" class=" form-control-label">Course</label>
</div>
<div class="col-12 col-md-9">
<select class="form-control" name="course_id" id="course" required>
<option value="">Please select</option>
#if ($courses)
#foreach ($courses as $course)
<option value="{{$course->id}}">{{$course->name}}</option>
#endforeach
#endif
</select>
</div>
</div>
But when I have paste the same code again then the second input field is working properly. I didn't get any error.
Edited:
I have some JavaScript which given below
<script>
$(document).ready(function(){
// Add click
$(".addBtn").click(function(){
var id = this.id;
// Get data from field
var sem = $("#"+id).data('sem');
var slotId = $("#"+id).data('slot');
var timeSlot = $("#"+id).data('timeslot');
var dayId = $("#day").data('dayid');
var dayValue = $("#day").data('dayvalue');
// Add data to model
$('#dayInput').text(dayValue);
$('#semesterInput').text(sem);
$('#timeInput').text(timeSlot);
// Hidden input value for db
$('#dayInputValue').val(dayId);
$('#semesterInputValue').val(sem);
$('#timeInputValue').val(slotId);
// Get assign teacher
$.ajax({
url: "{{URL::to('admin/teacher-assign/sem')}}/"+ sem,
type: 'GET',
success: function(data){
$('#course').html("<option value=\"\">Please select</option>");
$.each(data, function(key, value) {
$('#course')
.append($("<option></option>")
.attr("value",value.course.id +'-'+ value.teacher.id)
.text(value.course.name +'-'+ value.teacher.name));
});
}
});
});
// Edit click
$(".editBtn").click(function(){
var id = this.id;
// Get data from field
var sem = $("#"+id).data('sem');
var slotId = $("#"+id).data('slot');
var timeSlot = $("#"+id).data('timeslot');
var dayId = $("#day").data('dayid');
var dayValue = $("#day").data('dayvalue');
// Edit data
var course = $("#"+id).data('course');
// var teacher = $("#"+id).data('teacher');
var roomNo = $("#"+id).data('room_no');
var editNote = $("#"+id).data('note');
var routineId = $("#"+id).data('routine_id');
// Add data to model
$('#editDayInput').text(dayValue);
$('#editSemesterInput').text(sem);
$('#editTimeInput').text(timeSlot);
$('#editCourseInput').text(course);
// $('#editTeacherInput').text(teacher);
$('#editRoomNoInput').text(roomNo);
// Hidden input value for db
$('#editDayInputValue').val(dayId);
$('#editSemesterInputValue').val(sem);
$('#editTimeInputValue').val(slotId);
// Assign ID
$('#editRoutineIdValue').val(routineId);
$('#editNoteInputValue').val(editNote);
// Get assign teacher
$.ajax({
url: "{{URL::to('admin/teacher-assign/sem')}}/"+ sem,
type: 'GET',
success: function(data){
$('#editCourse').html("<option value=\"\">Please select for edit</option>");
$.each(data, function(key, value) {
$('#editCourse')
.append($("<option></option>")
.attr("value",value.course.id +'-'+ value.teacher.id)
.text(value.course.name +'-'+ value.teacher.name));
});
}
});
});
// Add button
$('td').mouseenter(function () {
$(this).find('.addBtn').show();
}).mouseleave(function () {
$(this).find('.addBtn').hide();
});
// Edit button
$('td').mouseenter(function () {
$(this).find('.editBtn').show();
}).mouseleave(function () {
$(this).find('.editBtn').hide();
});
// Delete button
$('td').mouseenter(function () {
$(this).find('.deleteBtn').show();
}).mouseleave(function () {
$(this).find('.deleteBtn').hide();
});
});
</script>
change #if ($courses) this into #if (count($courses) > 0) this and try again.

Need to refresh page before changing element style

I'm trying to customize a shop cart with jQuery ajax validation, function in my server side are running smooth so far, my real problem is after adding the item in the cart. The Item name should be changing the color to indicate that the item is already selected, but it needs to manually refresh the page to start changing the color of the item name.
Here's the picture below:
After I click the '+' button, here's the output:
As you can see in the picture I've encircle the selected item, that should be changing the color after selecting the item.
Please see the code here:
$(document).ready(function(){
$(".form-item").submit(function(e){
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...'); //Loading button text
$.ajax({ //make ajax request to cart_process.php
url: "cart_process.php",
type: "POST",
dataType:"json", //expect json value from server
data: form_data
}).done(function(data){ //on Ajax success
$("#cart-info").html(data.items); //total items in cart-info element
button_content.html('+'); //reset button text to original text
alert("Item added to Cart!"); //alert user
if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
loadinc(); //trigger to update data
}
})
e.preventDefault();
});
//Show Items in Cart
function loadinc(){
$(document).ready(function(){
$(".shopping-cart-box").show(); //display cart box
$("#shopping-cart-results" ).load( "cart_process.php", {"load_cart":"1"}); //Make ajax request using jQuery Load() & update results
});
}
loadinc();
});
And here's the HTML File
<?php
//List products from database
$results = $mysqli_conn->query("SELECT * FROM tbldata where category = 'SALAD'");
if (!$results){
printf("Error: %s\n", $mysqli_conn->error);
exit;
}
//Display fetched records as you please
$products_list = '<ul class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= '
<li>
<form class="form-item">
<h4>'.
(in_array($row["name"],array_column($_SESSION["products"],'name')) ? '<span style="color:#b91e2d;">'.$row["name"].'</span>' : $row["name"])
.'</h4>
<div>Price : '.$currency.' '.$row["price"].'<div>
<div class="item-box">
<div>
Qty :
<select name="product_qty">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<input name="product_code" type="hidden" value="'.$row["product_code"].'">
<button type="submit">+</button>
</div>
</form>
</li>
';
}
$products_list .= '</ul></div>';
echo $products_list;
?>
You forgot this line:
.css('color', '#b91e2d');
Like this:
$(document).ready(function(){
$(".form-item").submit(function(e){
var title = $(this).closest('span');
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...'); //Loading button text
$.ajax({ //make ajax request to cart_process.php
url: "cart_process.php",
type: "POST",
dataType:"json", //expect json value from server
data: form_data
}).done(function(data){ //on Ajax success
$("#cart-info").html(data.items); //total items in cart-info element
button_content.html('+'); //reset button text to original text
alert("Item added to Cart!"); //alert user
title.css('color','#b91e2d');
if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
loadinc(); //trigger to update data
}
})
e.preventDefault();
});
//Show Items in Cart
function loadinc(){
$(document).ready(function(){
$(".shopping-cart-box").show(); //display cart box
$("#shopping-cart-results" ).load( "cart_process.php", {"load_cart":"1"}); //Make ajax request using jQuery Load() & update results
});
}
loadinc();
});
And also, your item should be:
$products_list .= '
<li>
<form class="form-item">
<h4><span'.
(in_array($row["name"],array_column($_SESSION["products"],'name')) ? ' style="color:#b91e2d;" : "")
. '>' . $row["name"] . '</span></h4>'...etc.
Thanks guys for helping.
I should need to put
window.location.reload();
after aler function.
Thanks guys. :D

Reset ajax data when button clcik using jquery

I have scenario form like this
if option selected it will come out a new field i named "hah" i call it using ajax script like this
$('#bahan').change(function() {
var id = $('#bahan').val()
var datana = 'id=' + id
var urlna = "<?=base_url()?>controller/food/getdetailstok";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
success: function(data) {
$('#hah').html(data);
}
})
return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<select class="form-control select2" name="bahan" id="bahan">
<option value="">-- Choose One --</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
</div>
<div id="hah"></div>
How to reset "hah" if i click button save. hah in reset because the value field options again become null
$('#hah').empty() will do the trick.
.empty() will remove every element from the DOM. In your case every element in your #hah div.
$('#bahan').change(function() {
$('#hah').html("");
var id = $('#bahan').val()
var datana = 'id=' + id
var urlna = "<?=base_url()?>controller/food/getdetailstok";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
success: function(data) {
$('#hah').html(data);
}
})
return false;
})

Making a search of course/teacher with Ajax and jQuery

I have a jQuery Ajax problem.
I have a select tag with options of courses, the select holds div id="course". I have a button with id of "go" and an empty div with id of "courseInfo". I need to make it so that when a course number is selected, the teacher name in my php file that goes with it is displayed on the page. I have all my Ajax written, everything is linked, but it wont work and no error when I debug.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
Form:
<form action="" method="post">
<select name="course" id="course">
<option value="420-121">420-121</option>
<option value="420-122">420-122</option>
<option value="420-123">420-123</option>
<option value="420-221">420-221</option>
<option value="420-222">420-222</option>
<option value="420-223">420-223</option>
<option value="420-224">420-224</option>
</select>
Select a course to see the course name and teacher assigned<br><br>
<input type="button" id="go" value="go!">
</form>
<br><br>
<div id="courseInfo"></div>
Assuming that the PHP side is working properly, the code below should fix the issue.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
console.log(file);
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
You miss the = in var file.
Yours was
var file = "Course.php?course"+$("#course").val();
It should be
var file = "Course.php?course="+$("#course").val();

AJAX/JS/PHP: Submitting value of a select box without page refresh or button click

I am currently using Ajax to submit an input field without a page refresh or button click. The function works well with a text input field But it doesnt work with posting the value of a select box and then php echoing the result. I check with the firebug tool and nothing is being posted by Ajax/js function.
How can I submit the value of a select box so I can then echo with the php? EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
$('#item_input').text( $('#resultval', result).html());
}
});
return false;
}
$('#item_name').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#item_name").val();
dataString = 'name='+ name;
});
});
</script>
PHP
<?php
if ($_POST)
{
$item_name = $_POST['name'];
echo ('<div id="item_input"><span id="resultval">'.$item_name.'</span></div>');
}
?>
HTML
<html>
<form method="post" id="form" name="form">
<select name="item_name" value="<? $item_name ?>" size="4" id="item_name">
<option value="">Item1</option>
<option value="">Item2</option>
<option value="">Item3</option>
<option value="">Item4</option>
</select>
</form>
<div id="item_input"></div>
</html>
select tags does not trigger keyup event , you should use change instead, try the following:
$('#item_name').on('change', function() {
clearTimeout(timer);
var name = $(this).val();
dataString = 'name='+ name;
timer = setTimeout(submitForm, 050);
});
$('#item_input').html(result);
Trigger submitForm() with an onchange event so that every time the value of <select> changes, it submits.
KeyUp is for input boxes and others that use the keyboard. Select boxes you can either use onClick or onChange, preferrably onChange:
$('#item_name').change(function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#item_name").val();
dataString = 'name='+ name;
}
This will work for you.
Good Luck!
It seems that your js is right problem is in your html part. you not provided the select list values. pls provide values to select list options.
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
//$('#item_input').html( $('#resultval', result).html());
//$('#special').text(result);
//$('#item_input').html( $('#resultval').html() + '<p>' + result + '</p>');
$('#item_input').html(result);
}
});
return false;
}
$('#item_name').on('change', function() {
clearTimeout(timer);
var name = $(this).val();
dataString = 'name='+ name;
timer = setTimeout(submitForm, 050);
});
});
it should be like this or whatever values you want to post
<select name="item_name" value="" size="4" id="item_name">
<option value="item1">Item1</option>
<option value="item2">Item2</option>
<option value="item3">Item3</option>
<option value="item4">Item4</option>
</select>

Categories