i use the below code to call results from a mysqli database and display them on a page with a live search function.. while loading the results it displays <div id='ajax_request'></div> basicaly a loading gif and on completion it hides that div and shows the div <div id='ajax_results_table'></div> to show the results
I'm curious to know if there is a better method out there for doing the same thing as I could have multiple requests on one page and I need each div to display loading while it's performing its own ajax request
so far I would copy the same code and change the id's for the divs
I'm completely new to ajax and would like to learn more so far this is what I have got.
The Html Code...
<input type='text' class='form-control' onkeyup='showResult(this.value)' placeholder='Search Results'>
<div id='ajax_request'><img src='/ajax-loader.gif' class='text-center'> Fetching Data ...</div>
<div id='ajax_error'>Something went wrong with our ajax request</div>
<table id='ajax_results_table'>
<thead>
<tr>
<th> SMS ID</th>
<th> Time Stamp</th>
<th> Mobile Number</th>
<th> Message</th>
<th> Message Status</th>
</tr>
</thead>
<tbody id='ajax_results'>
</tbody>
</table>
The Ajax Code:
<script>
function showResult(str) {
$.ajax({
url: '/getjson.php?search=' + str,
type: 'POST',
dataType: 'json',
Timeout: 3000,
beforeSend: function() {
$('#ajax_request').show();
$('#ajax_results_table').hide();
$('#ajax_error').hide();
},
success: function(response) {
var trHTML = '';
$.each(response, function(key, value) {
trHTML +=
'<tr><td>' + value.ID +
'</td><td>' + value.Timestamp +
'</td><td>' + value.Number +
'</td><td>' + value.Message +
'</td><td>' + value.Status +
'</td></tr>';
});
$('#ajax_results').html(trHTML);
$('#ajax_request').hide();
$('#ajax_results_table').show();
},
error: function() {
$('#ajax_request').hide();
$('#ajax_error').show();
}
});
}
showResult('');
</script>
Related
I'm developing a live search function in a Laravel application, but I'm having some problems because i'm getting duplicate appends, for example I type in "Andrew".
Every key I hit starting with "A" until "W", im appending the results over and over, so Andre creates 6 table rows, but I want it to be only one.
The second problem is that if I delete all the input, I'm trying to show my "initial_table", but that doesn't work.
I tried changing $('#ajax').append(row); from append to html, but then I have only one result no matter how many matches I get.
<table id="usertable">
<thead>
<tr>
<th>Name</th>
<th>Tier</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Tier</th>
</tr>
</tfoot>
<tbody id="ajax">
{{-- search results here --}}
</tbody>
<tbody id="initial_table">
#foreach ($users as $user)
<tr>
<td>{{$user->username}} </td>
<td>{{$user->tier}}</td>
</tr>
#endforeach
</tbody>
</table>
This is my Javascript
<script>
});
// })
document.getElementById("search").addEventListener("keyup", searchUsers);
document.getElementById("search").addEventListener("change", searchUsers);
function searchUsers(){
if(this.value != '') {
$.ajax({
url: '/admin/searchUsers?search=' + this.value,
method: 'GET'
}).done(function(response){
console.log(typeof response);
console.log(response);
if(response.length < 1) {
$('#ajax').append('<span class="text-center">No results found!</span>');
$('#initial_table').hide();
}
else {
$.each(response, function(index, obj){
var row = $('<tr>');
row.append('<td> <a href="/admin/user/' + obj.id + '">' + obj.username + ' AJAX' + '</td>');
row.append('<td>' + obj.tier + '</td>');
$('#ajax').append(row);
$('#initial_table').hide();
});
}
});
}
}
</script>
Tried to add some comments to explain . Hope it helps
document.getElementById("search").addEventListener("keyup", searchUsers);
document.getElementById("search").addEventListener("change", searchUsers);
function searchUsers(){
if((this.value.trim()) != '') // even for extra space it should not allow in
{
$.ajax({
url: '/admin/searchUsers?search=' + this.value,
method: 'GET'
}).done(function(response)
{
console.log(typeof response);
console.log(response);
$('#ajax').empty(); //for 1st query :-on every ajax call it will first empty "#ajax" tbody
$('#initial_table').hide();
if(response.length < 1)
{
$('#ajax').append('<span class="text-center">No results found!</span>');
}
else
{
$.each(response, function(index, obj)
{
var row = $('<tr>');
row.append('<td> <a href="/admin/user/' + obj.id + '">' + obj.username + ' AJAX' + '</td>');
row.append('<td>' + obj.tier + '</td>');
$('#ajax').append(row);
});
}
});
}else // for 2nd query :- your code missing this part to show initial tbody if search text is all blank
{
$('#initial_table').show();
$('#ajax').hide();
}
}
I have this JavaScript
function pickdet(Id) {
//alert(Id);
var dd = Id;
$.ajax({
cache: false,
url: "/PVSigns1/GetDetails",
data: { 'Id' : Id },
type: "GET",
dataType: "json",
success: function (data) {
//alert('i dey here')
var row = "";
var baseurl = '#Url.Action("Edit","PVSigns1")' + '?Id=';
$.each(data, function (index, item) {
var clickUrl = baseurl + item.PVSignId;
//row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue + "</td><td> <input type= 'button' onclick= location.href = + '<Url.Action("Create", "PVSigns1", new { Id = item.PVSignId }) ' />" + "</td></tr>";
row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue +
"</td><td> <button class='editbtn btn btn-xs btn-success' data-url = '" + clickUrl + "'> <i class='fa fa-edit fa-lg'></i> Edit</button></td></tr>";
});
$("#pvv").html(row);
},
error: function (result) {
$("#pvv").html('Nothing to show <br /> <p />' + result);
}
});
}
$(function () {
$("button.editbtn").click(function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
});
When I run it, it display perfectly on the browser, but the link created don't work, and when I view the page source, the tbody part which the code above is supposed to inject, doesn't get rendered.
This is what I get, Click on any of the green buttons
in the top table, it loads the second table. The issue is with the second table.
Note: I am using JQuery Datatables.
This the rendered output from page source
<div>
<h3> Details</h3>
<table id="Pv" class="table table-condensed">
<thead>
<tr>
<th>Sign</th>
<th> Value </th>
<th></th>
</tr>
</thead>
<tbody id="pvv">
</tbody>
</table>
Notice <tbody id="pvv"> is empty, not table elements there. What is the issue?
You need to use delegation of dom element for click event. which element generated after binding event after existing dom
$("#Pv").on('click','button.editbtn', function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
I have a page that looks like this:
"Default List Name" is the name of the current page displayed. There are two buttons below and then a table which is the Default List table. Once I click Btn1, it will just re-display the default list table, but when I click Btn2, another table will be displayed, replacing the default list table. Let's call the second table "Second List". Once the table changes, the title "Default List Name" will also change to "Second List Name".
I am going to use AJAX for this so that real time button click and displaying of the corresponding table are applied. But I am still new to AJAX so I am having quite a hard time.
Here's my current code:
var title = $("#title").text();
var btn1 = $("#btn1");
var btn2 = $("#btn2");
/** If one of the buttons is clicked after another and then displays a table, the previous ajax that displayed the previous table, will be removed **/
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList(){
console.log("display default list table");
/*$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'url to current page (not sure)',
async: false
}).*/
}
function displaySecondList(){
console.log("display second list table");
}
I hope I'm making my self clear and hope you guys can help me.
I just wrote this for you just to show you that you can always show and hide your tables
$(document).ready(function(){
$("#mytable1").show();
$("#mytable2").hide();
$("#button1").click(function(){
$("#text").html("Default List Name");
$("#mytable2").hide();
$("#mytable1").show();
});
$("#button2").click(function(){
$("#mytable1").hide();
$("#mytable2").show();
$("#text").html("Second List Name");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div id = "text">Default List Name</div>
<button id = "button1">Button1</button>
<button id = "button2">Button2</button>
<table id = "mytable1" border = "1">
<tr>
<td>text1</td>
<td>text1</td>
<td>text1</td>
</tr>
<tr>
<td>text2</td>
<td>text2</td>
<td>text2</td>
</tr>
<tr>
<td>text3</td>
<td>text3</td>
<td>text3</td>
</tr>
<tr>
<td>text4</td>
<td>text4</td>
<td>text4</td>
</tr>
</table>
<br/>
<table id = "mytable2" border = "1">
<tr>
<td>box1</td>
<td>box1</td>
<td>box1</td>
</tr>
<tr>
<td>box2</td>
<td>box2</td>
<td>box2</td>
</tr>
<tr>
<td>box3</td>
<td>box3</td>
<td>box3</td>
</tr>
<tr>
<td>box4</td>
<td>box4</td>
<td>box4</td>
</tr>
</table>
NOW for your ajax, you should just simply hide one of the tables based on the button that was clicked, and then load the data to your specific table. This works for me. Hope it helps :)
Here's AJAX:
$(document).ready(function(){
$("#button1").click(function(){
$("#mytable2").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable1").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
$("#button2").click(function(){
$("#mytable1").hide();
$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable2").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});
});
I created this fiddle for you: https://jsfiddle.net/8bakcfub/.
Basically, each button click will simulate a call to an API that returns a very simple JSON object. On success, the code parses the response, empties the table and appends a new row to it with the data, and finally changes the title.
Note that the code is pretty much the same for both buttons, except for (a) the JSON returned from AJAX, and (b) the title :)
HTML:
<p id="title">
This title will be replaced...
</p>
<button id="btn1">
First list
</button>
<button id="btn2">
Second list
</button>
<table id="table">
<thead>
<th>Col 1</th>
<th>Col 2</th>
</thead>
<tbody>
</tbody>
</table>
JS:
var btn1 = $("#btn1");
var btn2 = $("#btn2");
$(document).ready(function() {
btn1.on("click", function() {
displayDefaultList();
});
btn2.on("click", function() {
displaySecondList();
});
});
function displayDefaultList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
row: [1, 2]
})
},
success: function(result) {
$('#title').text('first list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
function displaySecondList() {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
async: false,
data: {
json: JSON.stringify({
'row': [3, 4]
})
},
success: function(result) {
$('#title').text('second list');
$('#table tbody').remove();
var newRow = '<tbody><tr><td>' + result.row[0] + '</td></tr><tr><td>' + result.row[1] + '</td></tr></tbody>';
$('#table').append(newRow);
}
});
}
i have dropdown boxes for user_id and er and once both selected i want to load all the data as rows. please advice.
below is my controller
$getShifts = Shifts::Where('user_id','=',$user_id)->Where('week_id','=',$week)->get();
how can i proceed
table
<table class="table table-hover">
<tr class="table-header">
<th>Day</th>
<th>Date</th>
<th>Start</th>
<th>End</th>
<th>Total
<br/> Hours
</th>
<th>Run
<br/> Type
</th>
<th>Edit
<br/> / Delete
</th>
</tr>
EDIT
plese check below code which i have tried
success: function(data) {
var json_obj = $.parseJSON(data);//parse JSON
var output="<tr>";
for (var i in json_obj)
{
output+=
"<td>" + json_obj[i].id + "</td>"+
"<td>" + json_obj[i].bus_no + "</td>"+
"<td>" + json_obj[i].shift_no + "</td>"
;
}
output+="</tr>";
$('#span').html(output);
}
You should call your controller function in ajax and in controller you will get the selected data, so based on that run required query.
$(document).ready(function() {
$("#combo, #user_id").change(function(){
var combo = $('#combo option:selected').val();
var user_id = $('#user_id option:selected').val();
if(combo && user_id) {
$.ajax({
url: "path to controller function",
type: "POST",
dataType: "HTML",
async: false,
data:{combo:combo.user_id:user_id},
success: function(data) {
alert(data) // here you ll see the data from controllen, you can manipulate according to your requirement.
}
});
}
});
});
in controller
echo "
<tr>
<td>$day</td>
<td>$date</td>
<td>$start</td>
<td>$end</td>
<td>$end</td>
<td>$end</td>
</tr> ";
manipulate all fields in to a tr in controller and in ajax success() append the data to table.
I have the following script which populates a table with data when a dropdown value is selected :
<script>
$(document).ready(function(){
$('#commodity_name').change(function (){
//picks the value of the selected commodity_name from the dropdown
option = $(this).find('option:selected').val();
html='';
htmlhead='';
// alert(option)
$.ajax({
type:"GET",
//gets data from the url specified based on the selected commodity_name in the dropdown
url:"<?php echo base_url();?>user_transactions/return_details/"+option,
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++){
//Loops through the data to give out the data in a table format
//alert(data[i].transaction_type)
html += '<tr>\n\
<td><input type="text" id="commodity_name' + i + '" name="commodity_name[]" value="'+data[i].commodity_name+'"/></td>\n\
<td><input type="text" id="transaction_type' + i + '" name="transaction_type[]" value="'+data[i].transaction_type+'"/></td>\n\
<td><input type="text" id="total_quantity' + i + '" name="total_quantity[]" value="'+data[i].total_quantity+'"/></td>\n\
<td><input type="text" id="remarks' + i + '" name="remarks[]" value="'+data[i].remarks+'"/></td>\n\
<td><input type="text" id="unit_cost' + i + '" name="unit_cost[]" value="'+data[i].unit_cost+'"/></td>\n\
<td></td><td></td></tr> ';
}
htmlhead+='\n\
<th>Commodity Name</th>\n\
<th>Transaction Type</th> \n\
<th>Available Quantity</th> \n\
<th>Available Quantity</th> \n\
<th>Department</th>\n\
<th>Requestor Name</th>\n\
';
//alert(html);
//alert(htmlhead);
$('#thead').append(htmlhead);
$('#you').append(html);
//delegated submit handlers for the forms inside the table
$('#issue_1').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url()?>transactions/issues', $('#Issues_Form').serialize(), function () {
//success do something
alert("Success");
var url = "<?php echo base_url()?>transactions/view_request";
$(location).attr('href',url);
}).fail(function () {
//error do something
alert("Failed please try again later or contact the system Administrator");
})
})
},
error:function(data){
}
})
});
});
</script>
How can I clear the data from the html table that has been appended when I select the next commodity_name in the drop down list , I get only the data returned from the new select I have picked from the drop down list.
Just empty the html before appending.
...
$('#thead').empty();
$('#you').empty();
$('#thead').append(htmlhead);
$('#you').append(html);
...
Try to use the .detach() method of Jquery. Here the link: http://api.jquery.com/detach/