i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});
Related
I have two files fetch.php and index.php. The fetch.php file does a search and converts the results to Json.
Index.php has Jquery which loops through the Json result. One of the cells contains a URL. How can I get a user to redirect to the URL.
//index.php==============================
<script>
$(document).ready(function(){
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<hr>';
html += '<tr>';
html += '<div>'+data[count].title+'</div>';
html += '<td>'+data[count].book+'</td><tr/>';
html += '<br/><td>'+data[count].description+'</td><tr/>';
html += '<td><button> VIEW </button> '+data[count].url+'</td>'; //Is there a way to redirect to this URL by clicking on the VIEW button
html += '<hr>';
}
}
else
{
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#search_id').val();
load_data(query);
});
</script>
Simple solution:
html += '<td><button onclick="window.location.href=\''+data[count].url+'\'"> VIEW </button> '+data[count].url+'</td>';
Consider the following suggestions:
$(function() {
function load_data(q) {
$.ajax({
url: "fetch.php",
method: "POST",
data: {
query: q
},
dataType: "json",
success: function(data) {
$('#total_records').text(data.length);
var row;
if (data.length > 0) {
$.each(data, function(k, d) {
row = $("<tr>");
$("<td>").html(d.title).appendTo(row);
$("<td>").html(d.book).appendTo(row);
$("<td>").html(d.description).appendTo(row);
var e = $("<td>").appendTo(row);
$("<button>").html("VIEW").click(function(e) {
window.location.href = d.url;
}).appendTo(e);
});
} else {
row = $("<tr>");
$("<td>", {
colspan: 4
}).html("No Results Found.").appendTo(row);
}
}
});
}
$('#search').click(function() {
var query = $('#search_id').val();
load_data(query);
});
});
As you can see, this makes use of a few more jQuery parts to help slimline your code. Additionally, we create a Click event callback when the button is created and added to the table.
You had a lot of improper HTML Syntax. My example does not replicate that. A Row Element should contain Cells and not other elements. Yes, you can do it, yet it's not good practice. This is why I removed them. If they are needed for some reason, you should provide a more complete example so it's clear why they are needed.
For my course purpose I want to create a dynamic data table using ajax. Here's my Javascript code:
$("#submitcateg").click(function(){
var categ = $("#addcategname").val();
$.ajax({
type: "POST",
url: "ProcatServlet",
data: {"categ":categ, "id":"addcateg"},
success: function(data){
if(data=="true"){
$("#addcategname").hide();
$("#submitcateg").hide();
$("#categtable").show(function(){
$.ajax({
type: "GET",
url: "ProcatServlet",
data: {"id":"getcateg"},
success: function(responseJson) {
if(responseJson!=null) {
$("#categtable").find("tr:gt(0)").remove();
var tablebody = document.getElementById("categtable").getElementsByTagName("tbody");
$.each(responseJson, function(key, value){
var button = document.createElement("input");
button.type="button";
button.id="edit";
button.value="edit";
var rowNew = $("<tr><td></td><td></td></tr>");
rowNew.children().eq(0).text(value);
rowNew.children().eq(1).append(button);
rowNew.appendTo(tablebody);
});
}
}
});
});
$("#addcategtrigger").show();
} else {
alert("failed");
}
}
});
});
Using this code, I can show the data and assigned it to the table perfectly, but when I'm trying to add a button to the next column on the row, the button didn't appear. Please help me where I'm doing it wrong.
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
I want to check domain availability with php and ajax request. Requests will be sent to "whois.apitruck.com" API like this: "whois.apitruck.com/domain.com".
For each domain, a request is sent. I want to append table after complate all ajax request but this not work!
$(document).ready(function () {
$("#submit").click(function () {
var domain = $('#domains').val().split("\n");
var all_suffix = ["com","net","org","ir","biz","info","us","name","pro","eu","in","me","tv","cc"];
var counter = 0;
var TableDataString = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
var domain_count = domain.length;
$.each(domain, function (i, val) {
//increase i counter
counter++;
TableDataString += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]:checkbox:checked').each(function () {
var flag = '';
var suffix = $(this).val();
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: val, suffix: suffix},
success: function (msg) {
flag = msg.suc;
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});//end $.ajax
if(flag){TableDataString += '<td><i class="fa fa-times"></i></td>';}else{TableDataString += '<td><i class="fa fa-check"></i></td>';}
});//end get each suffix
TableDataString += '</tr>';
});//end each domain
TableDataString += '</tbody></table>';
if(counter === domain_count){
$(document).ajaxComplete(function(){
$('#domain_tables').append(TableDataString);
});
}
});
});
I am used a flag and check this after $.ajax. The display problem solved. But for each ajax request echo a new table, If that display one table for all ajax request. How to append table after complate all ajax request?! Another problem is that check flag does not work properly! why?!
You're using .append() on your $('#domain_tables'), so that each time a new table is generated. You should empty the #domain_tables div before making another AJAX request(s) queue.
You're not checking which check-boxes are checked and which are not, so that you only create <td> elements for chechbox:checked.
Even if you add all necessary <td> elements, these generated in AJAX success callback will be added at the end of the table, because your loop runs faster than AJAX request (simply saying). You have to state which <td> element belong to which AJAX request.
I'd go this way:
$(document).ready(function () {
$("#submit").click(function () {
// check if anything is selected:
if(!$('#domains').val() || !$('[type="checkbox"]:checked').length){
return false;
}
// disable the button:
var btn = $(this).prop('disabled', true);
var domain = $('#domains').val().split("\n");
var counter = 0;
// an indicator to state when the button should be enabled again:
var ajaxQueue = 0;
var Table = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.Eu</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
// create the td elements, but do not perform AJAX requests there:
$.each(domain, function (i, val) {
counter++;
Table += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')){
ajaxQueue++;
// if checkbox is checked make td element with specified values and a "load-me" class:
Table += '<td class="load-me" data-domain="'+val+'" data-suffix="'+$(this).val()+'"><small>loading...</small></td>';
}else{
Table += '<td><span class=text-muted><i class="fa fa-minus"></i></span></td>';
}
});
Table += '</tr>';
});
// Replace HTML of the 'domain_tables' div and perform AJAX request for each td element with "load-me" class:
$('#domain_tables').html(Table+'</tbody></table>').find('td.load-me').each(function(){
var td = $(this);
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: td.attr('data-domain'), suffix: td.attr('data-suffix')},
success: function (msg) {
// decrease ajaxQueue and if it's 0 enable button again:
ajaxQueue--
if(ajaxQueue === 0){
btn.prop('disabled', false);
}
if(msg.suc == false){
td.html('<span class=text-danger><i class="fa fa-times"></i></span>');
}else{
td.html('<span class=text-success><i class="fa fa-check"></i></span>');
}
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});
});
});
});
My final answer is look like this:
$(document).ready(function () {
$("#submit").click(function () {
var domain = $('#domains').val().split("\n");
var all_suffix = ["com","net","org","ir","biz","info","us","name","pro","eu","in","me","tv","cc"];
var counter = 0;
var TableDataString = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
var domain_count = domain.length;
$.each(domain, function (i, val) {
//increase i counter
counter++;
TableDataString += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]:checkbox:checked').each(function () {
var flag = false;
var suffix = $(this).val();
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: val, suffix: suffix},
success: function (msg) {
flag = msg.suc;
if(flag){TableDataString += '<td><i class="fa fa-times"></i></td>';}else{TableDataString += '<td><i class="fa fa-check"></i></td>';}
TableDataString += '</tr>';
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});//end $.ajax
});//end get each suffix
});//end each domain
if(counter === domain_count){
TableDataString += '</tbody></table>';
$('#domain_tables').append(TableDataString);
}
});
});
I think this will solve your last two mentioned problem.
I am just trying to clear the text area with an id of "discussion" it clears the textbox but it does not load the data from the server with the ajax statement. When I remove the line that clears that text area it loads all the data in fine but just adds to the current data.
Here is my code:
function LoadRoomMessages(id)
{
$.ajax(
{
type: "Get",
url: "#Url.Action("GetMessages", "Home")",
data: { roomId: id },
success: function (data)
{
// Here is the line that causes issues.
$('#discussion').val('');
json = data;
var obj = JSON.parse(json);
for (var i = 0; i < data.length; i++)
{
$('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "\r\n");
}
}
});
}
You may also try (as you asked to answer it)
$('#discussion').empty();