Doing AJAX call within timer and hold value - javascript

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();

Related

document.getelementById("").value does not work in case of Ajax call?

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.

Add removed element back to DOM jQuery 2

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/

jQuery - completion of multiple ajax-requests

in a $.each() I do a AJAX-request:
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
}
});
});
now I would like to show a message if every AJAX-request in the $.each() is complete. But how can I do this, As AJAX is asynchronous?
You can utilize jQuery.when(). This method
provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events.
var ajaxRequests = all.map(function(x) {
return $.ajax({
url: "/mycontroller/"+encodeURIComponent(x),
success: function(data){
$('#inner').append(data);
}
});
jQuery.when.apply(this, ajaxRequests).then(function() {
// do what you want
});
With simple javascript you can do it in following way:
var counter = 0;
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
counter++; //increment the counter
},
error: function(){
counter++; //increment the counter
},
complete : function(){
//check whether all requests been processed or not
if(counter == all.length)
{
alert("All request processed");
}
}
});
});
use async :false to make ajax request to be completed before the browser passes to other codes
$.each(all, function(i,v) {
$.ajax({
type: 'POST',
url: "/mycontroller/"+encodeURIComponent(v),
data: row,
success: function(data){
$('#inner').append(data);
}
error: function() {
console.log("Error")
}
}); });

How to call setinterval function in another function is not working

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) ;
}
}
});
}

Suppressing and adding parameters for ajax call

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>

Categories