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.
Related
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*/
}));
});
I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});
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().
I have a piece of code that does:
$('td.unique').live('click', function () {
//function logic here
});
This works fine on I click on the td of my table. All fine!
Now I would like to be able to have the same functionality programatically in certain cases without the user actually pressing click.
I have tried:
$(document).ready(function() {
$(".clearButton").click( function () {
var username = $(this).closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $(this).closest('tr').find('label').val();
var input = [];
input[0] = {action:'reset', id:user_id,user:username,};
$.ajax({
url: 'updateprofile.html',
data:{'user_options':JSON.stringify(input)},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
//all ok
console.log("ALL OK");
$(this).closest('tr').find('.unique').trigger('click');
$(this).closest('tr').find('td.unique').trigger('click');
$(this).closest('tr').find('td.unique').click();
}
else {
alert('failed');
}
}
});
This button is in the same row that the td.unique is
None of these work. Why? Am I doing it wrong? Is the function that I have bind in live not taken into account when I click this way?
You need to cache the $(this) inside the ajax function.
var $this = $(this);
the $(this) inside the ajax function will not refer to the element that is clicked
$(".clearButton").click(function () {
var $this = $(this);
var username = $this.closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $this.closest('tr').find('label').val();
var input = [];
input[0] = {
action: 'reset',
id: user_id,
user: username,
};
$.ajax({
url: 'updateprofile.html',
data: {
'user_options': JSON.stringify(input)
},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
console.log("ALL OK");
$this.closest('tr').find('.unique').trigger('click');
$this.closest('tr').find('td.unique').trigger('click');
$this.closest('tr').find('td.unique').click();
} else {
alert('failed');
}
}
});
});
I'm loading some data lively from the database and each row have some links that do some things over that.
They work flawlessly except for the last one I've implemented which seems not to be working on IE
$('.lockFile').click(function(){
var url = "functions/lock_call.php";
var unlock = 'assets/lock-unlock.png';
var lock = 'assets/lock.png';
var action = 'unlock';
var id = $(this).parent().parent().attr('id');
var image = $(this).children(0);
if (image.attr('src') == unlock)
action = 'lock';
var data = 'id='+id+'&action='+action;
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(){
alert (action);
if (action == 'lock')
image.attr('src', lock);
else
image.attr('src', unlock);
}
});
return false;
});
What could be wrong?
The alert is performer on "success" but nothing is made. That is, the script doesn't run.
IE 8 has some amazing variables reserved, try this one
$('.lockFile').click(function(){
var Aurl = "functions/lock_call.php";
var AunAlock = 'assets/lock-unlock.png';
var Alock = 'assets/lock.png';
var Aaction = 'AunAlock';
var Aid = $(this).parent().parent().attr('id');
var Aimage = $(this).children(0);
if (image.attr('src') == AunAlock)
Aaction = 'Alock';
var data = 'id='+Aid+'&action='+Aaction;
$.ajax({
type: "POST",
url: Aurl,
data: data,
cache: false,
success: function(){
alert (Aaction);
if (Aaction == 'lock')
Aimage.attr('src', Alock);
else
Aimage.attr('src', AunAlock);
}
});
return false;
});
try to declare data in JSON format
var data = {'id':id, 'action': action}