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
});
Related
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);
I'm trying to get the UID from an anchor tag which is the value of ID attribute of the anchor tag from a foreach loop PHP in ajax. But it only work once a time, when I click the anchor tag again then all the UIDs are grabbed in the ajax!
When I click on anchor tag then 1st I'm displaying a bootstrap 4 modal and in modal a textarea tag is present with a button and when I click button then I've to send uid and message again to the action.php page
This is my action.php code
if(isset($_POST['action']) && $_POST['action'] == 'fetchAllFeedback'){
$feedback = $admin->fetchFeedback();
$output = '';
if($feedback){
$output .= '<table class="table table-striped table-bordered text-center">
<thead>
<tr>
<th>FID</th>
<th>UID</th>
<th>User Name</th>
<th>User E-Mail</th>
<th>Subject</th>
<th>Feedback</th>
<th>Sent On</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
foreach ($feedback as $row) {
$output .= '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['uid'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['email'].'</td>
<td>'.$row['subject'].'</td>
<td>'.$row['feedback'].'</td>
<td>'.$row['created_at'].'</td>
<td>
<i class="fas fa-reply fa-lg"></i>
</td>
</tr>';
}
$output .= '</tbody>
</table>';
echo $output;
}
else{
echo '<h3 class="text-center text-secondary">:( No any feedback written yet!</h3>';
}
}
This is feedback.php ajax code
$("body").on("click", ".feedbackReplyIcon", function(e){
let uid = $(this).attr('id');
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
});
Here is what I believe happens: Since you declare a click method inside another click method, the uid variable turns empty after the first use. It's generally a bad practice to stack events like this inside one another. Try changing your javascript to this:
var uid;
$("body").on("click", ".feedbackReplyIcon", function(e){
uid = $(this).attr('id');
});
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
This might still be less than optimal, I'm a bit unclear on how your elements are laid out, and I can't really test it out. Let me know on what happens - if it still doesn't work, try dumping out the variables in admin-action.php , and see what's in there.
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>