I get some data by json, and there is small issue.
When I choose some data it returns result to me, but when I choose another data it keeps old result and add new result into it. What I want is to clear old results on new selected data.
Preview of my issue
My JavaScript code:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
console.log();
$('#info').append('<h3>'+ value['code'] + '<small>' + value['name'] +'</small></h3>');
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value2['service'] + ' - ' + value3['value'] + ' - ' + value3['etd'] +'</option>');
});
});
});
}
});
}else{
console.log(data);
}
});
});
</script>
My HTML Code:
<div id="calcul" style="margin-top: 30px;">
<div id="des"></div>
<dev id="info"></dev>
<select name="postchoose" id="">
<option class="form-control" value="">Select Shiping Method</option>
</select>
</div>
user .empty() method before appending the new data,
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
$('#info').empty();
$('select[name="postchoose"]').empty();
$('#info').append('<h3>'+ value['code'] + '<small>' + value['name'] +'</small></h3>');
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value2['service'] + ' - ' + value3['value'] + ' - ' + value3['etd'] +'</option>');
});
});
});
}
});
}else{
console.log(data);
}
});
});
</script>
Related
I'm currently working on a code that displays users activity log. Ajax will call the route and gets the response (json) results. I need to be able to display the log records on admin dashboard without refreshing the page.
Ajax
$(document).ready(function() {
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
},error:function(){
console.log(data);
}
});
});
If I understood, you can do this:
$(document).ready(function() {
var requesting = false;
var request = function() {
requesting = true;
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
requesting = false;
});
});
},error:function(){
console.log(data);
}
});
};
if(!requesting){
setTimeout(request, 1000);
}
});
Every seconds it does a request to your users.activity route, so there is an update every second.
You need to send last record id in server. so you can get only new data.
my updated answer based on #stackedo answer .
$(document).ready(function () {
var lastId = 0; //Set id to 0 so you will get all records on page load.
var request = function () {
$.ajax({
type: 'get',
url: "{{ route('users.activity') }}",
data: { id: lastId }, //Add request data
dataType: 'json',
success: function (data) {
$.each(data, function () {
$.each(this, function (index, value) {
console.log(value);
lastId = value.id; //Change lastId when we get responce from ajax
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
}, error: function () {
console.log(data);
}
});
};
setInterval(request, 1000);
});
In controller add were condition to query :
UserActivity::where('id','>',$request->id)->get();
I have this code in my javascript:
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option>');
I need value['code'] and value2['service'] in hidden inputs so i can save them in my DB, is that possible?
update
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
html
<div id="des"></div>
<div id="calcul" class="mb-20 mt-20">
<select name="postchoose" id="">
<option class="form-control" value="">Select Shiping Method</option>
</select>
<div id="courierinfo"></div> // i want my hidden input in this div
</div>
update 2
here is what i added to my ajax code and returning the result i want, but the problem is it return results like 30 times instead of only once:
$('select[name="postchoose"]').on('change',function(){
var selected = $(this).find('option:selected');
var code = selected.data('code');
var service = selected.data('service');
$('div#courierinfo').append('<input type="hidden" value="'+code+'" name="courier" > <input type="hidden" value="'+service+'" name="courier_service" >');
});
Hope this helps.
$('select[name="postchoose"]').append('<option id="postchoose"
class="form-control" value="'+ value3['value'] +'"
code="'+value['code']+'" service="'+value2['service']+'">'+
value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number)
+' Rp' + ' - ' + value3['etd'] +'</option>');
var code=$('select[name="postchoose"] option:selected').attr('code');
var service=$('select[name="postchoose"]
option:selected').attr('service');
You can add to data attribute of option
<div id="des"></div>
<div id="calcul" class="mb-20 mt-20">
<select name="postchoose" id="" onchange="addInputHidden(this)">
<option class="form-control" value="">Select Shiping Method</option>
</select>
<div id="courierinfo">
<!--i want my hidden input in this div-->
</div>
</div>
<script >
function addInputHidden(element) {
var $option = $(element).find('option:selected'),
code = $option.data('code'),
service = $option.data('service');
if (!jQuery('#courierinfo .code_' + code).length) {
jQuery('#courierinfo').append('<input class="code code_' + code + '" name="code[]" type="hidden" value="' + code + '"><input class="service code_' + code + '" name="service[]" type="hidden" value="' + service + '">');
} else {
jQuery('#courierinfo .code.code_' + code).val(code)
jQuery('#courierinfo .service.code_' + code).val(service)
}
}
jQuery(document).ready(function ($) {
$('body').on('change', 'select[name="city"]', function (e) {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if (cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/' + weight + '/' + encodeURI(cityID),
type: "GET",
dataType: "json",
success: function (data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] + '</p>'
);
$.each(data.data, function (key, value) {
$.each(value.costs, function (key2, value2) {
$.each(value2.cost, function (key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits: 0,
minimumFractionDigits: 0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="' + value3['value'] + '" data-code="' + value['code'] + '" data-code="' + value2['service'] + '">' + value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] + '</option>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
} else {
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
$('select[name="postchoose"]').on('change',function(){
var $option = $(this).find('option:selected),
code = $option.data('code'),
service = $option.data('service');
// you can use ajax to send
})
SOLVED
I added code below at the bottom of my ajax and it's working without looping results many times.
// show selected shipping information
$('select[name="postchoose"]').on('change',function(){
var selected = $(this).find('option:selected');
var code = selected.data('code');
var service = selected.data('service');
$('div#courierinfo').empty();
$('div#courierinfo').append('Shipping: <span name="courier">'+code+'</span> - <span name="courier_service">'+service+'</span><br><input type="hidden" name="courier" value="'+code+'"><input type="hidden" name="courier_service" value="'+service+'">');
});
Thanks to Bai Nguyen for the idea.
I would like to create a table with the the JSON data I retrieved from my API, but jQuery keeps putting elements in the wrong place....
This is my jQuery code:
var container = $("#container");
var table = $("#table");
$(document).ready(function() {
callAPI();
});
function callAPI() {
$.ajax({
url: "action-api.php",
method: "GET",
dataType: 'json',
success: function(data) {
console.log(data);
container.append('<table style="width:100%"><tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>');
$.each(data, function(i, item) {
container.append('<tr><td>' + item.id + '</td>');
container.append('<td>' + item.naam + '</td>');
container.append('<td>' + item.brouwerij + '</td>');
container.append('<td>' + item.type + '</td>');
container.append('<td>' + item.gisting + '</td>');
container.append('<td>' + item.perc + '</td>');
container.append('<td>' + item.inkoop_prijs + '</td></tr>');
});
container.append('</table>');
},
});
}
This is the HTML output:
You've to create the table and the row tr separated of the td, else they will be closed automatically after the append, for example when you do :
container.append('<tr><td>' + item.id + '</td>');
The output will be :
<tr><td>item.id</td></tr>
____________________^^^^^ //NOTE the closed tag will be added automatically
So you have just to separate them like :
var table = $('<table style="width:100%"></table>');
table.append('<tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>');
$.each(data, function(i, item) {
var tr = $('<tr/>');
tr.append('<td>' + item.id + '</td>');
tr.append('<td>' + item.naam + '</td>');
tr.append('<td>' + item.brouwerij + '</td>');
tr.append('<td>' + item.type + '</td>');
tr.append('<td>' + item.gisting + '</td>');
tr.append('<td>' + item.perc + '</td>');
tr.append('<td>' + item.inkoop_prijs + '</td>');
table.append(tr);
});
container.append(table);
Hope this helps.
Or you can just create your whole bloc and then append it :
var container = $("#container");
var table = $("#table");
$(document).ready(function() {
callAPI();
});
function callAPI() {
$.ajax({
url: "action-api.php",
method: "GET",
dataType: 'json',
success: function(data) {
console.log(data);
var html = '<table style="width:100%"><tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>';
$.each(data, function(i, item) {
html+='<tr><td>' + item.id + '</td>';
html+='<td>' + item.naam + '</td>';
html+='<td>' + item.brouwerij + '</td>';
...
});
html+='</table>';
container.append(html);
},
});
}
Here is the explanation for this: How do I force jQuery append to NOT automatically close a tag?
How can I get the value from an input field when I click the button using jquery?
Below is my Jquery code :
asset_status_list = '';
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>operations/asset_status",
dataType: "JSON",
success: function (response) {
for (i = 0; i < response.length; i++) {
asset_status_list = '<tr><td >' + response[i].job_card_no + '</td><td >' + response[i].number + '</td><td>' + response[i].type + '</td><td ><input type="text" name="view_more_id" class="view_more_id' + response[i].asset_id + ' btn btn-default" id="view_more_id" value="' + response[i].asset_id + '"/><button id="view_more_link" class="view_more_link' + response[i].asset_id + '"><i class="glyphicon glyphicon-zoom-in "></i>View More</button></td></tr>';
$('#asset_status_tr').append(asset_status_list);
$("#asset_status_tr").on("click", ".view_more_link" + response[i].asset_id, function () {
console.log(response);
var asset_id = this.value;
alert(asset_id);
});
}
$('#asset_table_status').DataTable({});
},
error: function (response) {
}
});
I want to get the value of the input field name view_more_id .
Is this the answer you are looking for ? var asset_id = $( "#view_more_id" ).val();
I am receiving a console error saying this..
Uncaught SyntaxError: Unexpected token +
It is saying for line 929, but when I click on the error, it shows highlighted that the error is coming from the closing line of all of this javascript. What could be the issue in this? There isn't even a + symbol in this line?
Does anyone see what is wrong?
<script>
jQuery(document).ready(function () {
$('.panel_out input').on('click', function () {
var id_to_show = '#' + this.id.replace('_button', '');
$(id_to_show).show().siblings().hide();
});//.first().trigger('click');
$('#dashboard_welcome').siblings().hide();
//For the arrow in panel
$("input.arrowBtn").click(function(){
$(this).siblings('.arrow-left').remove();
$("<div class='arrow-left'></div>").insertAfter($(this));
});
//For tabs to stay active
$('.panel_buttons').click(function(){
$('.panel_buttons').css("background-color","#707070");
$(this).css("background-color","#000"); })
});
//For User Rankings - wins/losses
$(document).ready(function(){
$("#member").on("change", function(){
$user = this.value;
$.ajax({
url: "show_user_rankings.php",
type: "POST",
data: "username="+$user,
success: function(text){
if(text == "Error!"){
alert("Unable to get user info!");
} else {
var txtArr = text.split('|');
//0: Contains wins
//1: Contains losses
$("#wins").val(txtArr[0]);
$("#losses").val(txtArr[1]);
}
},
error: function(xhr, textStatus, errorThrown){
alert(textStatus + "|" + errorThrown);
}
});
});
});
//For divisions
$(document).ready(function(){
$("#member_division").on("change", function(){
$user = this.value;
$.ajax({
url: "show_division.php",
type: "POST",
data: "username="+$user,
success: function(text){
if(text == "Error!"){
alert("Unable to get user info!");
} else {
var txtArr = text.split('|');
//0: Contains current division
//1: Contains losses
$("#current_division").val(txtArr[0]);
//$("#losses").val(txtArr[1]);
}
},
error: function(xhr, textStatus, errorThrown){
alert(textStatus + "|" + errorThrown);
}
});
});
});
//For Announcements
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
// "user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
//Shuffle
var displayResults = function(data){
var i = 0;
var lineheight = 24;
var time = 3000;
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
$('#results').append('<div class="result">' +
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
var $this = $('.shuffle_results:last');
$this.show().animate({
'left': 0 + 'px',
'bottom': + '0px'
//$(document).height() - (lineheight * data.length)
}, {
duration: time
});
i++;
} else {
clearInterval(interval);
}
}, 3000);
};
$(function(){
$('form[name="form"]').on('submit', function(e){
e.preventDefault();
$.post('shuffle_results.php', function(data){
var o = $.parseJSON(data);
displayResults(o);
});
});
});
//End Shuffle
//Owes tables
$(function() {
$( "#paid, #partially_paid, #owes" ).sortable({
connectWith: ".tdPayment",
remove: function(e, ui) {
var $this = $(this);
var childs = $this.find('div');
if (childs.length === 0) {
$this.text("Nothing");
}
},
receive: function(e, ui) {
$(this).contents().filter(function() {
return this.nodeType == 3; //Node.TEXT_NODE
}).remove();
},
}).disableSelection();
});
//End Owes Table
</script>
Here, in your animate code:
'bottom': + '0px'
Take away the + and it should be OK.