How to pass an array data from controller to blade file Laravel - javascript

I'm trying to pass an array from Controller to Blade
My Controller:
public function socaucuachuong($id){
$socaucuachuong = CauHoi::groupBy('chuong')->select('chuong', CauHoi::raw('count(id) as Total'))->where('idmonthi','=', $id)->get()->toArray();
return view('DeThi::dethi')->with('socaucuachuong', $socaucuachuong);
}
My Blade file:
$('select').select();
function get_units(id) {
var list = $('#dschuong');
list.empty();
var url = "{{ route('dethi.socaucuachuong') }}"+'/'+ id;
var success = function (result) {
if (result.length <= 0) {
var item = '<div class="input-field"><input type="text" disabled value="Môn này hiện chưa có câu hỏi nào"></div>';
list.append(item);
} else {
for (i = 0; i < result.length; i++) {
var item = '<div class="input-field"><label for="unit-' + result[i].chuong + '">Nhập số câu hỏi chương ' + result[i].chuong + ' (có ' + result[i].Total + ' câu) <span class="failed">(*)</span></label><input type="number" max="' + result[i].Total + '" class="unit_input" onchange="set_sum(' + result[i].Total + ')" name="unit-' + result[i].chuong + '" id="unit-' + result[i].chuong + '" required></div>';
list.append(item);
}
}
};
$.get(url, success);
}
My Route file:
Route::post('socaucuachuong', 'DeThiController#socaucuachuong')->name('dethi.socaucuachuong');

You can get array values in blade like this.
<script>
var socaucuachuong = #JSON($socaucuachuong); // this will be array value.
</script>

Related

Select one Particular sheet instead of listing all the sheets. Google app script, Code

I got this code from here : Display Spreadsheet Data to HTML Table
thanks to the great work of Cooper.
function htmlSpreadsheet(ssO) {
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(ssO.id);
var sht=ss.getSheetByName(ssO.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
s+='</body></html>';
var namehl=Utilities.formatString('<h1>%s</h1>', ss.getName());
var shnamehl=Utilities.formatString('<h2>%s</h2>', sht.getName());
var opO={hl:s,name:namehl,shname:shnamehl};
return opO;
}
function updateSpreadsheet(updObj) {
var i=updObj.rowIndex;
var j=updObj.colIndex;
var value=updObj.value;
var ss=SpreadsheetApp.openById(updObj.id);
var sht=ss.getSheetByName(updObj.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet() {
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
//working on this function right now 2017/11/08
function getAllSheets(ssO) {
var ss=SpreadsheetApp.openById(ssO.id);
var allSheets=ss.getSheets();
var vA=[['Select Sheet']];
for(var i=0;i<allSheets.length;i++)
{
var name=allSheets[i].getName();
vA.push([name]);
}
return {array:vA,type:'sel2'};
}
What I am trying to do is on a Single sheet. That is I don't want to browse all sheets and select among them~
I have tried modifying this code
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
// var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
// var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
I have used sheet Id instead of file.getId(), But It just don't work.
Please help me.
Change:
var files = DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS)
To getFileById():
var file = DriveApp.getFileById("sheet Id");
Then remove the loop:
function getSingleSpreadSheet() {
var file = DriveApp.getFileById("sheet Id")
var fileName = file.getName()
var fileId = file.getId()
var vA = []
vA.push([fileName, fileId])
return {
array: vA,
type:'sel1'
}
}

How to fix error GET http:... 404(not found)

I want to get value of dropdownlist and show textbox but my code dont working
This is my code:
Controller:
public function socaucuachuong($id)
{
$units = CauHoi::groupBy('chuong')->select('chuong', CauHoi::raw('count(id) as Total'))->where('idmonthi','=', $id)->get()->toArray();
return view('DeThi::dethi',compact('units'));
}
View: dethi.blade.php
$('select').select();
function get_units() {
var id = $('#id_select').val();
var list = $('#dschuong');
list.empty();
var url = "{{ route('dthi.socaucuachuong') }}"+'/'+id;
var success = function (result) {
if (result.length <= 0) {
var item = '<div class="input-field"><input type="text" disabled value="Môn này hiện chưa có câu hỏi nào"></div>';
list.append(item);
} else {
for (i = 0; i < result.length; i++) {
var item = '<div class="input-field"><label for="unit-' + result[i].chuong+ '">Nhập số câu hỏi chương ' + result[i].chuong+ ' (có ' + result[i].Total + ' câu) <span class="failed">(*)</span></label><input type="number" max="' + result[i].Total + '" class="unit_input" onchange="set_sum(' + result[i].Total + ')" name="unit-' + result[i].chuong+ '" id="unit-' + result[i].chuong+ '" required></div>';
list.append(item);
}
}
};
$.get(url, success);
}
Route:
Route::get('dethi/socau', 'App\Modules\DeThi\Controllers\DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
Route::resource('dethi', DeThiController::class);
And my error when I select dropdownlist:
How can I fix this?
You are missing a route parameter for the ID you're passing along.
https://laravel.com/docs/8.x/routing#required-parameters
Basically, your route needs to be updated to
Route::get('dethi/socau/{id}', 'App\Modules\DeThi\Controllers\DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
Route
Route::get('dethi/socau/{id}', 'App\Modules\DeThi\Controllers\DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
Javascript (blade)
var url = '{{ "dthi.socaucuachuong", ":id") }}';
url = url.replace(':id', id);

Clear previous results from query

Through the attached code I do a search on youtube based on the username and the results are shown. If I search twice, the results add up. I would like previous results to be deleted. I try with htmlString = card; but it show only one result.Thanks to everyone who wants to help me solve this problem.
var musicCards = [];
jQuery(document).ready(function() {
jQuery("#searchButton").on("click", function() {
var query = jQuery("#queryInput").val();
if (query != "") {
loadYoutubeService(query);
console.log(query + "");
}
});
});
function loadYoutubeService(query) {
gapi.client.load('youtube', 'v3', function() {
gapi.client.setApiKey('ADADADADADA');
search(query);
});
}
function search(query) {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: query,
type: 'channel',
maxResults: 15
});
request.execute(function(response) {
jQuery.each(response.items, function(i, item) {
if (!item['']) {
var musicCard = {};
musicCard._id = item['snippet']['customUrl'];
musicCard.title = item['snippet']['title'];
musicCard.linkprofilo = item['snippet']['channelId'];
musicCard.url = "https://www.youtube.com/channel/";
musicCard.description = item['snippet']['description'];
musicCard.immagine = item['snippet']['thumbnails']['high']['url'];
musicCards.push(musicCard);
}
});
renderView();
});
}
function renderView() {
var htmlString = "";
musicCards.forEach(function(musicCard, i) {
var card = createCard(musicCard._id, musicCard.title, musicCard.description, musicCard.url,musicCard.immagine, musicCard.linkprofilo);
htmlString += card;
});
jQuery('#youtube-utente').html(htmlString);
}
function createCard(_id, title, description, url, immagine, linkprofilo) {
var card =
'<div class="card">' +
'<div class="info">' +
'<img src="' + immagine + '" alt="' + description + '">' +
'</div>' +
'<div class="content">Clicca per selezionare:' +
'<h3>' + title + '</h3>' +
'<a class="seleziona" href="' + url +linkprofilo+'">'+ url +linkprofilo+'</a>' +
'<p>' + description + '</p>' +
'</div>' +
'</div>';
return card;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
Solved using :
request.execute(function(response) {
musicCards.length = 0; // clear array

How to convert the values in an array to strings and send to php?

I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.

Angular ng-href javascript function

I need to set href to Javascript function. When I click it, nothing happens, but when I hover over link it displays:
unsafe:javascript:ShowManagementdDiv('65','a60f2a16-267e-418d-bb14-d88de3a33b5f','0');
The table data is built dynamically in my angular controller:
contractorService.getemrtabulation()
.success(function (data) {
$scope.emrcolumns = data.EMRTabulationColumns;
repeatRow = '<td align="center" valign="middle" style="background-color:Transparent;border-color:Black;border-width:1px;border-style:Solid;padding:5px;white-space:nowrap;"><a class="IncidentColumn" ng-href={{e.hyper}}>Click Here to Review EMR Document</a></td>';
firstRow = '<td>EMR Document</td>';
for (i = 0; i < $scope.emrcolumns.length; i++) {
repeatRow = repeatRow + '<td>{{e.' + $scope.emrcolumns[i].vchAssociatedDetailColumn + '}}</td>';
firstRow = firstRow + '<td>' + $scope.emrcolumns[i].vchColumnHeaderText + '</td>'
}
firstRow = '<tr>' + firstRow + '</tr>';
$scope.emrdetail = data.EMRTabulationDetail;
angular.forEach($scope.emrdetail, function (value, key) {
value.dteExpirationDate = convertDate(value.dteExpirationDate);
value.dteDateCompleted = convertDate(value.dteDateCompleted);
value.dteEffectiveDate = convertDate(value.dteEffectiveDate);
});
angular.forEach($scope.emrdetail, function (value, key) {
contractorService.getimage(value.EMRDetailID, value.dteEffectiveDate)
.success(function (data) {
$scope.emrdetail[key].hyper = data;
});
});
$scope.emrTable = '<table>' + firstRow + '<tr style="text-align:center" ng-repeat="e in emrdetail">' + repeatRow + '</tr></table>';
firstRow = '';
repeatRow = '';
});
I use this to call it in the html:
<div class="row row-relative">
<div class="col-md-12">
<div>{{emrQuestion.EMRTabulationID}}{{emrQuestion.vchTabulationSequenceLetter}}. {{emrQuestion.vchClassPropertyName}}</div><br />
<div dynamic="emrTable"></div><br /><br />
</div>
</div>
The function is in a <script> tag on the page:
function ShowManagementdDiv(imageTypeID, Guid, selectedYear) {
var TargetWidth = 950;
var TargetHeight = 670;
bModalPopupActivated = true; window.clearTimeout(t);
DisplayModalDivExitWithClickSave('box', TargetWidth, TargetHeight, 'http://localhost/PECIMS/DocumentManagement.aspx?eid=' + imageTypeID + '&Edx=' + Guid + '&y=' + selectedYear, 'Close', 'Click to close window. ');
}
Here is the C# code that creates the link:
public async Task<ActionResult> GetImage(int emrDetailID, string docDate)
{
var columns = await CommonClient.GetEMRTabulationColumnsForClusterID(876);
var getcolumn = columns.FirstOrDefault(c => c.EMRTabulationColumnID == 1);
int? imageTypeId = getcolumn.EdataFileImageTypeID;
UserInfo.intDocumentManagementMode = 13;
UserInfo.intPerspectiveCompanyID = UserInfo.intMajorID;
UserInfo.intPerspectiveCompanyTypeID = UserInfo.intMajorCompanyType;
UserInfo.SegmentID = emrDetailID;
UserInfo.dteDocumentDate = DateTime.Parse(docDate);
var token = await CompanyClient.SaveRecallData(UserInfo);
string strPathAndQuery = Request.Url.PathAndQuery;
string strUrl = Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
string LinkToImagesApp = "";
LinkToImagesApp = AppendProtocolAndHostHeadersPathToWebConfigPath("LinkToImagesApplication");
string javaLink = strUrl + LinkToImagesApp + "/DocumentManagement.aspx?eid=";
string docLink;
string address = "javascript:ShowManagementdDiv('" + imageTypeId + "','" + token + "','0');";
return Json(address, JsonRequestBehavior.AllowGet);
}
I am assuming that the issue is that Angular deems the Javascript as "unsafe". Any assistance is greatly appreciated.
In order to use the Javascript function in my href I had to add the following to my app.js file:
app.config([
'$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|javascript):/);
}
]);

Categories