Show individual record on pop up Laravel - javascript

I am using a resource controller. All records are displayed on the dashboard. From here, I am trying to show an individual record after I click the show button.
The data is displayed on the pop up but it is the wrong one.
How can I solve this issue?
DashboardController.php
public function index()
{
$frontend = Frontend::orderBy('created_at', 'desc')->paginate(10);
return view ('dashboard')->with('frontends',$frontend);
}
dashboard.blade.php
<button type="submit" class="btn btn-secondary" onclick="showReviewModal()">
<i class="fas fa-eye"></i>
</button>
<div id="modalReview"
class="fixed overflow-x-hidden overflow-y-auto inset-0 flex justify-center items-center z-50 p-6"
style="display: none;">
<div class="relative mx-auto w-auto max-w-2xl">
<div class="bg-white w-full p-12 rounded-lg text-xl">
<span><strong>Review</strong></span>
<br />
#if (count($frontends))
<p class="mt-6 text-justify">{{ $frontend->review }}</p>
#endif
</div>
</div>
</div>
script.js
function showReviewModal() {
$("#modalReview").show();
$("#modalShadow").show();
}

You can consider getting the record id using jQuery/JavaScipt e.g
var id = attr('id')
This is assuming you would have used a data attribute "data-id"
From there, you simply do an Ajax call to the server to call the individual record you want to display in the modal by passing back the record id.
<script>
$(document).ready(function(){
$(this).click(function(){
var id = attr('id')
$.ajax({
type: "GET",
url: "/YOUR_URL/" + id,
dataType: "json",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (response) {
//CALL YOUR MODAL HERE AND LOAD IT WITH THE RETURN DATA
}
});
</script>

Related

Send data to another django template/view after specific process using ajax

I have a page where I load 2 files. After a click to the load button, this page reload to display a major part of the data, allowing the user to modified it. After a click to lunch button, I want to launch the process and I want to send to another page the path of results files to allow the user to download it.
My problem is after clicking on lunch button and send data to the other page. I have 2 versions :
The first one, send data to the result page, but I do not find a way to take back in the view the data modified by the user, the ajax seems to be ignored because of the type "summit" for the button launch :
<body>
<section class="bg-light py-5 border-bottom">
<div class="container px-5 my-5 px-5">
<div>
<h1 class="display-5 fw-bolder mb-2"> Convert to Dose </h1>
<br>
</div>
<form id="formCTD" action="{% url 'json:convertToDose' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
##here some fields to modified one of them following
<div class="row gx-5 justify-content-center">
<div class="col-lg-4 col-xl-4">
{% if factors %}
<input name="img_path" readonly
class="form-control" {{ pathAnalyseForm.img_path }}>
{% else %}
<input id="btn-submit-form-jsonfile"
class="btn btn-lg" {{ formImgFile.imgFile }}>
{% endif %}
</div>
</div>
<div class="text-center">
<div class="d-grid">
{% if factors %}
<button class="btn btn-primary btn-lg" id="launchButton" type="submit">
Launch
</button>
{% else %}
<button class="btn btn-primary btn-lg" id="submitButton" type="submit">
Load
</button>
{% endif %}
/div>
</div>
</form>
</div>
</section>
</body>
And the js block :
<script type="text/javascript">
$(document).ready(function () {
$("#launchButton").on('submit', function(e) {
e.preventDefault();
var form = $("#formCTD").get(0) //recup en html
// Est-ce que le formulaire est valide ?
console.log("valid? ")
if (form.checkValidity()) {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ")
nam = $("input[name='img_path']").val()
json = $("input[name='json_path']").val()
console.log(nam)
data = {"img_path" : nam,
"json_path": json}
console.log("bef ajax")
$.ajax({
url: "/filmchromique/convertToDose/",
type: "POST",
data: data,
beforeSend: function (xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val());
},
success: function (response) {
console.log("ok")
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
})
console.log("after ajax")
}
});
});
</script>
And the view :
def launchCtd(request):
if request.method == 'POST':
#2 after click load
if bool(request.FILES.get('calibrationFile', False)) == True and bool(request.FILES.get('imgFile', False)) == True :
#do some test ok
context = {
'factors': True,
'factorsCalib': factorsCalib,
'formCtd': formCtd,
'formJsonFile': formJsonFile,
'formImgFile': formImgFile,
'pathAnalyseForm': pathAnalyseForm,
'doseRect': doseRect,
'ctrlRect': ctrlRect,
}
return render(request, 'convertToDose.html', context)
after click lunch
else:
if request.is_ajax:
print ("here")#check
img_path = request.POST.get("img_path")
doseRectStr = request.POST.getlist('form[]')
json_pactrlRectth = request.POST.get("json_path")
method = request.POST.get("analyse_type")
if method == 'rb':
#init var
if method == 'multi':
#init var
img_out_path, json_pactrlRectth = functionTOLaunch()
context = {
'filename': img_out_path,
'protocol_file': json_pactrlRectth,
}
return render(request, 'result.html', context)
#1 load init
else:
formCtd = CtdForm()
formJsonFile = JsonFileForm()
formImgFile = ImgFileForm()
context = {
'factors': False,
'formCtd': formCtd,
'formJsonFile': formJsonFile,
'formImgFile' : formImgFile,
}
return render(request, 'convertToDose.html', context)
and the result page is a basic TemplateView.
In this first case, console.log in the ajax are not printed, I do not understand why and I supposed the function is not called (and so the ajax part)
in the second version, views are identical but I modified this on the html :
<button class="btn btn-primary btn-lg" id="launchButton" type="button">
Launch</button>
and this in the js part :
$("#launchButton").on('click', function(e) {....}
Data are sended to the view, I can read it but when I do the render to display the result page with out process data, nothing append... I supposed I have to implement something in the succes ajax part, but I do not understand what I have to do. I supposed I have to implement a new ajax request, to send the new context to the result page but how I take back the context sended by the render in the success ajax ... I'am totaly new and lost on this tech
Thanks for reading :)

Laravel project using Stripe works, once I push it online over FTP the fetch method suddenly doesn't want to work anymore

Locally my project works perfectly fine. I'm trying to get it online by transfering it over FTP to my domain. So far everything works but the only problem is when I try to fetch the session_id from where it's supposed to be fetched from... It doesn't function. The app is hosted on a subdomain -> https://[domain].be/app.
I'm pretty sure something is wrong with the fetch URL, which makes it fail. But I did the exact thing that I did with Localhost, but with adjusted pathing which should be correct...
The view that puts everything into works (laravel component)
#section('content')
<div class="bg-white">
<svg class="ml-6 mt-3 sm:hidden" xmlns="http://www.w3.org/2000/svg" width="12.838" height="12.512" viewBox="0 0 12.838 12.512" onClick="history.go(-1)">
<path id="Icon_awesome-arrow-left" data-name="Icon awesome-arrow-left" d="M7.376,14.322l-.636.636a.685.685,0,0,1-.971,0L.2,9.391a.685.685,0,0,1,0-.971l5.57-5.57a.685.685,0,0,1,.971,0l.636.636a.688.688,0,0,1-.011.983L3.912,7.757h8.235a.686.686,0,0,1,.688.688v.917a.686.686,0,0,1-.688.688H3.912l3.453,3.289A.683.683,0,0,1,7.376,14.322Z" transform="translate(0.004 -2.647)" fill="#707070"/>
</svg>
<div class="w-12/12 bg-navBlack sm:w-11/12 m-auto">
<img class="m-auto w-11/12 h-64 bg-navBlack object-contain mt-3 mb-14 bg-white sm:w-11/12 sm:m-auto sm:mb-20 sm:mt-3 sm:max-w-2xl" src="{{$subscription->logo}}" alt="image">
</div>
<div class="bg-fWhite rounded-tr-[60px] relative h-11/12 sm:w-11/12 m-auto">
<div class=" w-9/12 m-auto max-w-xl">
#livewire('favorite-live', ['type' => 'Subscription', 'typeId' => $subscription->id, 'fill' => $subscription->fill])
<h1 class="text-2xl text-fBlack pt-10 mb-10 w-10/12">{{ $subscription->title }}</h1>
<p class=" text-sm mb-16">{{ $subscription->description }}</p>
<form method="post" action="app/checkout/subscription/{{ $subscription->id }}">
#csrf
<button id="checkout-button" data-id="{{ $subscription->id }}" data-type="subscription" class="text-base w-11/12 text-white uppercase bg-fGreen border-none text-xs tracking-wide py-2 px-3 rounded-3xl mb-8 max-w-sm block m-auto text-center">gebruiken</button>
</form>
<div class="pb-32">
{!! $shareComponent !!}
</div>
</div>
</div>
</div>
#endsection
#section('footer-scripts')
<script src="{{ asset('/js/components/stripe.js') }}"></script>
#endsection
The JS code that activates when clicking the button.
const stripe = Stripe('pk_test_51K1WOQDm7AvXHILKuryQBYtRpecxjXB7GtWrX5fjGRQ2Gq3tlZLfIPrczJ1jazwfARsroGWmBsHceD2L3NS4tAgJ00U2p9jM5V');
let checkoutButton = document.getElementById('checkout-button');
console.log(checkoutButton.dataset);
checkoutButton.addEventListener('click', function() {
fetch(`/app/checkout/${checkoutButton.dataset.type}/${checkoutButton.dataset.id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'url': `/app/checkout/${checkoutButton.dataset.type}/${checkoutButton.dataset.id}`,
"X-CSRF-Token": document.querySelector('input[name=_token]').value
},
})
.then(function(response) {
return response.json();
})
.then(function(session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function(result) {
// If `redirectToCheckout` fails due to a browser or network
// error, you should display the localized error message to your
// customer using `error.message`.
if (result.error) {
alert(result.error.message);
}
})
.catch(function(error) {
console.error('Error:', error);
});
});
The route where the id is created
Route::post('/checkout/subscription/{subscription}', [StripeController::class, 'checkoutSubscription']);

Laravel How to reset modal ajax data values upon closing the modal

I am currently working on populating a user's searching for available appointments by selecting a date, start time and end time. I am trying to populate them onto a modal which is currently working. However I realise that whenever I close the modal and search for the new timeslots, the previous data populated on the modal will still be there.
I have tried doing function when I close the modal, the modal data will be cleared.
Below are my html codes for the modal:
<div class="modal fade" id="myModalNewAppointment">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Select Appointment</h4>
</div>
<!-- Modal body -->
<div class="modal-body">
{{-- <form id="test" action="" method="post"> --}}
<div class="form-group">
<label for="modal">Select a Timeslot</label>
<div class="spacer"></div>
<div class="timeslots-section">
<div class="timeslots text-center">
</div> <!-- end timeslots -->
</div>
</div>
{{-- </form> --}}
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="new_appt_cfm_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Confirm</button>
<button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Below is my ajax method to retrieve the timeslots:
$("#find_appointment_btn").click(function(event){
event.preventDefault();
let select_date = $('#select_date').val();
let start_time = $('#start_time').val();
let end_time = $('#end_time').val();
let data = { select_date: select_date, start_time: start_time, end_time: end_time };
$.ajax({
type:"POST",
url: "{{ route('assistant.newappts.get') }}",
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
dataType: "json",
success:function(data){
console.log(data);
if(data == ""){
alert("Clinic is close!");
return;
}
else if(data != ""){
$('#myModalNewAppointment').modal({backdrop: 'static', keyboard: false});
data.forEach(function(dt) {
// do something with `item`
// $(".timeslots").append(dt);
$('.timeslots').append('<input type="checkbox" class="timeslotchk" name="timeslot" value="'+ dt +'"/>' + dt );
});
}
},
error: function(error) {
console.log(error);
}
});
});
Below is the method I have tried to reset the data populated on my modal:
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').reset();
});
When you call the ajax request on the success you have appended the data in model "timeslots" division so its obvious that data will be still there on the hiding model try to empty the timeslots, try below code hope it work for you and make sure that method trigger on closing of model
$("#myModalNewAppointment").on("hidden.bs.modal", function () {
$('#myModalNewAppointment').find(".timeslots").empty();
});

How to Populate HTML with data from jquery (multiple nested div)

I want to Populate elements inside class info-wrapper using JQuery.
Data that has to populate are inside data variable in JQuery.
I can't use $('#id').append("div") like these syntax because i want to nest multiple div inside each other and popluate .card-wrapper and its child elements for every data item.
Jquery
$.ajax({
method: 'GET',
url: 'getUser/admin',
dataType: 'json',
success: function (data) {
console.log(typeof(data));
data = Object.entries(data);
for(var i = 0;i<data.length;i++)
{
}
},
error: function () {
}
})
Blade Template
#extends('layouts.app')
#section('admin-content')
<div class="container">
<div class="row" id="inject">
<div class="col-md-6 col-sm-12">
<div class="card-wrapper">
<div class="info-wrapper">
<h2 id="name"></h2>
<h6 id="email"></h6>
<hr/>
<h6 id="department"></h6>
<h6 is="sem"></h6>
</div>
<div class="button-wrapper">
<button class="btn btn-danger" type="submit">Delete Account</button>
<button class="btn btn-secondary" type="submit">Block Account</button>
</div>
</div>
</div>
</div>
</div>
#endsection
Because info-wrapper is just a single element, you can instead populate elements inside the div with inject id, you can make changes to your js to generate elements dynamically, I hope this can help.
$.ajax({
method: 'GET',
url: 'getUser/admin',
dataType: 'json',
success: function (data) {
console.log(typeof(data));
data = Object.entries(data);
let html = '';
for(var i = 0;i<data.length;i++)
{
html += `
<div class="card-wrapper">
<div class="info-wrapper">
<h2 id="name">${data[i].name}</h2>
<h6 id="email">${data[i].email}</h6>
<hr/>
<h6 id="department">${data[i].department}</h6>
<h6 is="sem"><${data[i].sem}/h6>
</div>
<div class="button-wrapper">
<button class="btn btn-danger" type="submit">Delete Account</button>
<button class="btn btn-secondary" type="submit">Block Account</button>
</div>
</div>
`;
}
html = `<div class="col-md-6 col-sm-12">${html}</div>`
$('#inject').html(html);
},
error: function () {
}
})

How to display data from API inside a bootstrap collapse/modal?

I have a school project about API, and I have problems displaying specific data inside a bootstrap collapse.
I have a school project, where I take data about coins from API server and present it. Every coin is presented in a different div and within that div there is a button. This button is "More Info", and should display more info about that coin, from a link with a specific id, similar to the coin. I managed to present the data from the API server, but couldn't make the button work.
This is the link for the "More Info" button: https://api.coingecko.com/api/v3/coins/{id}
This is the html:
<body>
<div class = "header">
Cryptonite
</div>
<div class="line"></div> </br>
<div class="container">
<div class="navigation">
<div id="buttons">
<button type="button" class="btn btn-link" id="home-btn" onClick="selectTab" name="home">Home</button>
<button type="button" class="btn btn-link" id="live-btn" onClick="selectTab" name="live">Live Reports</button>
<button type="button" class="btn btn-link" id="about-btn" onClick="selectTab" name="about">About</button>
</div>
<div class="search">
<input type="search" placeholder="Search" aria-label="Search through site content"/> <button type="button" class="btn btn-link" id="src-btn" name="src">Search</button>
</div>
</div>
</br>
<div class="coins">
</div>
</div>
</body>
This is the script:
//This is the function to call the data from the API server
function callCoins() {
$.ajax({
url: "https://api.coingecko.com/api/v3/coins/list",
dataType: "json",
success: function(data){
console.log(data);
for(let i=0;i<100;i++){
$(".coins").append(`
<div class="coin">
<span>
<p id="coin-sym">${data[i].symbol}</p>
<p>${data[i].name}</p>
<button class="btn btn-primary" data-toggle="collapse" data-target="#a${data[i].id}">More Info</button>
<div class="collapse" id="a${data[i].id}">example</div>
</span>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="b${data[i].id}">
<label class="custom-control-label" for="#b${data[i].id}"></label>
</div>
</div>
</br>
`)
}
}
})
}
//This is the function for 'More Info'
function moreInfo() {
$.ajax({
url: "https://api.coingecko.com/api/v3/coins/{id}",
dataType: "json",
success: function(data){
$(".collapse").append(`
<div class="moreInfo">
<span>
<p>${data.image.thumb}</p>
</span>
</div>
`)
}
})
}
When I click on "More Info", it should display data from a link with the coin specific id.
Here is a Demo File
Seems like you are not invoking the moreInfo function on click of the button. so your More Info HTML Button has to be like this.
<button class="btn btn-primary" data-toggle="collapse" data-target="#a${data[i].id}" onClick="moreInfo('${data[i].id}')">More Info</button>
and the moreInfo() function to be like this
function moreInfo(id) { /* change 1 - added id parameter*/
$.ajax({
url: "https://api.coingecko.com/api/v3/coins/"+id, /* change 2 - added the id parameter to the api call */
dataType: "json",
success: function(data){
$(".collapse").append(`
<div class="moreInfo">
<span>
<p>${data.image.thumb}</p>
</span>
</div>
`)
}
})
}
Hope this helps. And to Make it appear as an image you have add an image tag inside the p tag and bind the image url into the src attribute.

Categories

Resources