My Node API returns a JSON object, the object is being displayed on HTML table. However, my Node app takes some time to process and return the data. So till the time data has being retrieved I want a spinner to load on the page.
$(document).ready(function() {
$("#table1").hide();
$("#myButton").click(function() {
$("#myButton").hide();
$("#table1").show();
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
data: {
data1: str1,
data2: str2
},
dataType: 'json',
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="spinner" id="loadingBtn">
Loading...
</span>
<table class="table" id="table1">
<tbody>
<tr>
<td id="td1"></td>
</tr>
<tr>
<td id="td2"></td>
</tr>
</tbody>
</table>
How and where do I put the spinner id so that it is only displayed until the data is fully rendered onto the HTML table.
$(document).ready(function() {
$("#table1").hide();
$("#myButton").click(function() {
$("#myButton").hide();
$("#table1").show();
$.ajax({
url: "https://www.mocky.io/v2/5ec78da22f0000640042721f",
type: 'GET',
dataType: 'json',
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
},
beforeSend: function() {
$("#loadingBtn").show();
},
complete: function() {
$("#loadingBtn").hide();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="spinner" id="loadingBtn" style="display:none;">
Loading...
</span>
<button id="myButton">Press</button>
<table class="table" id="table1">
<tbody>
<tr>
<td id="td1"></td>
</tr>
<tr>
<td id="td2"></td>
</tr>
</tbody>
</table>
You can just add the loading spinner on loading and done. Show the spinner on call, and just hide it when the call is done. like so:
$.ajax({
type: 'POST',
success: function(res){
console.log(res);
}
}).done(function() {
setTimeout(function(){
$(".spinner").fadeOut(300);
},500);
});
take a look at this codepen:
https://codepen.io/yic666kr/pen/mxmvbV
It depends on your structure where you have it placed but I'll go with what you have put here. You have it visible when you start loading and hide it once data is loaded from your ajax.
$(document).ready(function() {
$("#table1").hide();
$("#myButton").click(function() {
$("#myButton").hide();
$("#table1").show();
// show the loader when you click the button
$('#loadingBtn').addClass('spinner--is-active')
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
data: {
data1: str1,
data2: str2
},
dataType: 'json',
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
// hide the loader
$('#loadingBtn').removeClass('spinner--is-active')
}
});
});
});
.spinner {
display: none;
}
.spinner--is-active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="spinner" id="loadingBtn">
Loading...
</span>
<table class="table" id="table1">
<tbody>
<tr>
<td id="td1"></td>
</tr>
<tr>
<td id="td2"></td>
</tr>
</tbody>
</table>
Just show your spinner in beforeSend of ajax function and hide it after data is loaded under success function.
$.ajax({
url: "http://localhost:8090/api/route1",
type: 'POST',
data: {
data1: str1,
data2: str2
},
dataType: 'json',
beforeSend: function() {
$("#loadingBtn").show();//show spinner
},
success: function(res) {
console.log(res);
console.log("Result1", res.result1);
console.log("Result2", res.result2);
$('#td1').append(res.result1);
$('#td2').append(res.result2);
$("#loadingBtn").hide();//hide spinner
}
});
Related
I'm new to bootstrap.I'm trying to show confirm message with bootbox format after click on delete btn .I know that bootbox.confirm need callback function so I utilize result and checked if its true then show it.I expect to see this: Are you sure to delete this customer? but after click noting happen and browser just freeze and I have to refresh it again.
this is all my code:
<h2>Customers</h2>
#Html.ActionLink("ADD New Customer", "CreatNewCustomer", "Customer", new { #class = "form-control" })
#if (!Model.Any())
{
<p> there is no customer</p>
}
else
{
<table id="Customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Customers</th>
<th>Discount Rate</th>
<th>Delete </th>
</tr>
</thead>
<tbody>
#foreach (var Customer in Model)
{
<tr>
#*<td>#Customer.Name</td>*#
<td>#Html.ActionLink(Customer.Name.ToString(),"Edit","Customer",new {id=Customer.CustomerID },null)</td>
<td>#Customer.MembershipType.MembershipName</td>
<td>
<button data-customer-id="#Customer.CustomerID" class="btn-link js-delete"> Delete</button>
</td>
</tr>
}
</tbody>
</table>
}
#section scripts
{
<script>
$(document).ready(function () {
$("#Customers .js-delete").on("click", function () {
bootbox.confirm("Are you sure to delete this customer?", function (result) {
if (result) {
var butten = $(this)
$.ajax({
url: "/api/customer/" + butten.attr("data-customer-id"),
method: "Delete",
success: function () {
console.log("success"),
butten.parents("tr").remove();
}
})
}
})
})
})
</script>
}
Main part is here:
<script>
$(document).ready(function () {
$("#Customers .js-delete").on("click", function () {
var butten = $(this);
bootbox.confirm("Are you sure to delete this customer?", function (result) {
if (result) {
$.ajax({
url: "/api/customer/" + butten.attr("data-customer-id"),
method: "Delete",
success: function () {
console.log("success"),
butten.parents("tr").remove();
}
})
}
})
})
})
</script>
I can't get what's wrong with that.
When I use bootbox.confirm my code not works but when I use confirm alon like this:
<script>
$(document).ready(function () {
$("#Customers .js-delete").on("click", function () {
var butten = $(this);
confirm("Are you sure to delete this customer?", function (result) {
if (result) {
$.ajax({
url: "/api/customer/" + butten.attr("data-customer-id"),
method: "Delete",
success: function () {
console.log("success"),
butten.parents("tr").remove();
}
})
}
})
})
})
</script>
my code works. I have installed bootbox version 4.3.0 and set in my bundle config like this :
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/bootbox.js",
"~/Scripts/respond.js"));
And I use vs 2017
Hope someone help me.
If you're trying to get a reference to the button that triggered the click event, you (still) are selecting the wrong item when doing this:
$(document).ready(function () {
var butten = $(this);
Where you have that line in your latest edit, you're selecting the document. What you need is:
$("#Customers .js-delete").on("click", function () {
// THIS is where you select the button...
var butten = $(this);
// ... the rest of your code
}
If you're struggling with this, I suggest spending some time on the jQuery Learning Center: https://learn.jquery.com/
I'm trying to fill a table based on the selected tab, I'm using JQuery-UI tabs library with ajax, the problem is that only the last function
$('#tabs, #tab-4').tabs()
is working (Actually all functions are executed but I can see only the last one), therefore it only brings the information from the last tab. I'm not sure if i'm doing the things right.
<ul id="tabs">
<li>Abiertos</li>
<li>Solucionados</li>
<li>Cerrados</li>
<li>Cancelados</li>
</ul>
<div class="containerTab" id="tab-1">
<table class="table table-striped" id="records_table">
<thead>
<tr>
<th class="text-center">Id</th>
<th class="text-center">Cliente</th>
<th class="text-center">Producto</th>
<th class="text-center">Descripción</th>
<th class="text-center">Fecha</th>
<th class="text-center">Incidente</th>
<th class="text-center">Operación</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
</div>
<div class="containerTab" id="tab-4">
<table class="table table-striped" id="records_table4">
<thead>
<tr>
<th class="text-center">Id</th>
<th class="text-center">Cliente</th>
<th class="text-center">Producto</th>
<th class="text-center">Descripción</th>
<th class="text-center">Fecha</th>
<th class="text-center">Incidente</th>
<th class="text-center">Cancelado por</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
</div>
This is my script section (I removed tab-2 and tab-3 for the sake of not making it longer)
$('#tabs, #tab-1').tabs({
activate: function (event, ui) {
$("#records_table tbody tr").remove();
$.ajax({
type: "POST",
url: "/Servicios/GetIncidentes",
contentType: "application/json; charset=utf-8",
data: "{'incidente':'Abiertos'}",
dataType: "json",
success: function (response) {
$(function () {
$.each(response, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.Id).addClass('text-center'),
$('<td>').text(item.Cliente).addClass('text-center'),
$('<td>').text(item.Producto).addClass('text-center'),
$('<td>').text(item.Descripcion).addClass('text-center'),
$('<td>').text(item.Fecha).addClass('text-center'),
$('<td>').text(item.Incidente).addClass('text-center'),
$('<td>').text('').addClass('text-center').prepend($('<i />', { 'class': 'fa fa-eye' }))
).appendTo('#records_table');
});
});
},
error: function (ts) { alert(ts.responseText) }
})
}
});
$('#tabs, #tab-4').tabs({
activate: function (event, ui) {
$("#records_table4 tbody tr").remove();
$.ajax({
type: "POST",
url: "/Servicios/GetIncidentes",
contentType: "application/json; charset=utf-8",
data: "{'incidente':'Cancelados'}",
dataType: "json",
success: function (response) {
$(function () {
$.each(response, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.Id).addClass('text-center'),
$('<td>').text(item.Cliente).addClass('text-center'),
$('<td>').text(item.Producto).addClass('text-center'),
$('<td>').text(item.Descripcion).addClass('text-center'),
$('<td>').text(item.Fecha).addClass('text-center'),
$('<td>').text(item.Incidente).addClass('text-center'),
$('<td>').text('').addClass('text-center').prepend($('<i />', { 'class': 'fa fa-eye' }))
).appendTo('#records_table4 tbody');
});
});
},
error: function (ts) { alert(ts.responseText) }
})
}
});
The GetIncidentes method recieves a string (string incidente) and returns a parsed Json list.
I have a form and ajax.
I can't send with $(form).serialize();
How do I send the button value with the form?
html:
<form action="" id="ogrenci_arama_formu">
<input type="text" id="eposta" name="eposta">
<button id="ogrenci_ara" name="ogrenci_ara" value="true" class="btn btn-info">Öğrenciyi Ara</button>
<!--<input id="ogrenci_ara" type="hidden" name="ogrenci_ara" value="true">-->
</form>
ajax:
$("#ogrenci_arama_formu").submit(function (e) {
e.preventDefault();
console.log("form: ",$(this).serialize());
$.ajax({
url: "sayfalar/ogrenci_bilgileri.php",
type: 'post',
/*dataType: 'json',*/
data: $(this).serialize()
}).done(function(data) {
$("tbody").html(data);
}).fail(function(data) {
console.log("error",data);
});
});
output:
eposta=
try like store button value into a variable and send with form serialize like this
JAVASCRIPT-
$("#ogrenci_arama_formu").submit(function(e) {
e.preventDefault();
var btnValue = $(this).find('#ogrenci_ara').val();
console.log("form: ", $(this).serialize()+'&ogrenci_ara='+btnValue);
$.ajax({
url: "sayfalar/ogrenci_bilgileri.php",
type: 'post',
/*dataType: 'json',*/
data: $(this).serialize()+'&ogrenci_ara='+btnValue
}).done(function(data) {
$("tbody").html(data);
}).fail(function(data) {
console.log("error", data);
});
});
I created 3 dependent select boxes in Laravel with Ajax (a reproduction of the code from the original project in wich I use MySQL instead of array): https://github.com/grigore16/laravel_select_boxes. It has only one view and one controller.
It generally works fine, but if I refresh multiple times, I get 500 Internal Server Error (in Chrome's console) and from jQuery I see the error is: xhr.send( options.hasContent && options.data || null ). In a slower computer the error is more often.
Please tell me if the code is ok or not!
This is the view:
<table class='table table-bordered'>
<tr>
<td>Country</td>
<td>City</td>
<td>Street</td>
</tr>
<tr>
<td>
<select id="country" name="country">
<option selected>Germany</option>
</select>
</td>
<td>
<select id="city" name="city">
<option selected>Hamburg</option>
</select>
</td>
<td>
<select id="street" name="street">
<option selected>h1</option>
</select>
</td>
</tr>
</table>
<div>
<script>
var present_country = 'Germany';
var present_city = 'Hamburg';
var present_street = 'h1';
$(document).ready(function(){
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {countries:'test'},
success: function (data) {
$(data.countries).each(function(index, country) {
if(country !== present_country){
$("#country").append(new Option(country));
}
});
var country = $('#country').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {country:country},
success: function (data) {
$(data.cities).each(function(index, city) {
if(city !== present_city){
$("#city").append(new Option(city));
}
});
var city = $('#city').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {city:city},
success: function (data) {
$(data.streets).each(function(index, street) {
if(street !== present_street){
$("#street").append(new Option(street));
}
});
}
});
}
});
}
});
$("#country").change(function() {
$('#city').empty();
$('#street').empty();
var country = $('#country').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {country:country},
success: function (data) {
$(data.cities).each(function(index, city) {
$("#city").append(new Option(city));
});
var city = $('#city').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {city:city},
success: function (data) {
$(data.streets).each(function(index, street) {
$("#street").append(new Option(street));
});
}
});
}
});
});
$("#city").change(function() {
$('#street').empty();
var city = $('#city').val();
$.ajax({
url: 'http://localhost/laravel_select_boxes/public/ajax',
method: "GET",
data: {city:city},
success: function (data) {
$(data.streets).each(function(index, street) {
$("#street").append(new Option(street));
});
}
});
});
});
</script>
and this is the controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AjaxController extends Controller
{
public function index(Request $request)
{
if($request['countries']){
$countries = ['Germany', 'France'];
return response()->json(['countries'=>$countries]);
}
if($request['country']){
if($request['country'] === 'Germany'){
$cities = ['Hamburg', 'Berlin'];
}
if($request['country'] === 'France'){
$cities = ['Paris', 'Lion'];
}
return response()->json(['cities'=>$cities]);
}
if($request['city']){
if($request['city'] === 'Hamburg'){
$streets = ['h1', 'h2', 'h3'];
}
if($request['city'] === 'Berlin'){
$streets = ['b1', 'b2', 'b3'];
}
if($request['city'] === 'Paris'){
$streets = ['p1', 'p2', 'p3'];
}
if($request['city'] === 'Lion'){
$streets = ['l1', 'l2', 'l3'];
}
return response()->json(['streets'=>$streets]);
}
}
}
Thank you very much!
I'm using Ajax to load data.
With help of jQuery jTemplates I load data within Container. I need to apply jqtip plugin to images withing Container, but for some reason it's not working. if it outside works fine.
Any idea why it's not working? maybe give me an idea how I can debug it?
Here is my code
$.ajax({
type: "POST",
url: "/json/default.aspx/loaditems",
data: "{'parameter':'" + parameter + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
ApplyTemplate(msg);
}
});
function ApplyTemplate(msg) {
$('#Container').setTemplateURL('/scripts/template.htm', null, { filter_data: true });
$('#Container').processTemplate(msg);
}
<div id="Container">
</div>
here is content of my template.htm page
{#foreach $T.d as post}
<div class="image_wrap" style="float: left;">
<a href="{$T.post.url}">
<img width="175" src="{$T.post.profimage}" title="test" /></a>
</div>
{#/for}
here is qtip code
<script type="text/javascript">
$(function () {
$('.image_wrap img[title]').qtip({
position: {
corner: {
target: 'topMiddle',
tooltip: 'bottomMiddle'
}
},
style: {
name: 'cream',
padding: '7px 13px',
color: '#350608',
width: {
max: 250,
min: 0
},
tip: true
}
});
});
</script>
You're running your qtip logic on $(document).ready(). The problem is that because you're loading new markup after the page has loaded, the qtip logic doesn't apply to it.
Try wrapping your qtip logic inside a function, then call the function after you run your AJAX call.
Something like this:
function InitQtip() {
$('.image_wrap img[title]').qtip({
position: {
corner: {
target: 'topMiddle',
tooltip: 'bottomMiddle'
}
},
style: {
name: 'cream',
padding: '7px 13px',
color: '#350608',
width: {
max: 250,
min: 0
},
tip: true
}
});
}
// This will take care of items loaded with the page.
$(function () {
InitQtip();
}
// This will take care of new items.
$.ajax({
type: "POST",
url: "/json/default.aspx/loaditems",
data: "{'parameter':'" + parameter + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
ApplyTemplate(msg);
InitQtip();
}
});