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

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 () {
}
})

Related

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();
});

Issues integrating response from OpenWeatherMap in to my HTML

I'm using the OpenWeatherMap API to get to display certain items in HTML and my code does not display them.
$('.`btn`').click(function() {
var city = $('.inputValue').val();
var key = '88da1611665dfe9338cd6679dee95466';
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather',
dataType: 'json',
type: 'GET',
data: {
q: city,
appid: key,
units: 'metric'
},
success: function(data) {
var temp = '';
$.each(data.weather, function(index, val) {
wf += '<p><b>' + data.name + "</b><img src=" + val.icon + ".png></p>" +
data.main.temp + '°F ' + ' | ' + val.main + ", " +
val.humidity + val.wind + val.uv
}, $("showWeather").html(temp));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="4">
<nav class="navbar navbar-light bg-light">
<p><b>Search for a city:</p></b>
<form class="d-flex">
<input type="search" class="inputValue" placeholder="" aria-label="Search">
<button class="btn btn-outline-success">
<i class="fas fa-search"></i>
</button>
</form>
</nav>
</div>
</div>
<div class="col-8">
<div class="row">
<h2 id="showWeather" class="date"></h2>
<p>Temperature:</p>
<p>Humidity:</p>
<p>Wind Speed:</p>
<p>UV Index:</p>
</div>
</div>
</div>
There's quite a few individual issues in your code:
You have backticks in the .btn selector which are invalid, remove them.
You need to prevent the standard form submission so that the AJAX call can fire and return data without the page refreshing. To do this call preventDefault() on the event which is fired, ideally on the submit of the form, not click of .btn.
</p></b> tags are the wrong way around
.html(temp) needs to be placed outside the each(), and definitely not as an additional argument passed to it
wf += should be temp += as that's what your variable is called
You can use map() along with template literals to build the HTML string more succinctly.
You're missing the # on $('showWeather')
wind is an object so you can't concatenate it to the string directly. Access its speed or deg properties (or both).
humidity is a property of main, not the weather you're looping through
There is no uv property anywhere in the response, so that needs to be removed.
With all that fixed, try this:
$('.d-flex').on('submit', function(e) {
e.preventDefault();
var city = $('.inputValue').val();
var key = '88da1611665dfe9338cd6679dee95466';
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather',
dataType: 'json',
type: 'GET',
data: {
q: city,
appid: key,
units: 'metric'
},
success: function(data) {
let html = data.weather.map(loc => `<p><b>${data.name}</b><img src="${loc.icon}.png" /></p>${data.main.temp}°F | ${loc.main}, ${data.main.humidity}%, ${data.wind.speed}kph # ${data.wind.deg}°`);
$("#showWeather").html(html);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="4">
<nav class="navbar navbar-light bg-light">
<p><b>Search for a city:</b></p>
<form class="d-flex">
<input type="search" class="inputValue" placeholder="" aria-label="Search" value="miami">
<button class="btn btn-outline-success">
Search
<i class="fas fa-search"></i>
</button>
</form>
</nav>
</div>
</div>
<div class="col-8">
<div class="row">
<h2 id="showWeather" class="date"></h2>
<p>Temperature:</p>
<p>Humidity:</p>
<p>Wind Speed:</p>
<p>UV Index:</p>
</div>
</div>
</div>

Laravel 5.8 : Why $request->hasFile returns false

I sent a file from HTML to my controller and var_dump my file in the controller but the return result is false.
var_dump($request->hasFile('logo')
If I use HTML to execute it the results will it be true? If I use Ajax the results are false. Here is a simple file input:
<section class="section bg-img" id="section-contact" style="background-image: url({{ asset('front/img/bg-cup.jpg') }})" data-overlay="8">
<div class="container">
<div class="row gap-y">
<div class="col-12 col-md-6 offset-md-3 form-section">
{!! Form::open(['id'=>'confirmation','class'=>'row', 'method'=>'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="col-12 col-md-10 bg-white px-30 py-45 rounded">
<p id="alert"></p>
<div id="form-box">
<div>
<span class="btn btn-info btn-file">
<input type="file" name="logo" id="logo"> </span>
</div>
<div class="col-md-12">
<button class="btn btn-lg btn-block btn-primary" type="button" id="save-form">SignUp</button>
</div>
</div>
</div>
{{!! Form::close() !!}
/div>
</div>
</div>
</section>
and here is my Ajax
<script>
$('#save-form').click(function () {
$.easyAjax({
url: '{{route('front.confirmation',$confirm->billing_number)}}',
container: '.form-section',
enctype: 'multipart/form-data',
type: "POST",
data: $('#confirmation').serialize(),
messagePosition: "inline",
success: function (response) {
if(response.status == 'success'){
$('#form-box').remove();
}
}
})});</script>
and this my controller :
public function update(Request $request, $billing){
$confirm = PaymentConfirmation::where('billing_number',$billing)->first();
var_dump($request->hasFile('logo')); //Here is return false
if ($request->hasFile('logo')) {
$confirm->invoice =$request->logo->hashName();
$request->logo->store('user-uploads/invoice');
}
$confirm->save();
return Reply::success('Thank you for upload.') }
Thanks for advance ^-^
Data from file inputs is not serialized by the jquery .serialize() method, so the file is truly not getting sent back to the server
To upload files, use FormData() instead
$('#save-form').click(function() {
$.easyAjax({
url: '{{route('front.confirmation ',$confirm->billing_number)}}',
container: '.form-section',
enctype: 'multipart/form-data',
type: "POST",
data: new FormData($('#confirmation')),
messagePosition: "inline",
success: function(response) {
if (response.status == 'success') {
$('#form-box').remove();
}
}
})
});

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.

Alpacajs form data not submitting if user does not tab off textbox

I am having an issue with alpacajs form not submitting data from a textbox if the user does not tab off the textbox before clicking the submit button, if the user has 5 fields to fill out all but the last one is included in the json results.
<div class="panel-group" id="accordian" role="tablist">
<div class="panel-placeholder"></div>
</div>
<div>
<button class="btn btn-default" type="submit">Submit</button>
</div>
<script id="panel-template" type="text/x-handlebars-template">
{{#each panels}}
<div class="panel panel-primary">
<div class="panel-heading">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#{{panelId}}">
{{title}}
</a>
</h4>
</div>
<div id="{{panelId}}" class="panel-collapse collapse in">
<div class="panel-body">
{{#each sections}}
<div id={{formId}}></div>
{{/each}}
</div>
</div>
</div>
{{/each}}
</script>
and the js code
function onData(formData) {
var friendlyData = "";
// Grab the template script
var templateScript = $("#panel-template").html();
// Compile the template
var compiledTemplate = Handlebars.compile(templateScript);
var compiledHtml = compiledTemplate(formData);
// Add the compiled html to the page
$('.panel-placeholder').html(compiledHtml);
//submit all data
$("[type='submit']").click(function () {
var postData = {
data: JSON.stringify(formData),
friendlyData: friendlyData,
storeData: storeData,
origUrl: origUrl
}
$.ajax({
url: apiUrl + "submit/",
data: postData,
dataType: 'json',
type: 'POST',
success: function (data) {
alert("Data was saved");
},
error: function (err) {
alert(err.statusText);
}
});
});
}
Any help with this would be great, I have not been able to find a solution.
Thank you

Categories

Resources