Need to refresh page before changing element style - php

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

Related

On remove select2 option trigger ajax remove from mysql

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>

How to pass the form id or submit button into ajax

This is my index.php
$('#searchAdv').click(function() {
//What to be put here
$.ajax({
//what to be put here
url:"filter.php",
success: function(response){
$('#view').html(response);
}
});
});
<form>
<select id="adv1" name="task1">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<select id="adv2" name="task2">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<input type="submit" id="searchAdv" value="Filter">
</form>
<div id="view"></div>
How to pass the form id or submit button into ajax in order to send the form contents into another php page
First, you don't have an id of the form. So add that...
<form id="myForm">
Then I believe your problem would be resolved if you just bind to the submit call from the form and don't bind the click from the submit button.
$( "#myForm" ).submit(function( event ) {
// use ajax call in here, this will now refer to your form
var serialized = $(this).serialize();
});
You could keep the click bind, but it's just unusual for me. Then you'd just access the form using the $("#myForm") selector inside your current function.
you can do the altenative like this:
<form>
<select id="adv1" name="task1">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<select id="adv2" name="task2">
<option value="blabla">Bla Bla</option>
.
.
.
</select>
<input type="submit" onclick="add()" >
</form>
and then your ajax must add the datatype and data(what your data) like this :
function add(){
var username = $("#adv1").val();
var password = $("#adv2").val();
$.ajax({
dataType: 'html',
url: "filter.php>",
type: "POST",
data: username+password,
}).done(function(data) {
$('#view').html(response);
});
}
You can use jQuery's submit event handler to capture field values when the form is submitted and then send them to the ajax method. But first you need to attach an id to your form. Let's say we keep an id="form".
$('#form').on('submit',function(){
method = $(this).attr('method');
url = $(this).attr('action');
/*define these attributes in your form. Here you grab them and pass them to the ajax method later.*/
/* next you want the values of all your input fields.
* So we grab them values and assign them to their respective name attributes
* and we put the whole thing in the data object which we will send via ajax.
* It will look something like:
{ name_attribute_of_a_field:"value of that field",
name_attribute_of_another_field:"value of that field",
..and so on}
*/
data = {};
$(this).find('[name]').each(function(){
/*this will find all elements with a name attribute in it and loop through each of them.*/
name = $(this).attr('name');
value = $(this).val();
data[name] = value;
});
$.ajax({
url:url,
method:method,
data:data,
datatype:"type-of-response-data you expect",
success: function(data){
$('#view').html(data);
}
});
});

jquery ajax Display multiple pages in div from multiple selection drop-down form

I have a multi select drop down. I need a div to be filled with pages based on the selections. I have this working for one selection at a time. I need it to also work when I select more than one option the corresponding pages will populate the div.
For exemple... if I select Item1 and Item2. I want the pages item1.php and item2.php displayed in my div. If I then delete item1 from the selection (using chosen.js) I need only item2.php to show since that is the only current selection.
Here is my current code:
$('#maindiv').on('change', function(event) {
var selected = $(this).val();
$.ajax({
url: 'includes/'+ selected + '.php',
type: 'POST',
data: { cat: selected },
})
.done(function(data) {
$('#displaydiv').html(data)
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
jsfiddle Link. You can't get any output from here but you have to use this in your server.
For more clarification about the page is get or not, see this jsfiddle link. Here you can see the page which will load.
jQuery:
$(function(){
$('#maindiv').on('change', function(event) {
$('#displaydiv').html("");
selected = $(this).val() + "";
arr = selected.split(",");
i = 0;
$(arr).each(function(){
$.get('includes/'+ arr[i] + '.php', function( data ) {
$('#displaydiv').append(data);
});
i++;
});
});
});
HTML:
<select multiple id="maindiv">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<div id="displaydiv">
</div>

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