How to transfer a variable value from one function to anoter function? - javascript

Actually i want to transfer the value of my variable to another function in javascript. I tried many methods. In fact I search on stackoverflow but i didn't get correct output.
When i click on button show() function runs and form open
function show(){
var target = event.target || event.srcElement;
var id = target.id;
var x = document.getElementById(id).parentElement.id; // I am getting the value of 'x' when i alert it shows correct output
//alert(x);
$.ajax({
url: 'php/retrieve_characters.php',
type: 'post',
data: {},
success: function(response) {
var data = $.parseJSON(response);
if(data!='') {
$.each(data, function(i, item) {
$('#0').attr('src',data[0].charac);
$('#1').attr('src', data[1].charac);
});
}
}
})
}
Now when form opens i click a button which is in form and new function runs
function setimage(){
var target = event.target || event.srcElement;
var id = target.id;
$.ajax({
url: 'php/retrieve_characters.php',
type: 'post',
data: {},
success: function(response) {
var data = $.parseJSON(response);
if(data!='') {
$.each(data, function(i, item) {
var parent=document.getElementById("par1");
var child = parent.lastElementChild;
while (child) {
parent.removeChild(child);
child = parent.lastElementChild;
}
var li = document.createElement("img");
li.setAttribute("id", "char"+id);
li.setAttribute("src", data[id].charac);
li.setAttribute("onclick", "show()");
li.setAttribute("class", "imgs-thumbnail");
parent.appendChild(li);
});
}
}
})
}
In function setimage() i want the value of x which is in first function.
Remember one thing I don't want to call one function into another because in both functions i m retrieving data from database which will be messed up if both functions will be concatenated.

Related

How to apply a function on an element without any event handler after just creating it

I made a dynamic element on javascript. Actually i am retrieving some data from db and on response i made an element in javascript
$.ajax({
url: 'php/count_comments.php',
type: 'post',
data: {
},
success: function(response) {
var data = JSON.parse(response);
if(data!='') {
$.each(data, function(i, item) {
var span3=document.createElement("span");
span3.appendChild(document.createTextNode("No Comments"));
span3.setAttribute("id",n+newsid);
span3.setAttribute("class","ment");
p1.appendChild(span3);
});
}else if(data==''){
alert("Admin has not uploaded any news yet");
return false;
}
}
});
Now when the element has been created and every element has a unique id now i want to run a function without any event handler for each element
this is function i want to run
function comments{
var target = event.target || event.srcElement;
var ids = target.id;
var id = ids.slice(-14);
// alert(id);
$.ajax({
url: 'php/count_comments.php',
type: 'post',
data: {
id:id
},
success: function(response) {
var data = JSON.parse(response);
if(data!='') {
$.each(data, function(i, item) {
// var target = event.target || event.srcElement;
// var ids = target.id;
// alert(ids);
// alert(document.getElementById(ids).innerHTML);
document.getElementById(ids).innerHTML=data[i].comments+ " Comment(s)";
});
}else if(data==''){
//alert("No comments yet");
return false;
}
}
});
}
You can call your function immediately in the loop which creates elements.
$.each(data, function(i, item) {
var span3=document.createElement("span");
span3.appendChild(document.createTextNode("No Comments"));
span3.setAttribute("id",n+newsid);
span3.setAttribute("class","ment");
p1.appendChild(span3);
//call from here with the id
comments(n+newsid)
});
Also, comments function is wrongly declared, correct it and have id as parameter.
function comments(id) {
// do your stuff
}
if you want to call comment method silently then use a timeout function while calling
setTimeout(function() {
comments(n+newsid);
}, 0)

how to count length of list created dynamically

I am creating a chat box in which chat messages are fetched in the form of list. My problem is whenever i am clicking on start chat button i have to open chat box and then count the no of list. my chat box is opening but length of list are always zero. how to solve this.
$(document).on('click', '.start_chat', function(){
var to_user_id = $(this).data('touser_id');
var to_user_name = $(this).data('tousername');
//console.log(to_user_id);
var getdata;
$.ajax({
url:"chat_id_table.php",
method:"POST",
data:{to_user_id:to_user_id},
async:false,
dataType:'json',
success:function(data)
{
//console.log(data);
getdata = JSON.parse(data);
//console.log(getdata);
}
})
if($('#user_dialog'+to_user_id).length == 0){
make_chat_box(to_user_id, to_user_name, getdata);
}
var chat_length = $('.msg_list').find("li").length;
});
Getting the chat data is an async call. so what happens is that the list is counted before the data comes in.
To solve this wrap the list counter in a function and call it after data is in.
fixed code here
$(document).on('click', '.start_chat', function(){
var to_user_id = $(this).data('touser_id');
var to_user_name = $(this).data('tousername');
//console.log(to_user_id);
var getdata;
$.ajax({
url:"chat_id_table.php",
method:"POST",
data:{to_user_id:to_user_id},
async:false,
dataType:'json',
success:function(data)
{
//console.log(data);
getdata = JSON.parse(data);
//console.log(getdata);
var chat_len = counter();
}
})
});
function counter(){
if($('#user_dialog'+to_user_id).length == 0){
make_chat_box(to_user_id, to_user_name, getdata);
}
var chat_length = $('.msg_list').find("li").length;
return chat_length;
}

Jquery onchange Ajax

i made a function that sends data (ajax) to the database and depending on the response from the server i need to alert a message but it seems like whenvever i change the select option i get the alert message for each change(if i change the select four times when i click i get the alert four times ) , but if i remove my ajax function and replace it simply by an alert i get it once not repeating itself here is my JS
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
$(".red").on('click', function (evt) {
if ('done' == msg) {
evt.preventDefault();
alert('NOP');
}
})
});
});
the event that you are binding i think is wrong. For newly append items is better in your case to use
$(document).on('click', ".red", function (evt) {
})
And it must be moved outside the ajax success because now you are triggering it every time
----- Edited ---
If you want just to alert the output of the ajax you dont need the onClick event
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
if (msg === 'done') {
evt.preventDefault();
alert('NOP');
}
});
});
If you want to show the latest result on a button click you can store the msg on a global variable and on click of a div show that like
var globalMsg = "";
$('.select_ids').change(function () {
var id = $(this).val();
var form = $('#form_widget_ids_' + id);
var container = form.parent('.ewb_forms');
var box = container.parent('.edit_widget_box');
container.children('.selected').fadeOut(300, function () {
$(this).removeClass('selected');
form.fadeIn(300, function () {
$(this).addClass('selected');
});
});
Widget.updateSSOUrl(box);
$.ajax({
type: "POST",
url: window.location + "",
data: {'id': id}
}).done(function (msg) {
globalMsg = msg
});
});
$(".div").click(function() { alert(globalMSG); });

How to unbind or turn off all jquery function?

I have constructed an app with push state. Everything is working fine. However in some instances my jquery function are fireing multiple times. That is because when I call push state I bind the particular js file for each page I call. Which means that the same js functions are binded many times to the html while I surf in my page.
Tip: I am using documen.on in my jquery funciton because I need my function to get bound to the dynamical printed HTML through Ajax.
I tried to use off in the push state before printing with no success!
Here is my code:
var requests = [];
function replacePage(url) {
var loading = '<div class="push-load"></div>'
$('.content').fadeOut(200);
$('.container').append(loading);
$.each( requests, function( i, v ){
v.abort();
});
requests.push( $.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(data){
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
$('a').off();
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
})
);
}
$(window).bind('popstate', function(){
replacePage(location.pathname);
});
Thanks in advance!
simple bind new function with blank code
$( "#id" ).bind( "click", function() {
//blank
});
or
used
$('#id').unbind();
Try this,
var requests = [];
function replacePage(url) {
var obj = $(this);
obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
var loading = '<div class="push-load"></div>';
$('.content').fadeOut(200);
$('.container').append(loading);
$.each(requests, function (i, v) {
v.abort();
});
requests.push(
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data) {
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
obj.bind("click", replacePage); // binding after successfulurl ajax request
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
}));
}
Hope this helps,Thank you

Getting wrong Form Data name when posting

I am trying to pass multiple parameters to a javascript function. When reviewing the post data I get incorrect data names.
HTML:
//Test function with button (HTML)
<button onClick='printList("projects",{"qid":1,"oid":3),getSampleEntity);'>Test getSampleEntity</button>
Javascript:
var getSampleEntity = function(oid, qid) {
//Returns Object
return $.ajax({
url: URL + 'downloadQuadrat_Organism.php',
type: 'POST',
data: { 'organismID': oid, 'quadratID': qid },
dataType: dataType
});
}
....
var printList = function(lid,options,get) {
var items = get(options);
var list = $("ul#"+lid);
list.empty();
items.success(function(data){
$.each(data, function(item,details) {
var ul = $('<ul/>');
ul.attr('id', lid+'_'+details.ID);
var li = $('<li/>')
.text(details.ID)
.appendTo(list);
ul.appendTo(list);
$.each(details,function(key,value) {
var li = $('<li/>')
.text(key+': '+value)
.appendTo(ul);
});
});
});
}
The resulting post data:
organismID[qid]:1
organismID[oid]:3
I see what is happening, but my question is how do I pass multiple parameters in to my printList() so that those parameters will be passed effectively to getSapleEntity()?
Try
var items = get(options.oid, options.qid);

Categories

Resources