I am using this snippet: http://bootsnipp.com/snippets/featured/payment-form-with-total-preview
And my problem is on the X click, when removing an element, I would like to access the value of the TDs (Concept, Description, Amount, Status and Date), in order to, after having those values, removing the element from my PHP session array, which is an array of all the payments, so I just would do an unset based on the values I get.
This is what I have done so far:
$(document).on('click', '.input-remove-row', function(){
var tr = $(this).closest('tr');
var tds = tr.children('td');
var txt = $(tds[0]).text()
var txt1 = $(tds[1]).text()
var txt2 = $(tds[2]).text()
document.write (txt1)
tr.fadeOut(200, function(){
tr.remove();
calc_total()
});
});
I have trying printing the value of txt, txt1 and txt2 but I always get the amount, I don't reach the other tds, and they are all supposed to be tds with class input based on the other function.
Another question would be how to handle the session here, but that's not the highest priority issue.
Any idea¿? Thank you in advance.
Edit :
If you want to use php to store session value, then you should use $.ajax:
$(document).on('click', '.input-remove-row', function(){
var tr = $(this).closest('tr');
var tds = tr.children('td');
var txt = $(tds[0]).text()
var txt1 = $(tds[1]).text()
var txt2 = $(tds[2]).text()
var data = {
concept: txt,
description: txt1,
amount: txt2
};
$.ajax("YOUR_PHP_POST_URL", {
type: 'POST',
data: data,
success: function(response) {
//Check if store success
if (POST_SUCCESS) {
// remove tr and calc total here
tr.fadeOut(200, function(){
tr.remove();
calc_total();
});
} else {
//notify store failed...
}
},
});
});
When you want the sessioned data, you can use:
$.ajax("YOUR_PHP_GET_URL", {
success: function(response) {
// convert reposnse to object
// then do something like append this data to table, and calc_total
},
});
Or if you use PHP to create the page, you can directly put those session data on table while rendering.
For more about ajax, go to jquery ajax, and you can also find more details, examples on internet.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
EDIT : found the solution, i edited the code so if anyone came to the same problem in a near future can copy my code.
I need to set AJAX response as variable so i can use it on next js script. how can i set AJAX response to variable?
i don't really good at javascript so it might be just typo or something.
this is my code
<script type="text/javascript">
var delivery; // declare of variable to make it "global"
$(document).ready(function() {
$("#jumlah").bind("input change paste keyup", function() {
var qty = $(this).val();
$.ajax({
type: 'POST',
url: '../component/quantity.php',
data: {
jumlah: qty,
id:<?php echo $hasil['id']; ?>
},
success: function (response) {
// We get the element having id of display_info and put the response inside it
delivery = parseFloat(response); // remove the "var" here so you take the cur variable and don't set a new one in the scope of this function.
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("select").change(function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = document.getElementById('jumlah').value;
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
$("#jumlah").bind("input change paste keyup", function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = $(this).val();
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
});
</script>
What you are looking for are scopes. Depending on how and where you set a variable the scope changes.
In your case you want one that is accessable globally so you should place it at the top. You just need to declare it, you don't need to assign any value.
<script type="text/javascript">
var delivery; // declare of variable to make it "global"
$(document).ready(function() {
$("#jumlah").bind("input change paste keyup", function() {
var qty = $(this).val();
$.ajax({
type: 'POST',
url: '../component/quantity.php',
data: {
jumlah: qty,
id:1
},
success: function (response) {
// We get the element having id of display_info and put the response inside it
delivery = parseFloat(response); // remove the "var" here so you take the cur variable and don't set a new one in the scope of this function.
}
});
});
});
</script>
2nd part
<script type="text/javascript">
$(document).ready(function() {
$("select").change(function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = document.getElementById('jumlah').value;
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
$("#jumlah").bind("input change paste keyup", function() {
var total = delivery;
$('select option:selected').each(function() {
total += parseFloat($(this).data('price'));
});
var updatePrice = $(this).val();
var grandTotal = total * updatePrice;
$(".total").val(grandTotal);
$(".total").html(grandTotal.toLocaleString());
});
});
</script>
Edit: Fixed the code. The variable has to be outside of a function.
The window object represents an open window in a browser.
window is a object and you can add any property to window.
success: function (response) {
window.deliveryResponse = response;
}
So you can use this response in any other js file.
other.js
(window.deliveryResponse) && console.log(window.deliveryResponse)
As ajax calls are async, you cannot be sure that the delivery variable will be undefined or not.
In your case, this cannot work also because the variable is defined in the callback scope. To ensure that the delivery response is defined, create a function like this:
function onDelivery(delivery) {
....(rest of second script)
}
Pass this function to the success and use delivery as it is.
Try this:-
<script type="text/javascript">
var delivery; // make your variable delivery as global so you can use it where you want.
$(document).ready(function() {
//you can use it here or anywhere in script you want to re-use it.
//put your code as per your functionality.
});
</script>
How can I pass 2 variables from ajax to function ?
I can successfully pass 1 variable, but I don't know how to write the code to pass 2 variables. I'm stuck here:
<button id ="+data[i].id+" onclick='tahu("+data[i].id+","+data[i].nama+")'>Detail</button>
Here is my function
function tahu(x, y) {
window.alert(x);
window.alert(y);
}
Here is my full ajax code
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
data_table +="<tr><td>"+data[i].id+"</td><td>"+data[i].nama+"</td><td>"+"<button id ="+data[i].id+","+data[i].nama+" onclick='tahu("+data[i].id+")'>Detail</button>"+"</td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
Ok, I've tried to solve your problem but without actually doing a json request so bear with me. Firstly, You are already using jquery for your ajax call so why not leverage jquery for your DOM manipulation as well? I have written your function to store the id and nama as attributes on the button element and instead of having an inline function call, I have written a click event handler in jquery to execute any time a button (with class detailButton) is clicked. This function will grab the data-id and data-name from the button itself and should display the information you want, specific to that button.
The final button element:
<button data-id ="id" data-name="nama" class="detailButton">Detail</button>
and the jquery:
//ajax request
function tampilkan() {
var data_table = "";
var head_table = "";
$.ajax({
url: "showkaryawan/da",
dataType: "json",
success: function(data) {
$('#oo').empty();
head_table +="<thead><tr class='bg-info'><th width='10%'>ID Karyawan</th><th width='30%'>Nama Karyawan</th><th width='15%'>Action</th></tr></thead>";
for (var i =0; i<data.length; i++) {
var id = data[i].id;
var nama = data[i].nama;
data_table +="<tr>";
data_table +="<td>"+id+"</td>";
data_table += "<td>"+nama+"</td>";
data_table += "<button data-id ="+id+" data-nama="+nama+" class="detailButton">Detail</button>";
data_table += "<td></td></tr>";
}
$('#oo').append(head_table);
$('#oo').append(data_table);
}
});
}
//click event handler
$('.detailButton').click(function() {
var id = $(this).data('id')
var nama = $(this).data('nama');
alert(id);
alert(name);
});
I took the liberty of expanding your data_table concatenation into multiple lines for ease of reading. Hope this is closer to your final solution.
I'm trying to map every element that has a contenteditable attribute in order to send the results with each individual element's value being sent. However, I am running into a problem when I try to use comma's inside a field because I am joining the elements then splitting them to get an array of values.
Here is my code:
function getProfileData(element, button) {
var profile_data = $(element).html();
var data = $(element).blur(function() {
profile_data = $(element).map(function() {
return this.innerHTML;
}).get();
});
$(button).on('click', function() {
var edited_content = profile_data.join(", ");
var split = edited_content.split(",");
$.ajax({
method : "POST",
url : "/members/profile/create-profile",
data : {
display_name : split[0],
email_address : split[1],
age : split[2],
location : split[3],
bio : split[4]
},
}).done(function() {
alert("Profile saved!");
location.href = '/members/profile';
}).fail(function() {
alert("Error saving profile, please try again");
});
});
}
Is there any way to not having a comma inside a field cut off the rest of the text after it?
Thanks!
I put my AJAX here and it is working fine in Firefox but not working in Google Chrome. I try but it fails to work in Google Chrome.
<script type="text/javascript">
function action()
{
jQuery('#dyntable').on('click','.quickview',(function()
{
//show all hidden row and remove all showed data
jQuery(this).parents('table').find('tr').each(function()
{
jQuery(this).removeClass('hiderow');
if(jQuery(this).hasClass('togglerow'))
jQuery(this).remove();
});
var parentRow = jQuery(this).parents('tr');
var numcols = parentRow.find('td').length + 1; //get the number of columns in a table. Added 1 for new row to be inserted
//this will insert a new row next to this element's row parent
parentRow.after('<tr class="togglerow"><td colspan="'+numcols+'"><div class="toggledata"></div></td></tr>');
var toggleData = parentRow.next().find('.toggledata');
parentRow.next().hide();
var qty = jQuery(this).val();
jQuery.ajax({
async: false,
type: 'GET',
url: "ajax/tabledata.php?id="+jQuery(this).val(),
success:function(data){
toggleData.append(data);
parentRow.next().fadeIn();
}
});
/*var qty = jQuery(this).val();
var url = "ajax/tabledata.php?id="+qty;
//get data from server
jQuery.post(url,function(data){
toggleData.append(data); //inject data read from server
parentRow.next().fadeIn(); //show inserted new row
//hide this row to look like replacing the newly inserted row
});*/
return false;
}));
//for map view of dropdown
jQuery('#dyntable').on('click','.showmap',(function()
{
//show all hidden row and remove all showed data
jQuery(this).parents('table').find('tr').each(function()
{
jQuery(this).removeClass('hiderow');
if(jQuery(this).hasClass('togglerow'))
jQuery(this).remove();
});
var parentRow = jQuery(this).parents('tr');
var numcols = parentRow.find('td').length + 1; //get the number of columns in a table. Added 1 for new row to be inserted
var qty = jQuery(this).val();
var url = "Mapdashboard.php?id="+qty;
//this will insert a new row next to this element's row parent
parentRow.after('<tr class="togglerow"><td colspan="'+numcols+'"><div class="toggledata"></div></td></tr>');
var toggleData = parentRow.next().find('.toggledata');
parentRow.next().hide();
//get data from server
jQuery.post(url,function(data){
toggleData.append(data); //inject data read from server
parentRow.next().fadeIn(); //show inserted new row
//hide this row to look like replacing the newly inserted row
});
return false;
}));
}
</script>
Try to add to ajax parameters the dataType too:
dataType: "html"
I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'¶1='+ para1 +
'¶2=' + para2+
'¶3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}