I want every time a user clicks a button, increases +1 in the counter, and Ajax work every time if user click.
This is just for a test with AJAX and the function will work every time if user click on the button.
My code in HTML:
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="jquery-3.1.1.js"></script>
<script src="JS.js"></script>
<!--script src="JS2.js"></script-->
</head>
<body>
<button id="1" onclick="dadosLog()">
Login
</body>
</html>
Function .js:
var numberOrigin = 0 //
function dadosLog (){
numberOrigin++;
var obj = login("xxxLog", "xxxxxxxPassword", numberOrigin);
}
// Function 2 before function 1 its OK
function function2(otherParameter, numberOrigin){
console.log(xxxxxx);
$.ajax({
type: 'POST',
dataType: 'json',
contentType: "application/json",
url: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/request/create',
data: JSON.stringify({
"synchronize":false,
"sourceRequest":{
"numberOrigin":numberOrigin,
"description": "test"
}
},
}),
success:function(output) {
console.log(output);
alert(output.request.number)
},
error:function(output) {
return '0';
console.log(output);
}
});
}
its work:
var counter = 10; // Enter the value you want to start the counter
function Function1(){
var obj = teste("xxxxxxx", "xxxxxxxxxxx", counter);
counter++;
}
var obj;
function teste (NameV, NameV2, counter){
counter +=1;
// function (...)
Then I will make a connection class with the bank and a field where it will check if the counter number already exists and if not, +1
Related
I'm working on a counter that shows the total amount of trees from TeamTrees.org (I'm new to JavaScript) Which I wanted to make it real-time. So, I use Odometer.js and it keeps updating from 0.
Here's the video to describe my problem.
removed
I've tried searching on this site, and other Sites. But, it still didn't work.
Here's the code:
index.html
</div>
<script src="trees.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/odometer.js/0.4.8/odometer.min.js"></script>
<script>
init();
var TreeCount = new Odometer({
el: document.querySelector('#cash'),
auto: 'true',
format: ',ddd',
theme: 'default'
})
</script>
</center>
</body>
Trees.js
function init() {
fetchTrees()
setInterval(fetchTrees, 3000);
}
function formatNumber(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function fetchTrees() {
$.ajax({
url: "-",
method: "POST",
data: {
"wrapAPIKey": "-"
}
}).done(function(data) {
numTrees = data["data"]["#totalTrees"];
$("#cash").text("$"+formatNumber(numTrees))
TreeCount.update(numTrees);
});
}
I think that you need to add the last retrieved value to the new value like so :
function init() {
fetchTrees()
setInterval(fetchTrees, 3000);
}
function formatNumber(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function fetchTrees() {
$.ajax({
url: "-",
method: "POST",
data: {
"wrapAPIKey": "-"
}
}).done(function(data) {
numTrees += parseInt(data["data"]["#totalTrees"]);
$("#cash").text("$"+formatNumber(numTrees))
TreeCount.update(numTrees);
});
}
I have 2 button, and when either buttons is clicked, the time is shown below. Both buttons have separate outputs. I'm trying to use clearTimeout, but it's not clearing the timeout for some reason. When a button is clicked again, it just makes another ajax call on top of the already existing ajax call. How do I get clearTimeout to work?
<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output1',0)">
<div id = 'output1'></div>
<input type = 'submit' value = 'show time' onclick = "showTime('test1.php', 'output2',1)">
<div id = 'output2'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
var timeout = [];
function showTime(gotoUrl,output,index) {
if (timeout[index]) {
clearTimeout(timeout[index]);
}
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
showTimeX(gotoUrl, output);
} //end of success:function(data)
}); //end of $.ajax
} //end of function showTime(gotoUrl, output)
function showTimeX(gotoUrl,output,index) {
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
timeout[index] = setTimeout(function(){showTimeX(gotoUrl, output, index)}, 5000);
} //end of success:function(data)
}); //end of $.ajax
} //end of function showTime(gotoUrl, output)
</script>
Your function showTime(gotoUrl,output,index) calls showTimeX(gotoUrl, output) on success.
But the showTimeX(gotoUrl,output,index) definition requires index as last argument, which is not specifed when you call that function.
Could it be that index is undefined and so timeout array doesn't contain any variables?
i am calling a function with parameters from onclick method what i want to do is i want this function to repeat every 1 min here is html code:
I am calling a function on everyclick with some parameter as id
The id fetches the the lat longs,and it is plotted in map ,i have done everything working except that i get the data keep recieving from the back end so what i want to do is , as i have clicked the href i want that particular id to be sent and keep recieve the data of that particular id only and when i click the second the first should be stopped and start the another .
<html>
</head>
<body>
</body>
</html>
javascript:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
Try this...
Use setInterval to call function every 1 minute and "trigger" function to click automatically when call function "test"
<html>
</head>
<body>
sdsd
sdsd
</body>
</html>
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
}
function test() {
$(".todo").trigger("click");
}
var refreshId = setInterval(test, 60000);
You can simply call a setInterval inside your todo function and it will fire with different calls, change your function like this:
function todo(id) {
setInterval(function() {
/*$.ajax({
type: "GET",
url: "example?value=" + id,
dataType: "text",
success: function(data) {
//parsing;
});*/
console.log(id);
}, 1000);
}
link1
link2
I used only 1000 milliseconds for test here, you only have to change it to 60000 to fit your needs, you can see the results in the console..
Note:
Keep in mind that for each click you will fire a new setInterval() so you have to disable click events after the first setInterval() to avoid this problem.
It is not clear as to what constraints you may require from your question and comments, but perhaps something like this?
Repeat will be stopped if there is an ajax error.
Clicking a button will cancel the current repeat and immediately start the new repeat (1-4). Requests in progress are not cancelled and there is no checking included to ignore processing them upon complete.
A stop button is included, this will stop the repeat but not the request in progress.
The requests are async and no effort has been made to make sure that they are processed in order of request.
This is a very basic example that starts you moving in the right direction.
var pre = document.getElementById('out'),
interval = 5,
running = false,
fetching = false,
timerId;
function stop() {
clearInterval(timerId);
running = false;
}
function todo(id) {
fetching = true;
$.ajax({
type: 'GET',
url: 'http://jsonplaceholder.typicode.com/albums?id=' + id,
dataType: 'jsonp',
error: function (qXHR, textStatus, errorThrown) {
pre.textContent += id + ': ' + textStatus + '\n';
stop();
},
success: function (data) {
pre.textContent += id + ': ' + data[0].title + '\n';
},
complete: function () {
fetching = false;
}
});
}
function start(id) {
if (running) {
stop();
}
running = true;
if (!fetching) {
todo(id);
}
timerId = setInterval(function () {
if (!fetching) {
todo(id);
}
}, interval * 1000);
}
document.body.addEventListener('click', function (evt) {
var target = evt.target;
if (target.classList.contains('album')) {
start(target.value);
}
}, false);
document.getElementById('stop').addEventListener('click', function () {
stop();
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="album" value="1">1</button>
<button class="album" value="2">2</button>
<button class="album" value="3">3</button>
<button class="album" value="4">4</button>
<button id="stop">stop</button>
<pre id="out"></pre>
You can use setTimeout of javascript.
It will repeat given function in specified time interval.
Javascript setTimeout function repeat
OR
setInterval( function(){ todo(id);}, 60000);
Make use of setTimeout to call the function again:
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
setTimeout(function(){todo(id)}, 60000);
}
And if you also want to clear timeout on some condition:
var timer;
function todo(id)
{
$.ajax({
type:"GET",
url: "example?value="+id,
dataType:"text",
success: function(data)
{
//parsing;
});
timer = setTimeout(function(){todo(id)}, 60000);
if(//Your condition){
window.clearTimeout(timer);
}
}
I am trying to use ++ in jquery to append data, and I face a problem, I need to refresh the value again if I click other button without refresh page, how can I do that? The var count will increase as I clicked, I want to know if I can start over this count again when I click second button.
var count='1';
$('#good').on('click',function(){
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data:data,
success: function(data){
count++
}
});
}):
$('#second').on('click',function(){
//refresh the var count, start from 1 again
count++
});
Updated Answer (based on clarification from OP):
I want to if I can start over this count again when I click second button
$('#second').on('click',function(){
//refresh the var count, start from 1 again
count = 1;
});
Live Example:
var count = 1;
$('#good').on('click', function() {
count++;
snippet.log("Incremented, count = " + count);
});
$('#second').on('click', function() {
//refresh the var count, start from 1 again
count = 1;
snippet.log("Reset, count = " + count);
});
<input type="button" id="good" value="Increment">
<input type="button" id="second" value="Reset">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Or if you wanted the first incremented number to be 1, start with count = 0:
Live Example:
var count = 0;
$('#good').on('click', function() {
count++;
snippet.log("Incremented, count = " + count);
});
$('#second').on('click', function() {
//refresh the var count, start from 0 again
count = 0;
snippet.log("Reset, count = " + count);
});
<input type="button" id="good" value="Increment">
<input type="button" id="second" value="Reset">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Original Answer:
I'm going to take a total guess at it here and say that in your ajax callback, you're modifying the page in some way, for instance:
$('#good').on('click', function() {
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function(data) {
$("selector-for-some-elements").html("new content"); // <===
current_page++
}
});
});
And that you want a click on the other element to reset things back to the way they were when the page was first loaded.
If so, then you can do something like this (see comments):
var current_page = '1';
// *** A variable for remembering the original content
var originalContent;
$('#good').on('click', function() {
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function(data) {
// Grab the elements we're going to change
var elementsToChange = $("selector-for-elements");
// If we don't have saved content...
if (!originalContent) {
// Save the original content
originalContent = elementsToChange.clone();
}
// Modify it
elementsToChange.html(/*....*/);
current_page++
}
});
});
$('#second').on('click', function() {
// If we have original content...
if (originalContent) {
// Put it back
$("selector-for-some-elements").replaceWith(originalContent);
current_page = 1;
}
});
Obviously, many aspects of the above would vary based on what you're actually trying to do, but as you haven't told us what that is, this is the best I can do...
I have two AJAX functions. First function takes the result of the first input field and concatenates a string and then changes the value of the second input field. The second input field is (type=”hidden”). Second function checks if there was a change triggered in the second input field and then display the value on the third input field. Nothing is being triggered by the change of value made in input field # 2. Example
<script>
$(document).ready(function () {
var timer = null;
var $result=$("#result");
$result.data('url',$result.val());
function submitForm( input ) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
var url=$result.data('url'),
newUrl= url+input+'/';
$result.val(newUrl);
}
});
return false
}
$("#input").on("keyup", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 40);
})
});
$(document).ready(function () {
var timer = null;
var $result=$("#result").val();
function submitForm( input ) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
$result.val();
}
});
return false
}
$("#result").on("change", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 40);
})
});
</script>
</head>
<body>
<h1>Enter a word:</h1>
<form action="index.php" method="post">
Input: <input type="text" id="input" name="input"></br>
Concatenated Result1(hidden): <input type="hidden" style="width:200px;" id="result" name="result" value="http//www.example.com/"></br>
Concatenated Result2: <input type="text" id="result2" name="result2" value=""></br>
</form>
This answer is really a revamp of your code, but maybe it will do what you need and simplify things.
If you simply throw out the second input box, and show #result (make it not hidden), i think this code might work to get what you need accomplished, and simplify things a bit.
What this should do is submit a request to the server no more frequently than every 40ms and on success of that request, we update the display value of #result.
I'm now noticing that if this does actually solve the issue, then you've gotten away from the onChange issue completely, because the real trigger now is the keyup event.
$(document).ready(function() {
/** get the inputs we might need */
var $result = $('#result');
var $input = $('#input');
$result.data('url', $result.val());
var timer;
/** function to submit data to the server and
update the result input on success */
function submitForm( input, newValue) {
$.ajax({
type: "POST",
url: "/concatenate/index.php",
data: {input:input},
dataType: "html",
success: function (data) {
$result.val(newValue);
}
});
};
/** on key up, fill #result with the url + input */
$input.bind('keyup', function() {
var $this = $(this);
var inp = $this.val();
var url = $result.data('url');
var newValue = url + inp + '/';
if(timer) { clearTimeout(timer); }
timer = setTimeout(function(){
submitForm(inp, newValue) ;
}, 40);
return false;
});
});
The OnChange event is not fired when the contents of the field is changed programmatically. The OnChange event is only raised when a user enters data into the field.
That's just the way this works.