Javascript: Determine whether an array contains a position - javascript

I have a list of files, and for each file, on click event, I get the file name and parse the file name and get the extension type:
extension = $('#'+id_href).text().split('.').pop();
Now, a ajax call should be made in order to fetch data about the current file extension.
I want to prevent the ajax api call if I already have the extension data saved in my extension array.
My extension array looks like: a[extension_1] = html_data_1, a[extension_2] = html_data_2;
I want to check if the position extension_1 already exists, and if not, a ajax call should be made to retrieve the data;
with what should i replace the if(!array_extension[extension]) line?
var array_extension = new Array();
ImgAjaxLoader = "$url_img"+'ajax-loader.gif';
ImgI = "$url_img"+'info_icon.png';
$("html").live("click", function() {
$(".info_box").hide();
});
$(".info").live("click",function(e){
e.stopPropagation();
var elem = $(this);
$(".info_box").hide();
position = $(this).offset();
var id = 'container_tooltip';
var id_img = $(this).attr('id');
var id_href = $(this).attr("id").replace("image_","href_");
$('#'+id_img).attr('src',ImgAjaxLoader);
$('#'+id).toggle(100, function() {
if($(this).css('display') == 'block') {
extension = $('#'+id_href).text().split('.').pop();
//if(!array_extension[extension])
$.ajax({
url: "$url",
data: { document_id:elem.attr('document_id') },
success: function (response) {
//console.log(response);
response = JSON.parse(response);
array_extension[response.extension] = response.html;
$('#'+id).html(response.html);
$('#'+id).css({'top':(position.top-110)+'px','left':(position.left+30)+'px'});
$('#'+id_img).css({'width':'20px','height':'20px',"padding":"0px"});
$('#'+id_img).attr('src',ImgI);
}
});
}
});
});

Related

ParsIng BIng Image Search using JQuery or Javascript Errors

I can successfully parse Bing Search JSON API correctly. Using Version 7 of both Web Search and Images. For some reason JSONLint is correct for images but but can not parse a damn thing. My JQuery code is below Thanks in advance!
////JQUERY CODE
$(document).on("click", "#i-search", function () {
//API URL
var uri = 'bing-img.php';
//SEARCH PARAMETERS
var e = escape($('#book').val());
var pg = escape($('#pg').val());;
var limit = escape($('#limit').val());;
var market = "en-us";
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:limit, p:pg, m:market },
success: function(data) {
var obj = JSON.parse(data)
//SEARCH RESULTS
var ocean = obj.value; //client prop is an array
for(var i = 0; i < ocean.length; i++){
//alert(ocean[i].thumbnail);
var ocean_format = '<p>' + ocean[i].name +'</p>';
$("#bookout").append(ocean_format);
}//END SEARCH RESULTS
$("#moreout").html(more);
},
error: function() {
// console.log(data);
}
});
}); //END IMAGE SEARCH SUBMIT
/////// VALID BING IMAGE JSON ////////////
https://0ct0p.us/bing-img.php?q=mazda&s=2&p=0&m=en-us
/////CROSS ORGIN ERROR ON FIREFOX
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin

Only add data to ajax call if it isnt a null value

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

Fetch contenteditable=true data

I want to fetch data from div tag which set contenteditable=true
I have used autosuggestion in that..Data is successfully fetched but when I write item which is written in autosuggestion field then it wont be fetched because it add HTML tag and it wont save into database
My code
if data is changed:
var timeoutID;
$('[contenteditable]').bind('DOMCharacterDataModified', function () {
clearTimeout(timeoutID);
$that = $(this);
timeoutID = setTimeout(function () {
$that.trigger('change')
}, 50)
});
$('[contentEditable]').bind('change', function () {
getTextChangeContent();
});
UPDATE
function getTextChangeContent() {
var ma = document.getElementById('myAudio');
var remove = ma.src.slice(0, -4);
var path = remove.substring(remove.lastIndexOf("/") + 1);
var newPath = path.concat('.wav');
var text_id = document.getElementById('textbox');
var textdata = text_id.innerHTML;
$.ajax(
{
type: "POST",
url: '#Url.Action("getChangeContent")',
dataType: "json",
mtype: "post",
data: { arg: varid, content: textdata, path: newPath },
async: true,
success: function (data) {
alert(data + " DATA");
}
});
}
when I changed data and use autosuggestion then it will show data as
The door is blacl <span class="atwho-inserted">[[Ceilings]]</span>
How to ignore html tag and take only values of that?
Plz suggest me
Retrieve innerText rather than innerHTML in order to ignore the HTML content. If you want only the content inside the html tag with class .atwho-inserted, then retrieve only that content.
var textdata = text_id.innerText;

Re factoring jQuery functions

How can refactor this below jQuery code.
All the functions does the same job but on different key-presses on the table search box. Which is filtering the table data.
I want re factor this code and write it in single function. Please help me.
jQuery(function($) {
// when the #name field changes
$("body").on("keypup", "#name", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#login", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#account_manager", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
$("body").on("keypup", "#email", function() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
});
});
function update() {
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});
}
$("body").on("keyup", "#account_manager, #login, #email", update);
The explanation:
1.) We extract the duplicate code in a single function called update. We follow the DRY principle here
2.) JQuery allows us to use multiple selectors, so we can bind the update function to all elements at once:
$("body").on("keyup", "#account_manager, #login, #email", update);
instead of calling:
$("body").on("keyup", "#account_manager", update);
$("body").on("keyup", "#login", update);
$("body").on("keyup", "#email", update);
how about just having one code block:
$("body").on("keypup", "#name, #login, #account_manager, #email", function() {
var form = $("#users_form");
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data);
});
});
Much better though, would be to give you elements a class, and bind to the class rather then each id, i.e.
$("body").on("keypup", ".someClass", function() { //etc
write a new function.
$("body").on("keypup", "#login", function() {
functionName();
});
and in function
function functionName(){
var form = $("#users_form"); // grab the form wrapping the name bar.
var url = form.attr("action");
var formData = form.serialize();
$.get(url, formData, function(data) {
$("#reseller_admin_list").html(data); // replace the "results" div with the result of action taken
});`
}

Cyclo for with inside ajax, the callback return a wrong result

I tried to create a jquery plugIn that load multiple feed rss (they are flexible can be 1 or 2 or 3 ect...), for create an html that show the news feed loaded. My target is having the possibility to load multiple rss feed (xml) and display them by html. When I tried seem that the callback is overwrite,I received 2 results but equal.
Example:
(function($){
$.fn.getFeed = function(Obj){
var
arrOpt = Obj.arrayOptions,
arrOptLng = arrOpt.length;
for(var i = 0; i < arrOptLng; i++){
var
index = i,
Opt = arrOpt[i],
feedUrl = Opt.feed,
sucFnc = Opt.callback,
$cnt = this;
console.log(index);
// here:
// 0
// 1
$.ajax({
url:feedUrl,
dataType: "jsonp",
success:function(data){
sucFnc(data,$cnt,Opt,index);
},
error:function(){
$cnt.html('error');
}
});
}
}
})(jQuery);
function feedManipulation(){
console.log(index)
// here:
// 1
// 1
}
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});
Ciao, I wrote this question and I created the solution so I would explain.
In this code I removed the cyclo for and I create a function that contain the ajax call.
The first time that I trigger the ajax function I pass an argument to the ajax function with inside an object that I used to set the plugIn (lock on the bottom) whereas my ajax function is itself calls, before sending the same object to the ajax function I change some information like "Opt.index" creating in this way a ajax cyclo. Is it really usefull ;) use it.
(function($){
$.fn.getFeed = function(Obj){
// Options object
Opt = new Object();
Opt.index = 0;
Opt.$cnt = this;
Opt.arrOpts = Obj.arrayOptions;
Opt.arrOptLng = Opt.arrOpts.length;
Opt.arrOpt = Opt.arrOpts[Opt.index];
Opt.feedUrl = Opt.arrOpts[Opt.index].feedUrl;
// ajax call
cycloAjax(Opt);
}
/* ajax cyclo */
function cycloAjax(Obj){
$.ajax({
url: Obj.feedUrl,
dataType: "jsonp",
success:function(data){
feedManipulation(data,Obj.$cnt,Obj);
if(Obj.index < Obj.arrOptLng - 1){
Obj.index++;
Obj.arrOpt = Obj.arrOpts[Obj.index];
Obj.feedUrl = Obj.arrOpts[Obj.index].feedUrl;
cycloAjax(Obj);
}
else{
completeLoadFeeds(Obj.$cnt,Obj);
}
},
error:function(){
Obj.$cnt.html('<p>error</p>');
}
});
}
.
.
.
})(jQuery);
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});

Categories