I have a simple application that calculates the total price of all the rows in a table.
New rows get added like this:
function add() {
[...data removed for readability...]
jQuery.ajax({
type: "POST",
data: {
a:'addadminprice',
id:<? echo $id; ?>,
priceid:el.attr('value'),
price:price
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
var initaddprice = 0;
var row="<tr class='pricedata' rel='"+result.id+"'>";
row+="<td class='drag'>::::</td>";
row+="<td>"+el.text()+"</td>";
row+="<td class='right'>"+price+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+price+"' /></td>";
row+="<td>"+(el.data('percent')=='1'?"%":"")+"</td>";
row+="<td><input type='text' onchange='recalc(this,"+result.id+")' value='"+result.qty+"' /></td>";
row+="<td class='right'>"+initaddprice.toFixed(3)+"</td>";
row+="<td><a class='button' href='#' onclick='return removeprice(this,"+result.id+")'>remove</a></td>";
row+="</tr>";
var isfound=false;
$('.pricedata').last().after($(row));
el.remove();
changePrice();
recalcall();
setsort();
saveposition();
}
}
});
As you can see it adds the row - then recalculates the total based all the rows. So far so good, it works fine.
function recalcall() {
console.clear();
console.log('----start calculation----');
var total=0;
$('.pricedata').each(function(){
var price=parseFloat($(this).find('td').eq(6).text());
if (isNaN(price)) price=0;
total+=price;
console.log('+'+price+' = '+total);
});
console.log('----end calculation----');
$('#total').text(total.toFixed(3));
}
When I remove one row, it removes the element and will recalculate the total again. But unfortunately the row is still included in the calculation process? I'm at loss here. Once you remove an element, it should be taken in consideration, right?
function removeprice(el,id) {
if (confirm('Are you sure?')) {
jQuery.ajax({
type: "POST",
data: {
a:'deleteprojectprice',
id:id
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
}
}
});
}
recalcall();
}
In the removeprice function, move recalcall(); in to the success function
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
recalcall(); // call function here
}
do it like following
function removeprice(el,id) {
if (confirm('Are you sure?')) {
jQuery.ajax({
type: "POST",
data: {
a:'deleteprojectprice',
id:id
},
url: options.actionurl,
dataType: "json",
success: function(result){
if (result.status=='success') {
$(el).closest('tr').remove();
}
//have this here
recalcall();
}
});
}
}
Related
i am new to JQuery AJAX and i need help with my code. What i want is when i click the add button it will change to delete button. but what happens in my code is that it changes to delete button but when i click delete button, it does not change back to add button. i want it to look like some sort of toggle. here's my html code with javascript:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#add_button').click(function(){
var temp = $('#add_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
}
});
});
$('#delete_button').click(function(){
var temp = $('#delete_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
}
});
});
});
</script>
</head>
<body>
<div>
<button id="add_button" name="add" value="testing">Add</button>
</div>
</body>
and here's my php code:
<?php
if(isset($_POST["add_button"])){
echo "<button id='delete_button' name='delete' value='testing'>Delete</button>";
}
if(isset($_POST["delete_button"])){
echo "<button id='add_button' name='add' value='testing'>Add</button>";
}
?>
please help. thanks
You can try hiding the button clicked and show other button something like
$('#add_button').click(function(){
var temp = $('#add_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
$('#add_button').hide();
$('#delete_button').show();
}
});
});
$('#delete_button').click(function(){
var temp = $('#delete_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
$('#delete_button').hide();
$('#add_button').show();
}
});
});
Or you can use jquery toggle
$( "#add_button").toggle()
http://api.jquery.com/toggle/
Your solution wasn't working, because delete button event handler was being attached to DOM before the DOM element(delete button) was initialised.
So, one event for both buttons would be enough:
$('button').click(function(){
var button = $(this);
if(button.data('type') == 'add') {
var postData = {add_button: button.val()};
} else {
var postData = {delete_button: button.val()};
}
$.ajax({
url: "ajax_test.php",
type: "POST",
data: postData,
success: function(data){
$('div').html(data);
}
});
});
HTML:
<div>
<button data-type="add" name="add" value="testing">Add</button>
</div>
PHP:
<?php
if(isset($_POST["add_button"])){
echo "<button data-type='delete' name='delete' value='testing'>Delete</button>";
}
if(isset($_POST["delete_button"])){
echo "<button data-type='add' name='add' value='testing'>Add</button>";
}
?>
<script>
$(document).ready(function () {
$('div').on('click', '#add_button', function(){
var temp = $(this).val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
}
});
});
$('div').on('click', '#delete_button', function(){
var temp = $(this).val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
}
});
});
});
</script>
Your code won't work on dynamically added elements, while above code works.
Read http://api.jquery.com/on/ for more informations.
Try the below code:
Give a class name to button:
<button id="add_button" class="btnOp" name="add" value="testing">Add</button>
Then you can add a js click event to that classname and change its data accordingly:
$('.btnOp').on('click',function()
{
var text=$(this).text();
if(text==="Add")
{
var temp = $('#add_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {add_button: temp},
success: function(data){
$('div').html(data);
$('.btnOp').val('testing');
}
});
}
else
{
var temp = $('#delete_button').val();
$.ajax({
url: "ajax_test.php",
type: "POST",
data: {delete_button: temp},
success: function(data){
$('div').html(data);
$('.btnOp').val('testing');
}
});
}
});
This will help you to change button values and functionality on success of ajax and acts like kind of toggle
I have a page full of different links that each have a class of .post-link.
In the following function, I'd like the line $(this).html('loading...'); to target the specific .post-link div that is clicked. How would I go about achieving this? I feel I should create some sort of variable but I'm a bit lost. Any help would be appreciated.
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$(this).html('loading...'); <--line in question
},
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
Edit
Here is how my HTML is set up:
<a class="post-link"><img src="image.jpg"></a>
Using Alexander's solution, the "loading..." text shows up like this:
<a class="post-link"><img src="image.jpg">loading...</img></a>
Is there a way to make it show like this?
<a class="post-link"><span>loading...</span><img src="image.jpg"></img></a>
Of course given that I wrap the text in span tags?
Update
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel'),
ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$('<span class="loading">loading...</span>').insertBefore($(e.currentTarget).find('img'));
},
success: function(response) {
$('.loading').remove();
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
if ($(window).scrollTop() != 0) {
projectShow();
$('html, body').animate({
scrollTop : 0
},100);
} else {
projectShow();
}
});
Use
$('<span>loading...</span>').insertBefore($(e.currentTarget).find('img'));
or
$(e.currentTarget).prepend('<span>Loading</span>');
because this in beforeSend does not refer to element
You could try something like:
$('.post-link').click(function(e) {
e.preventDefault();
// set a variable as a reference to 'this'
// prefixing variables containing jquery object with a '$'
// as an easy way to spot them in your code
var $self = $(this),
post_id = $(this).attr('rel'),
ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$self.html('loading...');
// use if .post-link is a text element
$self.prepend('<span>loading...</span>')
// if your .post-link is an image
},
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
Although Alexander's answer is better as long as you don't override/re-declare the e
You may have overcomplicated it a bit. Why do it in beforeSend? Just do it like this:
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
// do it here:
$('#project-wrapper').addClass('activated');
$(this).find('img').before('<span>loading...</span>');
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
// I guess you are calling projectShow() somewhere in here
});
In browsers which support ES5 (IE >= 9), you can simply use .bind(this) to get context.
beforeSend: (function() {
$('#project-wrapper').addClass('activated');
$(this).prepend('<span>loading...</span>');
}).bind(this),
Try with this code
$(this).parent('.post-link').html('loading....');
This is a relatively novice question. I have the following jQuery function:
$(function ()
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
});
I'm looking to name and parameterize the function so that I can call it repeatedly (with the parameters queryType and divID which are already included in the code). I've tried unsuccessfully multiple times. Would anyone have any insight?
Just stick it in a function
function doAjax(queryType, divID) {
return $.ajax({
url: 'testapi.php',
data: {query : queryType},
dataType: 'json'
}).done(function(data) {
var id = data[0];
$('#'+divID).html(id);
});
}
and use it
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id);
});
});
or
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id).done(function(data) {
// do something more with the returned data
});
});
});
If you're just looking for a simple function to wrap the ajax call give this a try. Place this function above the document ready code.
function callAjax(queryType, divID) {
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data) {
var id = data[0];
$('#'+divID).html(id);
}
});
}
To call the function do this:
callAjax('YourQueryHere', 'YourDivIdHere');
function myFunction(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}
and to call it simply use
myFunction("someQueryType", "myDiv");
function doThis(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}
i have a div that list all the uploaded files
$i = 0;
echo '<div style="float: left;margin-left: 25px;" id="filecontainer">';
echo "<ul>";
foreach($editorderdata['uploadedfiles'] as $row){
echo '<li>';
echo '<a href="'.base_url().'images/userfiles/'.$row['filename'].'" target="_blank">';
echo 'file_'.++$i.'</a>';
echo '<a href="#" data-fileid="'.$row['filename'].'" title="Remove file" class="removefile">';
echo '<img class="cross" src="'.base_url().'images/cross.png">';
echo '</a></li>';
}
echo "</ul>";
echo "</div>";
and this is the code to delete the selected file on pressing the .removefile class element
$(document).ready(function() {
$(".removefile").click(function(e) {
e.preventDefault();
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
$(this).closest("li").remove();
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
return false;
});
});
the code is working fine but what i want is to delete the parent li on ajax success which is not working.. help?
The problem you have is that $(this) in your success handler is not equal to the element which was clicked on. Try this:
$(".removefile").click(function(e) {
e.preventDefault();
var $btn = $(this); // <- save the clicked button to a variable
var fileidvar = $btn.data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data: { fileid: fileidvar },
dataType: 'json',
success: function (data) {
if (data.value) {
alert(data.value);
$btn.closest("li").remove(); // <- use cached selector here
}
},
error: function() {
alert("Something went wrong, please try again.");
}
});
}
return false;
});
Try it like,
if (confirm("Are you sure you want to remove selected file?")) {
var self=this;// make a copy of this to self and use it in ajax function
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
$(self).closest("li").remove();// use self in place of this
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
Try like this.
$(".removefile").click(function(e) {
e.preventDefault();
var this = $(this);
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
this.closest("li").remove();
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
return false;
});
Hope this helps
Problem $(this) is not the element clicked .
so we cache the selector here var this1 = $(this);
$(".removefile").click(function (e) {
var this1 = $(this);
e.preventDefault();
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url: '<?php echo base_url() ?>signup/removefile',
data: {
fileid: fileidvar
},
dataType: 'json',
success: function (data) {
if (data.value) {
alert(data.value);
this1.closest("li").remove();
}
},
error: function () {
alert("Something went wrong, please try again.");
}
});
}
return false;
});
try changing:
$(this).closest("li").remove();
to
$(this).parent().remove();
I have an AJAX registration form:
var id = null;
$.ajax({
type: 'POST',
url: requestUrl,
data: $(".defaultRequest").serialize(),
dataType: 'json',
success: function(data) {
if(data.response){
$('div.errormsg').remove();
if(data.step){
openStep(data.step);
}else{
openStep('next');
}
}else{
$('div.errormsg').remove();
$('<div class="errormsg">'+data.message+"</div>").insertBefore(form);
}
}
});
When a user is successful registered, I want to show him his unique ID, but it stays NULL. How can I solve it?
<script type="text/javascript">
$('#linkkk').text('Your id is: '+id+'');
</script>
you need to set id first in success callback.
$.ajax({
type: 'POST',
url: requestUrl,
data: $(".defaultRequest").serialize(),
dataType: 'json',
success: function(data) {
if(data.response){
$('div.errormsg').remove();
if (data.step) {
openStep(data.step);
} else {
openStep('next');
}
$('#linkkk').text('Your id is: ' + data.id);
} else {
$('div.errormsg').remove();
$('<div class="errormsg">'+data.message+"</div>").insertBefore(form);
}
}
});