I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/
Related
I want to do search and it can search many times. when it is submitted, it will show value in textbox by using document.getelementById("").value. All work well but I added ajax for filter search, document.getelementById("").value couldn't work.
$(document).ready(function() {
$('#job_no').change(function() {
$.ajax({
type: 'POST',
data: {JOB_NO: $(this).val()},
url: 'select.php',
success: function(data) {
$('#input_na').html(data);
}
});
return false;
});
});
<script type="text/javascript">document.getElementById('input_na').value = "<?php echo $_POST['input_na'];?>";</script>
Try this:
$(document).ready(function() {
$('#job_no').change(function() {
var $this = $(this); //add this line
$.ajax({
type: 'POST',
data: {JOB_NO: $this.val()}, //change this line
url: 'select.php',
success: function(data) {
$('#input_na').html(data);
}
});
return false;
});
});
the 'this' in $.ajax(..) function will not refer to $('#job_no'), so it should be assigned to another variable "$this" for use inside the ajax function.
I'm doing an AJAX call within a timer. The AJAX call gives me certain data which I need to make calculations based on the "new" and "old" data. The problem is that the data is overwritten.
function go_timer() {
var x_total = $('.old_value').text();
$.ajax({
type: 'GET',
url: 'http://scrape4me.com/yahoo?url=http://finance.yahoo.com/webservice/v1/symbols/asml.as/quote%3Fformat%3Dxml%26view%3D%E2%80%8C%E2%80%8Bdetail',
dataType: 'xml',
success: xmlParser
});
function xmlParser(xml) {
$('table tr.rows').remove();
$(xml).find('resource').each(function () {
$('table').append('<tr class="rows"><td class="movers"></td></tr>');
});
//end function
}
$('.old_value').text($('table tr td').text());
setTimeout(go_timer, 5000);
}
go_timer();
I would like to do x_total(old) + x_total(new) and then hold on to the outcome of that number.
var x_total = 0;
function go_timer() {
$.ajax({
type: 'GET',
url: 'http://scrape4me.com/yahoo?url=http://finance.yahoo.com/webservice/v1/symbols/asml.as/quote%3Fformat%3Dxml%26view%3D%E2%80%8C%E2%80%8Bdetail',
dataType: 'xml',
success: xmlParser
});
function xmlParser(xml) {
$('table tr.rows').remove();
$(xml).find('resource').each(function () {
$('table').append('<tr class="rows"><td class="movers"></td></tr>');
});
x_total = x_total + parseInt($('table tr td').text());
//end function
}
setTimeout(function(){ go_timer()}, 5000);
//here you can have add logic
}
go_timer();
I want to display Updated records count when Ajax process is going on. When i click on start process button updateRecords()function will execute and it will update records status from open to waiting status one by one in database.So at the same time i want display the waiting records count .For this when user click on strat process button i want to call displayWaitingRecords() using setinterval.
I am calling that function like this from updateRecords()
clear_Process = setInterval(function(){displayWaitingRecords()},200);
But displayWaitingRecords() will not call until updateRecords() process completes.But my requirement is displayWaitingRecords() also will execute simaltaniously with updateRecords().
Function to display updated record count
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
async: false,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}
Function when i click on start process button
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: false,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
Where i am doing wrong? Any help would be greatly appreciated.
You have set async: false. So the ajax call will process synchronized. Set it to false or leave it out (because true is default):
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: true,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
If you leave it out you have the same result:
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}
I am trying to make an ajax call for two separate click events. The difference is for the second click event the variable testOne should not be part of the call and instead there would be a new variable. How should I approach this?
var varOne = '';
var varTwo = '';
var varThree = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: {
testOne: varOne,
testTwo: varOne
}
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
varOne = 'xyz123';
varTwo = '123hbz';
testAjax();
});
$('.clickTwo').click(function(){
//varOne = 'xyz123'; // I dont need this for this click
varTwo = '123hbz';
varThree = 'kjsddfag'; // this gets added
testAjax();
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
Make some like this
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data= {
varOne: 'xyz123',
varTwo: '123hbz',
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data= {
varThree : 'kjsddfag',
varTwo: '123hbz',
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
You can also do the same in other way with minimum line of code, you can call the ajax on click event and pass the data based on the element triggered the click event.
like this:
$('.ajax').click(function(e){
if($(this).hasClass('clickOne')){
var data= { varOne: 'xyz123'; varTwo: '123hbz'; }
}else{
var data= { varThree : 'kjsddfag'; varTwo: '123hbz'; }
}
$.ajax({
type: "POST",
dataType: 'json',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
e.preventDefault();
});
<div class="ajax clickOne"></div>
<div class="ajax clickTwo"></div>
In this way you can put as many conditions for different data variable.
You should be doing it like this:
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data {
varOne = 'xyz123',
varTwo = '123hbz'
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data = {
varTwo = '123hbz',
varThree = 'kjsddfag'
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
This way you absolute control over which variables are added to which ajax call. You should not use global variables unless you really need them to be global, which doesn't seem to be the case.
You can pass whatever JavaScript object to the data parameter of the ajax method.
I just wanted to add something. I often hide value inside the value attribute of the button tags to produce something like this.
I haven't been able to test this of course but I thought it was worth mentioning.
jquery:
var fields = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: fields
}).done(function(data) {
$('.result').html(data);
});
}
$('#btn').click(function(){
var varCount = 0;
var vars = $(this).val().split('|');
$.each( vars, function( key, value ) {
varCount++;
fields = fields + 'var' + varCount + '=' + value + '&';
});
fields = fields.slice(0,-1);
$(this).val('123hbz|kjsddfag');
testAjax();
});
html:
<button id="btn" value="xyz123|123hbz"></button>
A more optimized and cleaner version -
var varTwo='junk1'
var varOne='junk2'
var varThree='junk3'
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.ajaxClick').click(function(){
var data={};
if(this.classList.contains('clickOne')){
data.varOne=varOne;
data.varTwo=varTwo;
}else{
data.varThree=varThree;
data.varTwo=varTwo;
}
testAjax(data);
});
<div class="ajaxClick clickOne"></div>
<div class="ajaxClick clickTwo"></div>
I'm getting tired of firebug telling my vars aren't defined...
I have a button: next. When the button is clicked, I want it to load a php page into a div, assigning the php page the variable representing the next page.
To do this, I have a variable crntpage that stores the value of the current page. In order to calculate what the var for the next page must be I have a function called next which calculates the value and returns it.
Let's assume that we are on page 5:
javascript
$(document).ready(function() {
$.ajax({
url: 'pagination.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (pages) {
last = pages['last'];
crntpage = 1;
function nxt(b) {
if (b == last) {
next = last;
} else {
next = b + 1;
}
return next;
}
$('#next').live('click', function() {
crntpage(next);
$('#content').load('getposts.php?pagenum=' + nxt(crntpage));
return false;
});
}
});
});
html
<div id="previous">
<a href=''> <-Previous</a>
</div>
I keep getting an error saying that next isn't defined. My guess is because my nxt function is not receiving the value of last. What am I doing wrong?
What you are trying to do with the nxt function can be accomplished more idiomatically with Math.min():
$('#next').live('click', function() {
crntpage = Math.min(crntpage + 1, last);
$('#content').load('getposts.php?pagenum=' + crntpage);
return false;
});
You should also prefix variable declarations with the var keyword, so as not to pollute the global namespace.
Here's the revised code together:
$(function() {
var currentPage = 1;
var last = 1;
$('#next').live('click', function() {
currentPage = Math.min(currentPage + 1, last);
$('#content').load('getposts.php?pagenum=' + currentPage);
return false;
});
$.ajax({
url: 'pagination.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (pages) {
last = pages['last'];
}
});
});
It looks like you didn't define next. (or maybe it is defined in the part of your code that you didn't post here, I don't know) Have you tried this:
$(document).ready(function() {
var next = ''; //defining the variable first, then you set it below in nxt()
$.ajax({
url: 'pagination.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (pages) {
last = pages['last'];
crntpage = 1;
function nxt(b) {
if (b == last) {
next = last;
} else {
next = b + 1;
}
return next;
}
$('#next').live('click', function() {
crntpage(next);
$('#content').load('getposts.php?pagenum=' + nxt(crntpage));
return false;
});
}
});
});