Laravel: rating system Javascript display - javascript

I'm making a review system. I'm done with the post, but the get and display wont perfectly work. Can you please help me with this.
HTML:
<input type="hidden" id="aa" value="{{$re->rating}}" />
<div id="d"></div>
JAVASCRIPT:
var wrapper2 = document.getElementById("d");
var rating = 0;
var myHTML2 = '';
var rating = document.getElementById("aa").value;
var nonee= 0;
nonee = 5 - rating;
for (var w = 0; w <rating; w++) {
myHTML2 += '<span class="fa fa-star"></span>';
}
for (var e = 0; e <nonee; e++) {
myHTML2 += '<span class="fa fa-star-o"></span>';
}
wrapper2.innerHTML = myHTML2;
The result should be three reviews along with the rating but it will only display the rating in the first review, the rest none.

Your solution can only be used to show 1 rating/review. If you need to show more reviews, you need to modify it with some iterations/loops.
If you don't use AJAX for fetching more reviews, you can just loop through all the reviews with blade template since you're using laravel.
#foreach($ratings as $re)
<div class="d">
#for($i = 0; $i < $re->rating; $re++)
<span class="fa fa-star"></span>
#endfor
#for($i = 0; $i < 5 - $re->rating; $re++)
<span class="fa fa-star-o"></span>
#endfor
</div>
#endforeach
If you're using AJAX, you can format the output of your ratings with JSON like such:
[
{"review_id":1, "rating":3, "review":"not so bad"},
{"review_id":2, "rating":5, "review":"good"},
{"review_id":3, "rating":5, "review":"perfect"}
]
and decode it with javascript, then let javascript handle the HTML generation:
<div id="containerRating"></div>
<script>
$.ajax({
url: "http://...",
type: "GET",
success: function(data){
var ratings = JSON.parse(data);
for (var i=0; i<ratings.length; i++) {
var ratingHtml = "<div class='review'>";
for (var j=0; j<ratings[i]; j++) {
ratingHtml = ratingHtml + "<span class='fa fa-star'></span>"
}
for (var j=0; j<5-ratings[i]; j++) {
ratingHtml = ratingHtml + "<span class='fa fa-star-o'></span>"
}
ratingHtml = ratingHtml + "</div>"
$("#containerRating").append(ratingHtml);
}
});
</script>

try this. i used modal here because its been tested with modal. you can change it to out on a non modal. the result is display on a table using ajax :
<div id="view" class="modal fade" >
<div class="modal-dialog box box-default" role="document">
<div class="modal-content">
<div class="modal-header" style="background-color:#4287f5;color:white">
<p class="modal-title">Record</p>
</div>
<form class="form-horizontal" method="post" role="form">
{{ csrf_field() }}
<div class="modal-body">
<div class="table-responsive">
<table id="tableID" class="table table-bordered table-striped table-highlight">
<thead>
</thead>
<tbody style="margin-left:10px;">
</tbody>
</table>
</div>
</div>
<div class="modal-footer" style="background-color:#4287f5;color:white">
<button type="button" id="btnclose" class="btn btn-primary btn-xs" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
//ajax
<script>
function getResult(x)
{
var ID = x;
//alert(ID);
$.get('/url?recordID='+ID, function(data){
var html = '';
html +='<tr bgcolor="#c7c7c7" align="center">';
html +='<th align="center">Review</th>';
html +='<th align="center">Ratings</th>';
html +='</tr>';
$.each(data,function(index,obj){
html +='<tr>';
html +='<td>'+ obj.review+'</td>';
html +='<td>'+ obj.ratings+'</td>';
}
html +='</tr>';
$('#tableID').html(html);
});
});
$("#view").modal('show')
}
</script>

Related

ajax get data request url not found but already exist, Laravel 8

hello guys i have a problem with my ajax data json, i have a project about scan a barcode with a webcam but it just views the code of the barcode, the data in the database not call in my ajax, this is the code of blade, i'm using a modal
this is the modal
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="scanModalLabel">Scan Barcode</h5>
<button type="button" class="close close-btn" data-dismiss="myModal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<dl class="row">
<dt class="col-sm-4"><h4>Kode Barang</h4></dt>
<dd class="col-sm-8" id="kode_barang"></dd>
</dl> <hr>
<table class="table align-items-center tabel-detail" >
<thead class="thead-light">
<tr>
<th>Nama Barang</th>
<th>Harga Jual</th>
<th>Stok</th>
<th>Insert</th>
</tr>
</thead>
<tbody class="list">
</tbody>
</table>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
this is the jquery code
var args = {
autoBrightnessValue: 100,
resultFunction: function(res) {
[].forEach.call(scannerLaser, function(el) {
$(el).fadeOut(300, function() {
$(el).fadeIn(300);
});
});
scannedImg.attr("src", res.imgData);
scannedQR.text(res.format + ": " + res.code);
console.log(res.code);
document.getElementsByName('qrcode')[0].value = res.code;
var kode= res.code;
$('#kode_barang').text(': '+kode);
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data)
{
$('.list').html(data.table_data)
}
});
$('#myModal').modal('show');
},
this is the controller
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::findOrFail($id)
->where('kode_barang', '=', $id)
->select('produks.*')
->first();
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
this is the route
Route::get('transaksi/scan', '\App\Http\Controllers\ProdukController#cekScan')->name('daftar_produk.scan');
what should i do the error said "jquery.min.js:2 GET http://localhost:8080/rezkastore1/%7B%7B%20route('daftar_produk.scan')%20%7D%7D?kode=2135758676 404 (Not Found)"
Seems like problem with URL.
You can't access the route in JS file.
Make a global variable in blade for ajaxURL then use in JavaScript.
<script>
var ajaxURL = '{{ route('daftar_produk.scan') }}';
</script>
<script src="xyz.js"></script>
I have no idea wether you write your Javascript section, in Laravel Blade View or in separate JS file. If you write it within Laravel Blade Template, you may use
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
but I recommend you to write complete URL within your AJAX call. Make your AJAX call like this :
$.ajax({
url:"/transaksi/scan",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data) {
$('.list').html(data.table_data)
}
});
Instead of using findOrFail(), you can use find() or regular where() with error handler, because findOrFail() will returns 404 not found if it can't find any records, here is the cekScan function
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::where('kode_barang', '=', $id)->first();
if (!$produk) {
return json_encode(['table_data' => 'Barang Tidak Ditemukan']);
}
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
Maturnuwun

AJAX in 000webhost

I am having problem with AJAX in 000webhost. The output for AJAX is not displaying. Also, there is no error in the Console when I inspected.
This is my website link:
https://cwp-geoworld.000webhostapp.com/
The AJAX part is working fine with localhost and it can display the list of continents in the sidebar as well as a table in the middle of the page when the sidebar is clicked.
Example of how it should look like is here:
https://drive.google.com/open?id=1Tn5hQXepA--o4LTqBc_DzjeZ17yz830Z
Here are the codes for the index.php which contains the AJAX code:
<?php
include("control.php");
//require_once( "classes/session.class.php" );
$username = Session::getInstance()->getProperty("username");
$userRole = Session::getInstance()->getProperty("userRole");
require_once( "classes/PDOConnection.class.php" );
//header('Content-type: application/json');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>GeoWorld | Home</title>
<!--Icon at the tab-->
<link rel="icon" type="image/png" href="images/globe_icon.png"/>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="template/other_pages/bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="template/other_pages/bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="template/other_pages/bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="template/other_pages/dist/css/AdminLTE.min.css">
<!-- Skins -->
<link rel="stylesheet" href="template/other_pages/dist/css/skins/skin-purple.css">
<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition skin-purple sidebar-mini">
<!--WRAPPER-->
<div class="wrapper">
<!-- Main Header -->
<header class='main-header'>
<!-- Logo -->
<a href='index.php' class='logo'>
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class='logo-mini'><i class='fa fa-globe'></i><b>Geo</b></span>
<!-- logo for regular state and mobile devices -->
<span class='logo-lg'><b>Geo</b>World</span>
</a>
<!-- Header Navbar -->
<nav class='navbar navbar-static-top' role='navigation'>
<!-- Sidebar toggle button-->
<a href='#' class='sidebar-toggle' data-toggle='push-menu' role='button'>
<span class='sr-only'>Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!--Include Conditions for Navbar-->
<?php include ('include/navbar.php'); ?>
</ul>
</div>
</nav>
</header>
<!--Include Sidebar-->
<?php include ('include/sidebar.php'); ?>
<!-- CONTENT WRAPPER -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1 align='center'>
Welcome to GeoWorld
</h1>
</section>
<!-- Main content -->
<section class="content container-fluid">
<!-- search form (Optional) -->
<div id="searchTextBox">
<div class="input-group">
<input type="text" id='search' name="search_country" maxlength=3 class="form-control" placeholder="Search for a country here...">
<span class="input-group-btn">
<button type="submit" id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</div><!-- /.search form -->
<br/>
<div class="searchResults"></div><br/>
<div class="box-body">
<div id="records"></div>
</div>
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
</div><!-- ./wrapper -->
<!-- Modal for show more details about country -->
<div class="modal fade" id="countryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">More details about the country</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>-->
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<!-- Modal for show details about city -->
<div class="modal fade" id="cityModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">City details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>-->
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<!-- Modal to update HOS -->
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
<!-- Modal to upload flag -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Upload Flag</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
</body>
</html>
<!-- REQUIRED JS SCRIPTS -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<!-- jQuery 3 -->
<script src="template/other_pages/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="template/other_pages/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="template/other_pages/dist/js/adminlte.min.js"></script>
<!--script for displaying continents and countries records-->
<script type="text/javascript">
$(document).ready(function(){
//$('#searchTextBox').hide();
$('.records').hide();
$("input[name='search_country']").on('keypress', function (e) {
var charCode = e.which;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8)
return true;
else
return false;
});
});
$(function()
{
$.getJSON( "showAllContinents.php", function(obj)
{
$.each(obj, function(key, value)
{
var sidebarOption = "";
//sidebarOption = '<input type="hidden" value="showAllContinents" name="action"/>';
sidebarOption += '<li>';
sidebarOption += '<a data-id="'+value.ID+'" class="sidebar-country">';
sidebarOption += value.Name;
sidebarOption += '</a>';
sidebarOption += '</li>';
$(".treeview-menu").append(sidebarOption);
});
});//end of $.getJSON function
$("#options_continent").change(function() {
getCountryRecords($(this).val());
});//end of option function
$(document).on('click', '.sidebar-country', function() {
getCountryRecords($(this).attr('data-id'));
});
//to show LifeExpectancy, GNP and HOS when button is clicked
$("#records").on("click", "#tbl_countries button#more_details",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
//var result= $.parseJSON(data);
//console.log(result);
var string ='<table id="tbl_countries" class="table table-bordered table-hover"><tr><th>Life Expectancy</th><th>GNP</th><th>Head of State</th></tr>';
$.each( data, function( key, value )
{
$(".records").empty();
string += "<tr>"
+"<td>"+value['LifeExpectancy'] +"</td>"
+"<td>"+value['GNP']+"</td>"
+"<td>"+value['HeadOfState']+"</td>"
+"</tr>";
});
string += '</table>';
$(".modal-body").append(string);
} //end of function data
); //end of get
});//end of click button
//to show city details when button is clicked
$("#records").on("click", "#tbl_countries button#city_details",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCityDetails.php',
{A3Code: A3Code},
function(data)
{
var string ='<table id="tbl_countries" class="table table-bordered table-hover"><tr><th>City Name</th><th>District</th><th>Population</th><th>Latitude</th><th>Longitude</th></tr>';
$.each( data, function( key, value )
{
$(".records").empty();
string += "<tr>"
+"<td>"+value['name'] +"</td>"
+"<td>"+value['district']+"</td>"
+"<td>"+value['population']+"</td>"
+"<td>"+value['lat']+"</td>"
+"<td>"+value['lng']+"</td>"
+"</tr>";
});
string += '</table>';
//$(".records").append(string);
$(".modal-body").append(string);
} //end of function data
); //end of get
});//end of click button
//to update HOS modal box
$("#records").on("click", "button#update_HOS",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
var forms='';
$.each( data, function( key, value )
{
forms +='<form id="updateForm" name="updateForm" action="updateHOS.php" method="post">';
forms +='<div class="form-group">';
forms +='<input type="hidden" id="A3Code" name="A3Code" value='+value["A3Code"]+'>';
forms +='<label class="control-label">HOS:</label>';
forms +='<input type="text" class="form-control" id="hos" name="hos" value='+value['HeadOfState']+'>';
forms +='</div>';
forms += '<div class="form-group">';
forms += '<input type="submit" class="btn-success" id="updateBtn" name="updateBtn" value="Update">';
forms +='</div>';
forms +='</form>';
});
$(".modal-body").append(forms);
} //end of function data
); //end of get
});//end of click button */
//to show upload flag modal box
$("#records").on("click", "button#upload_flag",function()
{
$("#uploadModal .modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
var uploadForm='';
$.each( data, function( key, value )
{
uploadForm +='<form id="uploadFlagForm" name="uploadFlagForm" action="upload_flag.php" method="post" enctype="multipart/form-data">';
uploadForm +='<div class="form-group" align="center">';
uploadForm +='<input type="hidden" id="A3Code" name="A3Code" value='+value["A3Code"]+'>';
uploadForm +='<input type="file" name="fileToUpload" id="fileToUpload">';
uploadForm +='</div>';
uploadForm += '<div class="form-group" align="center">';
uploadForm += '<button type="submit" class="btn btn-primary" id="uploadBtn" name="uploadBtn">Upload Flag</button>';
uploadForm +='</div>';
uploadForm +='</form>';
});
$("#uploadModal .modal-body").append(uploadForm);
} //end of function data
); //end of get
});//end of click button
//To get country records
function getCountryRecords(id) {
$.ajax
({
url: 'showCountryInfo.php',
type: 'post',
data: {ID:id},
success:function(response)
{
var userRole = "<?php echo $userRole; ?>";
var string = "";
//string += '<input type="hidden" value="showCountryInfo" name="action"/>';
string += '<table id="tbl_countries" class="table table-bordered table-hover">';
string += '<tr>';
string += '<th>Flag</th>';
string += '<th>Country Name</th>';
string += '<th width=200px>Region</th>';
string += '<th>Surface Area</th>';
string += '<th>Population</th>';
string += '<th width=150px>Independent Year</th>';
string += '<th width=100px>City Details</th>';
if (userRole === "admin")
{
string += '<th width=100px>More Details</th>';
string += '<th width=100px>Update Details</td>';
string += '<th width=100px>Upload Flag</td>';
}
string += '</tr>';
/* from result create a string of data and append to the div */
$.each( response, function( key, value )
{
//var base64URL = "";
$("#records").empty();
string += "<tr>";
//string += "<td><img src='"+value['image']+"'/></td>";
//string += "<td><img src='data:image/png;base64, "+base64URL+"'/></td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' data-id='" + value['A3Code'] + "'>View</button>" + "</td>";
//string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' value='" + value['A3Code'] + "'>View</button>" + "</td>";
string += "<td>"+value['Name']+"</td>";
string += "<td>"+value['Region']+"</td>";
string += "<td>"+value['SurfaceArea']+"</td>";
string += "<td>"+value['Population']+"</td>";
string += "<td>"+value['IndepYear']+"</td>";
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#cityModal' id='city_details' name='city_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
if (userRole === "admin")
{
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#countryModal' id='more_details' name='country_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#updateModal' id='update_HOS' name='update_HOS' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-edit'></i></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#uploadModal' id='upload_flag' name='upload_flag' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-flag'></i></button>" + "</td>";
}
string += "</tr>";
});
string += '</table>';
$("#records").append(string);
}
});
}
/*$(document).on('click', '#btnView', function(){
window.location.href = "view_flag.php";
});*/
$(document).on('click', '#btnView', function(){
var value = $(this).attr('data-id');
window.location.href = "view_flag.php?A3Code=" + value;
});
/*//For view flag function
$("#btnView").on('click', function(e) {
window.location.href = "view_flag.php";
});*/
/*$("#view_flag").on("click",function()
{
window.location.href = "view_flag.php";
});*/
//For search country function
$("#search-btn").on("click", function ()
{
if(document.getElementById("search").value.length < 3)
{
alert("The characters MUST NOT be less than 3!");
return false;
}
$("#records").empty();
$(".records").empty();
$('.searchResults').empty();
var searchCountry = $("#search").val();
$.get(
'searchCountryInfo.php',
{id: searchCountry}, //left->sql id ,right->script id
function (data)
{
if (!$.trim(data)){
alert("No country with that name is found!");
return false;
}
var userRole = "<?php echo $userRole; ?>";
var string = "";
//string += '<input type="hidden" value="searchCountryInfo" name="action"/>';
string += '<table id="tbl_countries" class="table table-bordered table-hover">';
string += '<tr>';
string += '<th>Flag</th>';
string += '<th>Country Name</th>';
string += '<th width=200px>Region</th>';
string += '<th>Surface Area</th>';
string += '<th>Population</th>';
string += '<th width=150px>Independent Year</th>';
string += '<th width=100px>City Details</th>';
if (userRole === "admin")
{
string += '<th width=100px>More Details</th>';
string += '<th width=100px>Update Details</td>';
string += '<th width=100px>Upload Flag</td>';
}
string += '</tr>';
// var base64URL = getBase64(data[0]['image']);
// console.log(base64URL);
/* from result create a string of data and append to the div */
$.each( data, function( key, value )
{
$("#records").empty();
string += "<tr>";
//string += "<td>"+"<img src='data:image/png;base64,base64_encode("+value['image']+")"+"'/>"+"</td>";
//string += "<td>"+"<img src='data:image/jpeg;base64, "+base64URL+"'/></td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' data-id='" + value['A3Code'] + "'>View</button>" + "</td>"; string += "<td>"+value['Name']+"</td>";
string += "<td>"+value['Region']+"</td>";
string += "<td>"+value['SurfaceArea']+"</td>";
string += "<td>"+value['Population']+"</td>";
string += "<td>"+value['IndepYear']+"</td>";
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#cityModal' id='city_details' name='city_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
if (userRole === "admin")
{
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#countryModal' id='more_details' name='country_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#updateModal' id='update_HOS' name='update_HOS' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-edit'></i></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#uploadModal' id='upload_flag' name='upload_flag' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-flag'></i></button>" + "</td>";
}
string += "</tr>";
});
string += '</table>';
$("#records").append(string);
}
);
}); // end of search function
}); //end of big function
</script>
Your help will be really appreciated. Thank you.

AngularJS: ng-click still not working after using "$compile(html)($scope)"

I want to do something like this:
(1) click 'create' to invoke function 'createGroupForm', and then some html will be prepend to '#user-group-list'
(2) then I type the group name and click the 'ok' button, and the console will print the group name I typed before.
Now I have achieved step 1, but in step 2 function 'createGroup' can't be invoked. So how can I fix this problem?
html:
<body class="skin-blue sidebar-mini" ng-app="myApp">
<div class="wrapper" ng-controller="authorityController">
<div class="content-wrapper">
<section class="content-header">
<span class="breadcrumb">
<a ng-click="createGroupForm($event)"><i class="fa fa-upload"></i>create</a>
</span>
</section>
<section class="content" id="user-group-list">
</section>
</div>
</div>
</body>
js:
angular.module('myApp').controller("authorityController",['$compile','$scope','$http','$log','$cookies',function ($compile,$scope,$http,$log,$cookies) {
$scope.groupName = "";
$scope.createGroupForm = function($event){
var html = '<div class="box box-solid" ng-repeat="groupInfo in groupInfoList">' +
'<div class="box-body">' +
'<input ng-model="groupName" class="pull-left" placeholder="please type in the group name"/>' +
'<span class="pull-right">' +
"<button ng-click='createGroup()' class='btn btn-danger pull-right btn-block btn-sm'>Ok</button>" +
'</span>' +
'</div>' +
'</div>';
var $html = $compile(html)($scope);
$("#user-group-list").prepend(html);
};
$scope.createGroup = function(){
$log.log($scope.groupName);
};
}]);
You pass the wrong reference, instead of $html you pass html to prepend
var $html = $compile(html)($scope);
$("#user-group-list").prepend(html);
should be
var $html = $compile(html)($scope);
$("#user-group-list").prepend($html);

How can I delete image uploaded?

My html code is like this :
<input type='file' multiple/>
<?php
for($i=0;$i<5; $i++) {
?>
<div class="img-container" id="box<?php echo $i ?>">
<button style="display: none;" type="submit" class="btn btn-danger show-button">
<i class="glyphicon glyphicon-trash"></i>
</button>
</div>
<?php
}
?>
My javascript code is like this :
$(function () {
$(":file").change(function () {
var noOfFiles = this.files.length;
for(var i=0; i < noOfFiles; i++) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[i]);
}
});
});
function imageIsLoaded(e) {
var imgTmpl = '<img height="142" width="162" src='+e.target.result+'>';
var IsImgAdded=false;
$('.img-container').each(function(){
if($(this).find('img').length==0 && IsImgAdded==false){
$(this).append(imgTmpl);
IsImgAdded=true;
$(this).find('.show-button').show();
}
});
};
$(".show-button").click(function(){
$(this).find('img').hide()
});
Demo and full code is like this : http://phpfiddle.org/main/code/uu9x-w50q
I try use hide the image. But it does not work
How can I solve this problem?
You should use parent method in order to achieve this, because image DOM element belongs to the parent of .show-button.
$(document).on('click',".show-button",function(){
var imgTmpl = '<div class="img-container">'+
'<button style="display: none;" type="submit" class="btn btn-danger show-button">'+
'<i class="glyphicon glyphicon-trash"></i>'+
'</button></div>';
$(this).parent().remove();
$('body').append(imgTmpl);
});
Here is solution.
Try with closest()
$(".show-button").click(function(){
$(this).closest('.img-container').find('img').hide()
//$(this).closest('.img-container').children().remove() used for remove the all child element of the `.img-container`
console.log('hi')
});

display array data in a modal with success function in ajax

I have a function in a controller that will return an array that contains data from dataBase, that data will be sent to my success function as a json file ,
i want to display those informations in a div in my modal, and i can't do that so here is my controller function :
public function list_salle($id)
{
$data= $this->salle_model->get_all_salle($id);
$this->output->set_output(json_encode($data));
}
and here is my js function and its ajax :
function consulter_salle(id)
{
$.ajax({
url : "<?php echo site_url('index.php/batiment/list_salle')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
var table_header = "<table class='table table-striped table-bordered'><thead><tr><td>head_x</td><td>head_y</td></tr></thead><tbody>";
var table_footer = "</tbody></table>";
var html ="";
for (row in data)
{
html += "<tr><td>"+data.id +"</td><td>"+data.libelle+"</td></tr>";
}
var all = table_header +html+ table_footer;
// show bootstrap modal when complete loaded
$('.modal-title').text('Test');
$('#salle_list').html(all);
$('#modal_list').modal('show');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error displaying data');
}
});
}
and here is my modal :
<div class="modal fade" id="modal_list" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Liste des salles</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<div class="form-body">
<div id="salle_list"></div>
</div>
</form>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
</div>
So the data is sent correctly as a json file but i can't display it and i think the problem in the loop and the .html function , please help
thank you !
Your for loop in the ajax looks like it should be a foreach, but even then it's wrong. You're iterating over a json object, look at this question if you want some alternatives on how to do that: How do I iterate over a JSON structure?. One answer there gives a loop like this:
$(jQuery.parseJSON(JSON.stringify(data))).each(function() {
html += "<tr><td>"+this.id +"</td><td>"+this.libelle+"</td></tr>";
}
I found a solution :
success: function(data)
{
var table_header = "<table class='table table-striped table-bordered'><thead><tr><td>Identifiant</td><td>Libelle</td></tr></thead><tbody>";
var table_footer = "</tbody></table>";
var html ="";
data.forEach(function(element) {
html += "<tr><td>"+element.id +"</td><td>"+element.libelle+"</td></tr>";
});
var all = table_header +html+ table_footer;
$('.modal-title').text('Liste des salles');
$('#salle_list').html(all);
$('#modal_list').modal('show');
}

Categories