hi i am trying to load data from database using ajax . but the data is loading twice on the html page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('button').click(function(){
$.ajax({
url:"{{route('zaeemajax')}}",
method:"get",
datatype:"json",
success:function(response){
console.log(response);
var tabledata="";
$.each(response,function(key,value){
tabledata +="<tr>";
tabledata +="<td>"+value.name+"</td>";
tabledata +="<td>"+value.price+"</td>";
tabledata +="<td>"+value.category+"</td>";
tabledata +="</tr>";
});
$('#show tbody').append(tabledata);
}
});
});
</script>
in my controller i am return product data as json
public function showallpro()
{
$product=Product::all();
return response()->json($product);
}
there are only two fields right now in the products table but wheneever i try to fetch data from database it is showing the same data twice
here is the html code where i am trying to show the fecthed data from the data base
<table id="show" style="border: 1px solid black;">
<tr>
<th>name</th>
<th>Price</th>
<th>Category</th>
</tr>
<tbody>
</tbody>
</table>
<button type="">Show Data</button>
the only problem i was having that data was loading twice so i made the following changes and it worked
i changed this
$('#show').append(tabledata);
instead of
$('#show tbody').append(tabledata);
Related
Here is a screen shot of the problem
The original file has some hard coded data and I am suppose to replace this data with the one I have in my JSON file, I tried that with this code, made some progress but every time I click on the other e mail header the same data gets placed in the tag of my html file (index). I need to find a way to stop data from duplicating. Can somebody help me?! I am new in AJAX/JSON
$(document).ready(function() {
$.getJSON("email_list.js",
{format: "json"}).done(function(data){
console.log(data);
for (key in data) {
emailID = "#" + data[key].id;
$(".email-header")
.eq(key).attr("id", data[key].id);
$(emailID).find('td')
.eq(0).attr("id", "sender" + data[key].id)
.html(data[key].sender);
$(emailID).find('td')
.eq(1).attr("id", "subject" + data[key].subject)
.html(data[key].subject);
$(emailID).find('td')
.eq(2).attr("id", "datetime" + data[key].datetime)
.html(data[key].datetime);
}
});
// show/hide emails when click on headers
$("tr.email-header").click(function(){
id = "#body " + $(this).attr("id");
//creates the name for each file
fileID = $(this).attr("id") + ".js";
//console.log(id);
$.ajax({
url: fileID,
dataType: "JSON",
success: function(data) {
console.log(data);
//I need to replace the contents in the HTML file with
//my JASON file contents.
fElement = $("tr.email-body").find("p");
fElement.eq(0).html(data.recipient);
fElement.eq(1).html(data.body);
fElement.eq(2).html(data.recipient);
fElement.eq(3).html(data.body);
fElement.eq(4).html(data.recipient);
fElement.eq(5).html(data.body);
}}).fail(function() {
console.log(id + " - HAS AN ERROR!");
});
$(this).next().eq(0).toggle();
});
// hide email on click
$("tr.email-body").click(function(){
$(this).hide();
});
});
Here's an updated snippet that is pulling ajax data from your github repo. Just trace through to see how we are accessing the elements in the js file.
Some additional notes:
Try to use classes for repetitive elements like sender subject and datetime rather than ids. Then it is even easier to access them. I didn't change that.
You have it set to reload the email every time it's header is clicked. Might want to ensure to only load once.
You should clear out the existing html right away so the placeholder text isn't shown for a split second before the real content gets loaded.
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/email_list.js", {
format: "JSON"
}).done(function(data) {
for (key in data) {
emailID = "#" + data[key].id;
$(".email-header")
.eq(key).attr("id", data[key].id);
f_el = $(emailID).find('td');
f_el.eq(0).attr("id", "sender")
.html(data[key].sender);
f_el.eq(1).attr("id", "subject")
.html(data[key].subject);
f_el.eq(2).attr("id", "datetime")
.html(data[key].datetime);
}
});
// show/hide emails when click on headers
$("tr.email-header").click(function() {
let id = $(this).attr("id"),
emailBody = $(this).next(".email-body"),
emailRecipient = emailBody.find('p').first(),
emailContent = emailBody.find('p').last();
//make the AJAX call here
$.ajax({
url: 'https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/' + id + '.js',
dataType: "JSON",
success: function(data) {
emailRecipient.text('To: ' + data.recipient);
emailContent.text(data.body);
}
}).fail(function() {
console.log(id + " - HAS AN ERROR!");
});
emailBody.toggle();
});
// hide email on click
$("tr.email-body").click(function() {
$(this).hide();
});
});
.email-body {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="email.js"></script>
<link rel="stylesheet" href="email.css">
</head>
<body>
<h1>Email Inbox</h1>
<table class="table table-hover" id="inbox">
<thead>
<tr class="active">
<th>Sender</th>
<th>Subject</th>
<th>Received</th>
</tr>
</thead>
<tbody>
<tr class="warning email-header">
<td>Bob</td>
<td>Re: Your brains</td>
<td>01/03/2014 9:56pm</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: Tom#tom.tom</p>
<p>Heya Tom, it's Bob, from the office down the hall...</p>
</td>
</tr>
<tr class="warning email-header">
<td>Your only friend</td>
<td>I've been shockingly nice</td>
<td>04/07/2011 12:34pm</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: want#you.gone</p>
<p>That's what I'm counting on.</p>
</td>
</tr>
<tr class="warning email-header">
<td>Mr. Fancy Pants</td>
<td>Chances are...</td>
<td>10/21/2005 4:16am</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: dancing#the.parade</p>
<p>You thought you had some fancy pants and now you know it's true.</p>
</td>
</tr>
</tbody>
</table>
</body>
</html>
I am fetching data from database in a table.Now i want to edit particular field in a row of the table and save that value into MySQL.
This is my complete code for displaying data in table and editing. Here i want to edit the status. It is editable but after editing how to get the value from the table and update that value to MySQL.
<?php
include "config.php";
$sql = "select * from d_jobs where Status ='drafted' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
//echo $count;
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
$("document").ready(function(){
$('#sdata').click(function(){
var myTxt = $(('.status')+[i]).html();
console.log(myTxt);
var id = $(('.status')+[i]).attr('id');
console.log(id);
}
/* $.ajax({
type: 'post',
url: 'job_field_edit.php',
data: 'varname=' +myTxt
}); */
});
});
</script>
</head>
<body>
<table border="2" align="center">
<thead>
<tr>
<th>Job Name</th>
<th>Builder</th>
<th>Job Type</th>
<th>Status</th>
<th>Effective Date Start</th>
<th>Estimated completion date</th>
<th>Job Gal Glag</th>
<th>Take List Flag</th>
<th>Planner</th>
<th>Project Manager</th>
<th>Hand Over</th>
<th>Other Comments</th>
</tr>
</thead>
<tbody>
<?php
if( $count ==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysqli_fetch_array($result)){
echo "<tr><td>{$row['JOB_NAME']}</td>
<td>{$row['BUILDER']}</td>
<td>{$row['JOB_TYPE']}</td>
<td contenteditable='true' id='{$row['JOB_ID']}' class='status[{$row['JOB_ID']}]'>{$row['status']}</td>
<td>{$row['EFFECTIVE_START_DATE']}</td>
<td>{$row['ESTIMATED_COMPLETION_DATE']}</td>
<td>{$row['JOB_GAL_FLAG']}</td>
<td>{$row['JOB_TAKE_LIST_FLAG']}</td>
<td>{$row['Planner']}</td>
<td>{$row['Project_Manager']}</td>
<td>{$row['Handover']}</td>
<td>{$row['Comments']}</td>
<td><input name='need_delete[{$row['JOB_ID']}]' type='checkbox' id='checkbox[{$row['JOB_ID']}]' value='{$row['JOB_ID']}'></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<input id="sdata" type="button" value="Send Data" />
</body>
</html>
<?php
mysqli_close($conn);
?>
There's a number of ways to approach this. One is to dispense with the manual Send Data button and allow javascript to respond automatically to users' contenteditable edits.
Unfortunately, contenteditable elements don't fire a change event but they do fire a blur event, from which a change event can be triggered.
First, build your contenteditable elements like this :
<td contenteditable=\"true\" class=\"status\" data-job-id=\"{$row['JOB_ID']}\">{$row['status']}</td>
Then, for each contenteditable element, attach a blur handler, and initialize a data-value attribute equal to innerText.
$('[contenteditable]').on('blur', function(e) {
var self = $(this);
if(self.text() !== self.data('value')) {
self.trigger('change');
}
self.data('value', self.text());
}).each(function() {
$(this).data('value', $(this).text()); // equivaluent to data-value="{$row['status']}".
});
Thus you can have contenteditable elements that mimic, at least in part, HTML input elements.
So now you can attach a change handler as you would for a standard HTML input element.
$(".status").on('change', function(e) {
var job_id = $(this).data('jobId');
var old value = $(this).data('value');
var current value = $(this).text(); // in this regard, <input> is not mimicked. For a genuine <input> we would write `$(this).val()`.
// here, perform ajax to keep server-side up to date.
});
DEMO
Note: This approach is slightly over-the-top when [contenteditable] and .status are virtual synonyms for each other. However, in the general case where there might be several different classes of contenteditable element, then you would likely avoid much repetition of code.
I have a table in a page for example:-
<tr>
<th>no</th>
<th>name</th>
<th>age</th>
<th>actions</th>
</tr>
<tr>
<td>$i</td>
<td>$name</td>
<td>$age</td>
<td>Delete</td>
</tr>
on the click of the delete it will go the controller through jquery and successfully delete the row, after that I want to show the updated table means without that deleted row. for this now I'm using another page and with the table data, on success I'm doing like this:
$(.updated_table_view).html(data.view);
is there any other simple way to do this like without an another page?
Presumably "...will go the controller through jquery..." means via Ajax, so if you want it to just do a simple removal, just hide the row:
jsFiddle: https://jsfiddle.net/842x2wuc/
<script>
$(document).ready(function(){
$('.delete').click(function(e) {
e.preventDefault();
var thisBtn = $(this);
$.ajax({
url: '/link/to/delete.php',
type: 'post',
data: { id: thisBtn.attr('href') },
success: function(response) {
// This will fade out the row
thisBtn.closest('tr').fadeOut('fast');
}
});
});
});
</script>
Currently I have a button to view cart contents as such:
SHOW CART
data-target is for my modal
data-targets is for the body of my modal after the ajax endpoint returns a response
My Ajax code is as follows:
$('a[data-async="true"]').click(function(e){
e.preventDefault();
var self = $(this),
url = self.data('endpoint'),
target = self.data('targets'),
cache = self.data('cache');
$.ajax({
url: url,
cache : cache,
success: function(data){
if (target !== 'undefined'){
$('#'+target).html( data['response'] );
}
}
});
});
(courtesy of jQuery and data-attributes to handle all ajax calls?)
Now once the modal dialog popup has appeared I have some grid items inside a table such as:
<table id="itemstable" class="table table-striped table-bordered">
<thead class="fixed-header">
<tr>
<th>QTY</th>
<th>SKU</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>' . $v->qty . '</td>
<td>' . $v->sku . '</td>
<td> X
</tr>
</tbody>
</table>
The problem I'm running into is I have another ajax endpoint call for each table line item but this time when I click it, the Ajax isn't firing at all. I looked at my browsers inspector but not even an error or attempt.
Am I missing something here because it's practically the same code I ran to get the popup and show the response in the body but now the only difference is I'm doing it inside the modal.
Your help is appreciated!
Change it to this and it should work.
$(document).on('click', 'a[data-async="true"]', function (e) {
e.preventDefault();
// your code here
});
I need a help with the following code. There are 2 styles: activatedRow and disactivatedRow. When a user clicks on a button (located inside the TD of a table), then either activatedRow or disactivatedRow is applied to a row. Selection of a style is based on current style. For instance, if a row is activated, then the button will disactivate it, and vice versa.
So, I have a problem with AJAX success. How to write IF statement to check current style of a row?
P.S. Also it would be interesting to know how to change TD IMG (button) for disactivated and activated rows.
CSS
.activatedRow td {
background-color:#FFFFFF !important;
color: #000000 !important;
}
.disactivatedRow td {
background-color:#DFE1ED !important;
color: #9896A8 !important;
}
Function "disactivateRow()"
<script type="text/javascript">
function disactivateRow(flightNum,obj){
$.ajax({
type: "POST",
url: "callpage.php?page=tables/disactivate.php",
data: "flightNum=" + flightNum,
success: function(){
if ($(obj).hasClass("activatedRow")) {
$(obj).removeClass("activatedRow").addClass("disactivatedRow");
} else
$(obj).removeClass("disactivatedRow").addClass("activatedRow");
}
});
}
</script>
Button inside the table
<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
<th scope="col">Flt Num</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($result1 as $row):
$flightNum=$row['flightNum'];
?>
<tr id="<?php echo $flightNum; ?>" class="edit_tr">
<td><?php echo $flightNum;?></td>
<td id="<?php echo $flightNum; ?>">
<div onclick='disactivateRow("<?php echo $flightNum; ?>", this)'>
<img src='images/disactivate.png' alt='Disactivate' />
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
jQuery DataTable activation
$(document).ready(function(){
$('#newspaper-b').dataTable({
"sPaginationType":"full_numbers",
"bJQueryUI":true,
'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
if (aData[0] == "0") {
nRow.className = "disactivatedRow";
} else
nRow.className = "activatedRow";
return nRow;
}
});
ANSWER:
It works now:
$(".disact_but" ).click(function() {
var ID=$(this).attr('id');
$.ajax({
type: "POST",
url: "callpage.php?page=tables/disactivate.php",
data: "flightNum=" + ID,
success: function(){
$("#"+ID).toggleClass("disactivatedRow", 100);
}
});
return false;
});
If obj is the TD to apply the style as your code indicates you could use toggleClass
Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
$(obj).closest('tr').toggleClass('disactivatedRow');
$(obj).closest('tr').toggleClass('activatedRow');
EDIT
According new information you added, obj is a row's child. closest method should give you the appropiate tr and then we can apply toggleClass