How to stop execution in jquery for 1 sec - javascript

I want to submit form using ajax and hide button and show message.
I used "async:false" into ajax that's why button is not hiding. If I use "async:true" then it working.
$(document).ready(function (e) {
$("#submit_form").on('submit',(function(e) {
$('#btn1').css('display','none');
$("#show1").css('display','block');
e.preventDefault(e);
var chkArray = [];
var chkArray1 = [];
$('#loading').show();
var inps = document.getElementsByName('chk_url[]');
//sleep(1000);
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
if($(inp).is(':checked')){
var site_url=$('#site_urls').val(inp.value);
$.ajax({
url: $('#site_urls').val(),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
async:false,
success: function(data)
{
if(data=='done'){
chkArray.push($('#site_urls').val());
}else{
chkArray1.push($('#site_urls').val());
}
}
});
}
}
}));
});
Is there another way to execute hide code before ajax execution??
I have used "delay(1000)" and "sleep(1000)".
I cannot use "setTimeout" function.

Don't use the ajax call in for loop, use outside the loop,
I have change your code, let i know it is helpful..
$(document).ready(function (e) {
$("#submit_form").on('submit',(function(e) {
$('#btn1').css('display','none');
$("#show1").css('display','block');
e.preventDefault(e);
var chkArray = [];
var chkArray1 = [];
$('#loading').show();
var inps = document.getElementsByName('chk_url[]');
//sleep(1000);
var fd = new FormData();
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
if($(inp).is(':checked')){
fd.append( 'site_urls', inp.value );
}
}
/*send call to server start here*/
$.ajax({
url: $('#site_urls').val(),
type: "POST",
data: fd,
contentType: false,
cache: false,
processData:false,
async:false,
success: function(data)
{
if(data=='done'){
chkArray.push($('#site_urls').val());
}else{
chkArray1.push($('#site_urls').val());
}
}
});
/*send call to server ens here*/
}));
});

Related

How to display JSON using ajax

I want to display the value based on selected value on drop down list with using Get method of Ajax from the url,
based on schema i have to add the value of selected item to the meddle of url and then i can get the relative data from the server:
this is my code:
$.ajax({
type: 'GET',
url: 'url',
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#tbl2").append("<option>"+data[i]+"</option>");
}
}
});
var one = 'http://gate.atlascon.cz:9999/rest/a/';
var middle = $('#tbl2 :selected').text(); // it should be the selected item from last get method
var end = '/namespace';
var url_t = one + middle + end ;
$.ajax({
type: 'GET',
url: url_t,
success: function(data2) {
$("#text-area").append(data2);
}
but it is not work!
i am new in programming, could you please help me.
thanks.
try this:
$.ajax({
type: 'GET',
url: 'url',
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#tbl").append("<tr><td>"+data[i]+"</td></tr>");
}
}
});
Add this in your ajax success():
data.forEach(function(item) {
$("#tbl").find('tbody')
.append($('<tr>')
.append($('<td>').text(item))
);
})

jQuery clearinterval / stopinterval doesn't work

I have an autorefresh function that gets called if a checkbox is checked and a button clicked. I want to stop the autorefresh when the checkbox is unclicked:
var refreshId = null;
$("#disINFRAlive").click(function(infralivefun) {
event.preventDefault(infralivefun);
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
if ($('#autorefcheck').is(':checked')) {
var refreshId = setInterval(function() {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
}, 5000);
}
});
The autorefresh works if the checkbox #autorefcheck is checked and the button #disINFRAlive is clicked. However, I can't make it stop by unchecking the checkbox:
function stopinterval(){
clearInterval(refreshId);
return false;
}
$('#autorefcheck').click(function() {
stopinterval();
});
I tried to use clearInterval in various ways and none worked so far.
Remove the var keyword from the initialization of refreshId.
if ($('#autorefcheck').is(':checked')) {
refreshId = setInterval(function() {
The way you have it, you are redeclaring the variable in a different scope. That way, you cannot access it from stopInterval().

Close the Chrome Extension automatically

I am trying to close the extension automatically after saving my data.
Here is the code which is used to save the data:
$(function(){
function displayMessage(string){
alert(string);
}
var submit = $('#submit');
$('#create').submit(function(){
$('#loading_image').html('<img src="images/wait.gif">');
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
var favicon_key = localStorage.getItem("favicon_image_key");
var peoples = [];
var tags_peoples = $("#s2id_people .select2-choices .select2-search-choice");
for (i=0; i<tags_peoples.length; i++) {
peoples.push({"label": tags_peoples[i].childNodes[1].textContent})
}
var subjects = [];
var tags_subjects = $("#s2id_subjects .select2-choices .select2-search-choice");
for (i=0; i<tags_subjects.length;i++) {
subjects.push({"label": tags_subjects[i].childNodes[1].textContent})
}
var places = [];
var tags_places = $("#s2id_places .select2-choices .select2-search-choice");
for (i=0; i<tags_places.length; i++) {
places.push({"label": tags_places[i].childNodes[1].textContent})
}
var begin = $(".daterangepicker_start_input")[0].childNodes[1].value;
var end = $(".daterangepicker_end_input")[0].childNodes[1].value;
var data = {
'content': $('#title').val(),
'people': peoples,
'subjects': subjects,
'begin_date': begin,
'end_date': end,
'places': places
}
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://my_site_url/api/v3/data/",
dataType: "json",
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
$('#loading_image').hide();
window.location.href = 'saved.html';
setTimeout(function(){
window.close();
}, 2000);
},
error: function(data) {
$('#div1').text("Error on saving the data");
$('#loading_image').hide();
},
complete: function() {
submit.removeAttr('disabled').text('Save');
}
});
return false;
});
});
I am using this to close the extension
setTimeout(function(){window.close();}, 3000);
But this doesn't work. Should I write any EventListener to close the extension automatically?
Appreciated the answers
Consider this snippet from your code:
window.location.href = 'saved.html';
setTimeout(function(){
window.close();
}, 2000);
This will not work. As soon as you change location, the page starts to navigate away, eventually wiping the window state and all timeouts set when the new page loads.
You need to set the timeout from saved.html for this to work.

Issue with newElements function

I have a vote function in one of my projects. Please see following code.
$(function () {
$(".vote").click(function () {
var id = $(this).data("id");
var name = $(this).data("name");
var dataString = 'id=' + id;
//var dataId = id;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_up.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
} else {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_down.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
}
return false;
});
});
and I'm using jQuery infinite scroll to load rest of the pages/posts. I'm using following code in main page and second page which i load rest of the data
('#left').infinitescroll({
navSelector: '#page-nav', // selector for the paged navigation
nextSelector: '#page-nav a', // selector for the NEXT link (to page 2)
itemSelector: '.post-box', //
}, function (newElements, data, url) {
$(".vote").click(function () {
var id = $(this).data("id");
var name = $(this).data("name");
var dataString = 'id=' + id;
//var dataId = id;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_up.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
} else {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_down.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
}
return false;
});
});
Issue is after 2nd 3rd or any other page load, vote function is triggering twice. How can I fix this issue. Any help will be appreciated.
Maybe if you unbind the click event and then bind it
function(newElements, data, url){
$(".vote").unbind( "click" );
$(".vote").click(function() {
You need to unbind the click event before binding it again.
[...]
$(".vote").unbind('click').click(function()
[...]
or
[...]
$(".vote").off('click').click(function()
[..]
depending on the version of jQuery you are using.

How Can I Do to my textbox autocomplete, works

I'm trying to do an autocomplete to my textbox, but it doesn't work. Follow my code.
$(function () {
var credenciada = '<%= credenciadaId %>';
xml_NomeCompleto = "";
var Nomes = "";
var retorno = '';
var count = 0;
var t = '';
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
t = $(this).find("NOMECOMPLETOUSUARIO").text();
Nomes += ["\"" + t + "\","];
});
}
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
});
The variable 't' receives all the names of my users, normally, but the autocomplete don't work.
Wait for ajax response to complete and then initialize the autocomplete because before you initialize the plugin data is not available. Also the way you are creating Nomes(source) is wrong. Declare it as an array and use push method to populate it.
Try this
var Nomes = [];
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
Nomes.push($(this).find("NOMECOMPLETOUSUARIO").text());
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
}
});

Categories

Resources