How to update quantity in session array on the go? - php

I want to capture value keyed in textbox for quantity in the shopping cart while they type. I used jquery's key up for this.Then I want to save the new value in the session for quantity. I'm getting the value but unable to save it. It returns null after refreshing the page.
Html
<input type="text" size="4" class="qty" value="<?php echo $v['quantity'];?>" id="<?php echo $k;?>"/>
Ajax
$("input[class=qty]").keyup(function()
{
var data;
var newVal = $(this).val();
var id = this.id;
console.log(id+" "+newVal);
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php?id="+id+"&&value"+newVal, //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});
});
updateCart.php
<?php
session_start();
$id = $_GET['id'];//say 2
$new_value =$_GET['value'];//say 16
foreach($_SESSION['cart'] as $k=>$v)
{
$k;
$v["id"];
$v["quantity"];
if($id == $k)
{
//assign new value to the quantity
$_SESSION['cart'][$id]['quantity']=$new_value;
//print_r($_SESSION['cart'][1]['quantity']);
}
}
//echo json_encode($new_value);
//var_dump($_SESSION['cart']);
this can display session['cart'] with updated value if I test in
this page ..but when passed to originated page via ajax, returns null.
echo $_SESSION['cart'][$id]['quantity'];
?>

You left out the = between &value and + newVal. But I recommend you let jQuery do this automatically by using the data: option.
data = { id: id, value: newVal };
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});

Related

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

passing with AJAX to php include

I need to get the following code to pass the $Bus_Account_ID and the $Usr_ID to the include file rating2.php
$Bus_Account_ID=733;
$Usr_ID=3;
I am not familar with AJAX so learning here.
I believe that this is the line passing to the include but I don't know what is happening with "attrVal"
data: 'postID='+attrVal+'&ratingPoints='+val,
$(function() {
var value = "<?php echo $total_points ?>";
$("#rating_star").codexworld_rating_widget({
starLength: '5',
initialValue: value,
callbackFunctionName: 'processRating',
imageDirectory: 'images/',
inputAttr: 'postID'
});
});
function processRating(val, attrVal){
$.ajax({
type: 'POST',
url: 'rating2.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
dataType: 'json',
success : function(data) {
if (data.status == 'ok') {
$('#avgrat').text(data.total_points);
$('#totalrat').text(data.rating_number);
}else{
alert('Some problem occured, please try again.');
}
}
});
}
postid shows in only 3 place in the above and here
<input name="rating" value="0" id="rating_star" type="hidden" postID="1" />
This is what is being called on the include file
$postID = $_POST['postID']; /* BUSINESS ID */
How to I call the $Bus_Account_ID and the $Usr_ID?
You have the problem with passing the data here.., You need to maintain the format like this: data: { name: "John", location: "Boston" }
$.ajax({
type: 'POST',
url: 'rating2.php',
data: 'postID='+attrVal+'&ratingPoints='+val,
So change the data by,
data: { postID: attrVal, ratingPoints: val, Usr_ID : "<?php echo $Usr_ID;?>", Bus_Account_ID : "<?php echo $Bus_Account_ID;?>" }

Make Checkbox that checked after submit to be visible using ajax

I have a form that takes the attendance of staffs. After submit I need the checkbox to be checked for the selected staffs. The form is submitted through ajax. Below is the code that inserts the attendence of the whole staffs.
var _data = new FormData($('#formaction')[0]);
$.ajax({
type: 'POST',
dataType:"json",
processData: false,
contentType: false,
url: '<?php echo base_url();?>SchoolAdmin/insertAttendance',
data: _data,
success: function (result) {
console.log(result);
staffattendance();
}
});
function staffattendance()
{
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
//var currentDate = fullDate.getDate() + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
var currentDate = fullDate.getFullYear()+"-"+ twoDigitMonth +"-"+fullDate.getDate();
$.ajax({
type: 'POST',
dataType:"json",
url: '<?php echo base_url();?>SchoolAdmin/staffattendance',
data: {currentDate:currentDate},
success: function (result) {
$.each(result, function (i, item) {
console.log(result[i].staff_id);
$('.teachers').prop('checked', true);
});
}
});
}
Here I called a function staffattendance(), to get the staff id of staffs who is present on the current day. So i need to match the staff id I received through this function with the checkbox field and should be in checked mode. Below is the code that dynamically generates checkboxes with staff name.
<?php foreach($teacher as $row)
{?>
<tr><td>
<?php echo $row->name;?>
</td>
<td>
<input type="checkbox" name="teachers[]" class="teachers" value="<?php echo $row->staff_id;?>" >
<input type="hidden" name="teachers1[]" class="teachers1" value="<?php echo $row->staff_id;?>">
</td>
</tr>
<?php }?>
So I need to retain the checkbox of the staff_id that i got from staffattendance() fuction .
How this can be achieved.
Rose, the question is bit unclear as you do not specify when your table with names and checkboxes are generated and will this table be affected by ajax success..
you could try:
$.each(result, function (i, item) {
console.log(result[i].staff_id);
$('.teachers[value="'+result[i].staff_id+'"]').prop('checked', true);
});

How to create dynamic table using the results

$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
dataType:"JSON", //<----here
success: function(json){
var str= "<table><tr>";
$.each(json.query,function(i,v){
alert(v.uID); //gives U0016
alert(v.name); //gives saman
str+="<td>"+v.uID+"</td>";
str+="<td>"+v.name+"</td>";
})
str+="</tr></table">;
$("body").append(str);
}
I want to create a dynamic table using json object values it must create a table but this is not working it will says v.ID not define
row += "$('<td>').append("+dataString[i]+")";
or
var row = $('<tr>');
for(var i = 0; i < n; i++) {
row.append($('<td>').html(dataString[i]));
}
$('#results').append(row);
create a table on the layout (on html code) then inside this create a <tbody> tag. assign an ID, then on the success function of your jquery, use $("#*tbody ID*").html to assign the value on the tbody.
i've got this code on one of my projects. maybe you can use this as a reference (tblApproved is the id of the tbody):
function updateApprovedTable(){
// retrieve Unit Record
$.ajax({
type:'post',
url:'php/requests.php',
data:{mode:"getApproved"},
success:function(data){
$('#tblApproved').html(data);
}//success
});//ajax
}
can you please used this :
$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
success: function(data){
$("body").append(data);
});
Also write your code for table create into this url "/controller_d/login/admin_search_user"
PHP Code
echo "<table>";
echo "<tr><td>content</td></tr>";
echo "<tr><td>content</td></tr>";
echo "<tr><td>content</td></tr>";
echo "</table>";

JQuery: How to apply this click function to all elements of the same class on the page?

My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.

Categories