jquery-the output is always in the first item only - php

I am trying to create a web store and I use Jquery in radio button for selecting a category but the output is always on the first item only not in each items.
here is the jquery code
function populateswatches() {
var swatchesName = $('input[name=optradio]:checked').val();
$.getJSON('getdata.php', {swatchesName: swatchesName}, function(swatch) {
var html = '';
$.each(swatch, function(index, array) {
html = html + '<div class="col-md-3 w3-margin-top"><div class="w3-display-container w3-hover-opacity"><div class="w3-center"><input type="radio" name="swatches_code" value="' + array['swatches_code'] + '" required></div><div class="w3-display-middle w3-display-hover"><button type="button" class="btn btn-primary"><i class="fa fa-search fa-lg" aria-hidden="true"></i></button></div><img src="../backend/functions/images/'+array['images']+'" style="width:100%"><div class="w3-center">' + array['swatches_code']+'</div></div></div>';
});
$('#swatches').html(html);
});
}
$(function() {
$(this).change(function() {
populateswatches();
});
});
here is the code for php. it is not complete though.
$priceSQL="SELECT * FROM price WHERE id_item='$IDitem'";
$priceRES=mysqli_query($conn,$priceSQL);
while($priceROW=mysqli_fetch_assoc($priceRES)){
$id_categ=$priceROW["id_category"];
$catSQL="SELECT * FROM category WHERE id_category='$id_categ'";
$catRES=mysqli_query($conn,$catSQL);
while($catROW=mysqli_fetch_assoc($catRES)){
echo '
<div class="radio">
<label><input type="radio" name="optradio" value="'.$priceROW["price"].'-'.$id_categ.'" required>'.$catROW["swatches_category"].'- ₱'.formatMoney($priceROW["price"]).'</label>
</div>
';
}
}
</li>
</ul>
<h4>SWATCHES</h4>
<div class="form-group">
<span id="swatches"></span>
</div>
<input type="hidden" value="'.$IDitem.'" name="id_item">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Add to Cart</button>
here is the output
here is the image output for it

Reason:-
id is treated as unique identifier in jQuery.Since all spansin your code have same id, that's why code only working for first-one.
Solution:-
Convert id to class in your HTML code like below:-
<span class="swatches"></span>
And change # to . in jQuery like below:-
$('.swatches').html(html);
Note:- class is treated as a group identifier in jQuery and work on each element which share same class.

Related

JSON Decode to MYSQL Database

I am having JSON POST like this.
{"item_sku":["016","APL","017"],"item_quantity":[2,4,1]}
I want to insert it into mysql database table and in column named 'item_sku' and 'item_quantity'. I guess this will insert three rows.
HTML Page:
<form id="form1" class="p-md col-md-6" ng-submit="addOrder()">
<ul class="list-group m-b-sm md-whiteframe-z0" ng-repeat="item in cart.items">
<li class="list-group-item">
<a ui-sref="app.product({productSku: item.sku})" class="pull-right w-56"><img ng-src="http://192.168.0.228/app/{{ item.image || 'img/default_product.jpg' }}" alt="{{item.sku}}" class="img-responsive"></a>
<div class="clear">
<b>{{item.name}}</b><br>
<span style="color:#666;font-size:12px;">{{item.description}}</span><br>
<span style="color:#666;font-size:12px;">SKU# {{item.sku}}</span>
<input type="text" ng-model="sku[$index]" ng-init="sku[$index]=item.sku">
<br><br>
</div>
<div>
<!-- use type=tel instead of to prevent spinners -->
<button
class="form-control btn btn-grey" type="button" style="width:34px;background-color:#ddd;"
ng-disabled="item.quantity <= 1"
ng-click="cart.addItem(item.sku, item.name, item.price, -1)">-</button>
<input
class="form-control btn btn-grey" size="2" style="width:44px" type="tel"
ng-model="item.quantity"
ng-change="cart.saveItems()" />
<button
class="form-control btn btn-grey" type="button" style="width:34px;background-color:#ddd;"
ng-disabled="item.quantity >= 100"
ng-click="cart.addItem(item.sku, item.name, item.price, +1, $index)" >+</button>
<input type="text" ng-model="quantity[$index]" ng-init="quantity[$index]=item.quantity">
</div>
</li>
<div class="p b-t b-t-2x">
<a style="color:#666;" ng-click="cart.addItem(item.sku, item.name, item.price, -10000000)" >
<i class="icon mdi-action-delete i-20" style="color:#666;"></i>Remove</a>
<span class="pull-right">{{item.price * item.quantity | currency:' ₹ ':2}}</span>
</div>
</ul>
<button type="submit" class="btn btn-info m-t" >Submit</button>
</form>
Controller:
app.controller('OrderCtrl', function($scope, $location, $http ) {
$scope.sku = [];
$scope.quantity = [];
$scope.addOrder = function(){
$http.post(serviceURL+'submit_order.php', {
'item_sku':$scope.sku,
'item_quantity':$scope.quantity
})
.success(function(data,status,headers,config){
$location.path('app/feedbackthankyou');
});
};
});
PHP Code:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
include "db.php";
// Using Static Data from POST -- Just for testing
$a='{"item_sku":["016","APL","017"],"item_quantity":[2,4,1]}';
$data = json_decode($a);
var_dump($data);
foreach ($data as $value)
{
echo $value->item_sku;
echo $value->item_quantity;
}
?>
I guess details are enough now. BTW I am using AngularJS to create CART. Please help.
The shape of your data complicates the database insertion a bit. Data that should go in the same row is divided into two separate objects: $data->item_sku and $data->item_quantity.
It would be simpler if everything that should go in one row were together in one variable or one array element. I would change the shape of the data I submit. Instead of a item_sku and item_quantity, I would just submit items.
Javascript
var items=[];
for(var i=0; i<$scope.sku.length; i++){
items.push({'sku':$scope.sku[i], 'qty':$scope.quantity[i]});
}
$http.post(serviceURL+'submit_order.php', {items:items})
Then on the PHP side
$data = json_decode($_POST['items'],true);
Now $data is an array of items with the shape:
[
['sku'=>'016','qty'=>2],
['sku'=>'APL','qty'=>4],
];
This can be more easily inserted in your database because the data is already organized in rows. You said you already know how to do DB inserts so I'll let you work out that part.

Codeigniter, Submit "button" missing instructions from controller or model?

the submit "button" isn´t working properly, I know there must be something missing, the problem is Idk what is it...
The main idea is to insert information, then do a refresh displaying it in a table below, all in the same "page", the "submit" doesn´t save :(.
Thanks in advance.
Part of the code in Model:
function create_gei()
{
$data['theyear'] = $this->input->post('theyear');
$data['qty_alumni'] = $this->input->post('qty_alumni');
$data['emanations'] = $this->input->post('emanations');
$data['temperature'] = $this->input->post('temperature');
$this->db->insert("pdc_factor_gei", $data);
}
Part of the code in Controller:
function btn_create_gei()
{
$this->model_gas_consum->create_gei();
$submit = $this->input->post('send');
if($submit=='repeatgei')
{
redirect(current_url("gas_consum/factor_gei/"), 'refresh');
}
else
{
redirect("gas_consum/home_gas/");
}
}
Part of the code in View "button":
<?php echo form_open("gas_consum/factor_gei"); ?>
<div class="row">
<div class="col-md-6 text-right">
<button
name="send" value="repeatgei" class="btn" type="submit">
<span class="glyphicon glyphicon-refresh"></span> Save</button>
</div>
<?php echo form_close(); ?>
Try this
<input type="submit" name="send" value="repeatgei" class="btn">
Try this, change your
<button name="send" value="repeatgei" class="btn" type="submit">
<span class="glyphicon glyphicon-refresh"></span> Save</button>
To this
<?php echo form_submit('send', 'repeatgei', 'class="btn"'); ?>

Retrieving Id to display image using laravel

I am trying to retrieve an image from the database to be displayed in a modal for that selected user. However my attempts to display the image has proved futile. My problem is that I am unable to retrieve the id for that selected user image to be displayed. Any assistance would be GREATLY appreciated.
HTML (User list)
<table>
<tbody>
#foreach($users as $key => $u)
<tr class="id-here" data-id="{{$u->id}}">
<input type="hidden" class="avatar" value="{{$u->avatar}}">
<td class="firstname">{{$u->firstname}}</td>
<td class="lastname">{{$u->lastname}}</td>
<td class="email">{{$u->email}}</td>
<td class="project">{{$project->countProject($u->id)}}</td>
<td class="level">{{ucfirst($u->level)}}</td>
<td class="status"><span class="label label-{{$u->confirmed_email==0?'default':'success'}}">{{$u->confirmed_email==0?'unconfirmed':'confirmed'}}</span></td>
<td class="register">{{date("M j, Y g:i a", strtotime($u->created_at))}}</td>
<td>
{!!$u->level=='regular'?'<a class="btn btn-round btn-info edit get-id" title="edit" data-toggle="modal" data-target="#editModal"><i class="glyphicon glyphicon-edit"></i></a>':''!!}
<i class="glyphicon glyphicon-eye-open"></i>
{!!$u->level=='regular'?'<i class="glyphicon glyphicon-trash"></i>':''!!}
</td>
</tr>
#endforeach
</tbody>
</table>
{!! str_replace('/?', '?', $users->render()) !!}
Attempts
Attempt 1. HTML-- MODAL(Loops through data but returns all image paths)
<div class="form-group col-xs-6">
<div class="uploader pull-right">
<div class="pic-uploader">
<input id="file-1" class="edit-user-avatar" type="file" multiple="true" value='{{ROOT}}<?php
$all_users = \DB::table('users')->where('level', '=', 'regular')->get();
foreach ($all_users as $key => $value)
{
$id = $value->id;
$userImagePath = \DB::table('users')->where('id', '=', $id)->first(["avatar"]);
if(preg_match("/^https/", $userImagePath->avatar))
{
$pic = $userImagePath->avatar;
}
else
{
echo $pic = $userImagePath->avatar;
}
}
?>'>
</div>
<div style="margin-top:-40px;">
<small>File types allowed: <b>JPG</b>, <b>JPEG</b>, <b>PNG</b> or <b>GIF</b> • <b>1MB</b> file limit</small><br>
<small>At least 1024x768 pixels • 4:3 aspect ratio</small>
</div>
</div>
<input type="hidden" name="type" id="upload-type" value="user_avatar">
</div>
Attempt 2. HTML--MODAL(Stores id in hidden input but unable to retrieve the ID)
<div class="form-group col-xs-6">
<input type="hidden" name="userid" id="userid" value="<?php echo $userid = old('id')?>">
<div class="uploader pull-right">
<div class="pic-uploader">
<input id="file-1" class="edit-user-avatar" type="file" multiple="true" value='{{ROOT}}<?php
$id = $userid;
$userImagePath = \DB::table('users')->where('id', '=', $id)->first(["avatar"]);
if(preg_match("/^https/", $userImagePath))
{
$pic = $userImagePath;
}
else
{
echo $pic = $userImagePath;
}
?>'>
</div>
<div style="margin-top:-40px;">
<small>File types allowed: <b>JPG</b>, <b>JPEG</b>, <b>PNG</b> or <b>GIF</b> • <b>1MB</b> file limit</small><br>
<small>At least 1024x768 pixels • 4:3 aspect ratio</small>
</div>
</div>
<input type="hidden" name="type" id="upload-type" value="user_avatar">
</div>
JQUERY
$('.edit').click(function(){
var obj = $(this).parent().parent();
var fname = $(obj).find('.firstname').html();
var lname = $(obj).find('.lastname').html();
var status = $(obj).find('.status span').html();
var avatarImg = $(obj).find('.avatar').html();
var level = $(obj).find('.level').html().toLowerCase();
var id = $(obj).attr('data-id');
$('#edit-first-name').val(fname);
$('#edit-last-name').val(lname);
$('.edit-user-avatar').val(avatarImg);
$('#userid').val(id); // retrieves id to store in hidden input
if(status =='confirmed')
{
$('#edit-status').attr('checked','true');
}
else
{
$('#edit-status').removeAttr('checked');
}
//$('select#edit-title > option[value='+name[0].toLowerCase()+']').attr('selected','selected');
$('select#edit-level > option[value='+level+']').attr('selected','selected');
$('#uid').val(id);
$('#user-password').removeAttr('checked');
$('#user-data').attr('checked', 'checked');
$('#edit-password').css('display','none');
$('#edit-data').css('display','block');
});
Taken from the Bootstrap documentation:
$('#editModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // link that triggered the modal
var imageid = button.data('imageid') // Extract info from data-* attributes
var modal = $(this)
modal.find('.edit-user-avatar').val(imageid)
});
You'll just need to change you edit link to include the data-imageid attribute with the image ID as the value:
{!!$u->level=='regular'?'<a class="btn btn-round btn-info edit get-id" title="edit" data-imageid="{{ID GOES HERE}}" data-toggle="modal" data-target="#editModal"><i class="glyphicon glyphicon-edit"></i></a>':''!!}

Get id of Buttons using php once clicked

I have 4 buttons,and also an exportexcel button.I want to set the excel filename.If i clicked getToday button, i want to set the today date to the excel.
<div class="span3 btns_state">
<div data-toggle="buttons-radio" id="toggleButton" class="btn-group clearfix sepH_a">
<button type="button" name="getTday" id="getToday" class="btn btn-info rep_data tip-bottom active" data-original-title="<?php echo $today;?>"onclick = "show()">Today</button>
<button type="button" name="getWeek" id="getWeek" class="btn btn-info rep_data tip-bottom" data-original-title="<?php echo $this_week;?>"onclick = "show()">This Week</button>
<button type="button" name="getMonth" id="getMonth" class="btn btn-info rep_data tip-bottom" data-original-title="<?php echo $this_month;?>"onclick = "show()">This Month</button>
<button type="button" name="getPreMonth" id="getpremon"class="btn btn-info rep_data tip-bottom" data-original-title="<?php echo $previous_month;?>"onclick = "show()">Last Month</button>
</div>
</div>
My php code to get the dates.
$str = $_GET['getTday'];
if($str == 'getToday')
{
$var=$today;
}
else
{
$var=$this_week;
}
I want to retrieve the dates corresponding to the button i clicked,but only else part is working.
Here is the excel export.
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), Report-<?php echo $var?>.xlsx");
You can use query string to pass the value of clicked button
refer the "Today" button below.
You can set the value of variable "$var" to your execel or anything.
[Note:I done in the same page,create "test.php" and paste the following code and try,it will works well]
Thank You.
<?php
//Assume Variables $today and $this_week like below
$today = date('Y-m-d');
$this_week = "This week";
$var = "";
if(isset($_GET['getTday'])):
$str = $_GET['getTday'];
if($str == 'getToday')
{
$var=$today;
}
else
{
$var=$this_week;
}
endif;
echo $var;
?>
<div class="span3 btns_state">
<div data-toggle="buttons-radio" id="toggleButton" class="btn-group clearfix sepH_a" >
<button type="button" name="getTday" id="getToday" class="btn btn-info rep_data tip-bottom active" data-original-title="<?php echo $today;?>"onclick = "show('getToday')">Today</button>
<button type="button" name="getWeek" id="getWeek" class="btn btn-info rep_data tip-bottom" data-original-title="<?php echo $this_week;?>"onclick = "show()">This Week</button>
<button type="button" name="getMonth" id="getMonth" class="btn btn-info rep_data tip-bottom" data-original-title="<?php echo $this_month;?>"onclick = "show()">This Month</button>
<button type="button" name="getPreMonth" id="getpremon"class="btn btn-info rep_data tip-bottom" data-original-title="<?php echo $previous_month;?>"onclick = "show()">Last Month</button>
</div>
</div>
<script>
function show(val)
{
if(val == 'getToday')
{
location.href = "test.php?getTday=getToday";
}
}
</script>
Make button type submit with form tag
<form>
<button type="submit" name="getTday">
and so on...
</form>
Then you will get in php like $_GET['getTday'] this will get name attr of field so keep id and name same
else you need to use jquery/js to get id of button
add value attribute in your button like this value="getToday".
You can get this in php file.
Example
<button type="button" name="getTday" id="getToday" value="getToday" class="btn btn-info rep_data tip-bottom active" data-original-title="<?php echo $today;?>"onclick = "show()">Today</button>
Using jquery click event to perform your action. You have to remove all click event inside html
$(".btn.btn-info.rep_data.tip-bottom").click(function(){
var name=$(this).attr("name");
// you can get what ever it is
// this.id;
// this.value
});
DEMO
NOTE: Dont write event in html it is not good practis

Cannot pass hidden form value to php

When i pass the hidden value to the php file it gives (true) 1 as a answer.
I am passing the value from the modal to the php file.
The span value was retrieved using jquery.
PHP CODE:
<?php
include "dbcon.php";
if(isset($_POST['pd_del']))
{
echo mysql_error();
$delid=isset($_POST['delidd']);
echo $delid;
}else
{
echo mysql_error();
}
?>
HTML CODE:
Form thats send the product id to the php file
<form name="prd_del" action="del_prod.php" method="post">
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="delModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">DELETE PRODUCT</h4>
</div>
<div class="modal-body">
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="pd_del" >Delete It!</button>
</div>
</div>
</div>
</div>
</form>
Your HTML :
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid">
Your JS :
$(".modal-body #delid").text( pd_del_id);
First problem is that you have 2 elements with the same id value (the sppan and the input field). You shouldn't.
Change one of your ids, something like that :
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid_value">
And in your JS, if I understood what you want to do :
$(".modal-body #delid").text(pd_del_id); // Here you put the product's ID in your span to show it to the user.
$(".modal-body #delid_value").val(pd_del_id); // Here you put the product's ID in your hidden field to send it with your form.
Now, your PHP :
$delid=isset($_POST['delidd']);
echo $delid;
isset() function returns either true or false if the variable is set or not.
The variable $_POST['delidd'] is set (the hidden field is always sent to your PHP).
If you want to get the value (your product's ID) :
if (!empty($_POST['delidd'])) {
// The value is not empty
$delid = $_POST['delidd'];
} else {
// The value is empty : there is a problem (For example echo an error message or do whatever you have to do in that case.)
}

Categories