how to count length of list created dynamically - javascript

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;
}

Related

use multiple $(function() with ajax live search

I created a live search. When i open up the page i want to run $(function() {. This run the ajax once and all the output shown up. But i want that it is also updating the page when i type in the searchbox(thats why i used this $('#search').keyup(function(){). AND i want that it update the page also when i press one of the checkboxes which add some other values to the livesearch($('.btn').click(function(){)
$(document).ready(function(){
$(function() {
$('#search').keyup(function(){
var search = $(this).val();
console.log("Input: " + search);
$('.btn').click(function(){
let val1 = getval1();
let val2 = getval2();
let val3 = getval3();
let val4 = getval4();
console.log(val1 + val2 + val3 + val4)
$.ajax({
url:"search.php",
method:"post",
data:{
search:search,
val1:val1,
val2:val2,
val3:val3,
val4:val4,
},
success:function(data){
$('#output').html(data);
}
});
});
});
});
$(document).ready(function(){
//page completed loading
$('#search').keyup(function(){
//user typed something
var search = $(this).val();
let val1 = getval1();
let val2 = getval2();
let val3 = getval3();
let val4 = getval4();
//let's retrieve values
$.ajax({
url:"search.php",
method:"post",
data:{
query:query,
search:search,
val1:val1,
val2:val2,
val3:val3,
val4:val4
},
success:function(data){
$('#output').html(data);
}
});
});
That is enough. You don't even need to use click event since it will fire on each type. Otherwise you can use the click instead of the keyup and it will fire on button click.
Each time you will type something into #search, you will check the value of the other fields too. I'm curious to see what is inside each getval fucntion beacuse probably they can be replaced by something simpler (btw no need for four different functions imho)
Note: $(document).ready(){}; is used to tell the browser to wait the full page to be loaded before executing the code. You will have one of these only in your page with all the js inside. The functions you define (like when you do
function getval1(){
//your function here
}
don't need to be inside the document ready statement
<script type="text/javascript">
search_data()
$(document).ready(function(){
$('#search').keyup(function(){
search_data()
});
$('.btn').click(function(){
search_data()
});
});
function search_data(query){
var search = $('#search').val();
let val1 = getval1();
let val2 = getval2();
let val3 = getval3();
let val4 = getval4();
$.ajax({
url:"search.php",
method:"post",
data:{
query:query,
search:search,
val1:val1,
val2:val2,
val3:val3,
val4:val4,
},
success:function(data){
$('#output').html(data);
}
});
}
</script>

How to insert multiple values to database table using php?

Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);

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

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.

Confirming Retweet

I'm making a script that when a user clicks a button a popup box displays with a text box of the tweet and a button for the user to retweet what's in the text box. In the script it's suppose to tell the user if it has retweeted successfully. The thing is that it tells the user it's successfully retweeted before the user has clicked the retweet button in the pop up box.
Seems as though just by clicking the button that activates the pop up box display is when the code activates a successful retweet message though nothing has been retweeted on the users end.
I'm not very familiar with javascript, my guess it's not the php code that's making the faulty logic but the javascript code. Here is what I have below.
(function($) {
$(document).ready(function() {
$.getScript("http://platform.twitter.com/widgets.js", function(){
twttr.events.bind('tweet', function(event) {
var targetUrl = event.target.src;
var query = getQueryParams(targetUrl);
click_callback(query.url);
});
});
});
})(jQuery);
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
function click_callback(id){
var user = "<? echo $data->id;?>";
document.getElementById("Hint").style.display='block';
$("#Hint").html('Confirming Tweet...');
$.ajax({
type: "POST",
url: "plugins/rt/complete.php",
data: "id="+ id + "&user=" + user,
success: function(msg){
$("#Hint").html('Tweeted! Success!');
removeElement('boxes', id);
}
});
}
function removeElement(parentDiv, childDiv){
if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
}
I think this is what's causing it within the code:
function click_callback(id){
var user = "<? echo $data->id;?>";
document.getElementById("Hint").style.display='block';
$("#Hint").html('Confirming Tweet...');
$.ajax({
type: "POST",
url: "plugins/rt/complete.php",
data: "id="+ id + "&user=" + user,
success: function(msg){
$("#Hint").html('Tweeted! Success!');
removeElement('boxes', id);
}
});
}

Trying to save the response of AJAX() call to a variable but that variable returns empty string [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I am trying to save the reponse of an AJax() call in a javascript variable but this variable returns empty when I append the value to a div .
here is my script code
<script>
/*<![CDATA[*/
$(document).ready(function(){
$("#abusoForm #enviar").livequery("click",function(e){e.preventDefault();
console.log("Click is working");
var hidden = $('#mensajeAbuso').val();
var category = $('#opcmarcar').val();
var name=$('#nombre').val();
var phone=$('#telefono').val();
var mail=$('#email').val();
var cf_mail=$('#confirma_email').val();
var k="<?php echo $this->config->defaultLanguage?>";
var url="somedomain.com/index.php?param=value";
//url = 'proxy.php?url='+url;
var otro = $('#otro_email').val();
var E=$("#abusoForm #enviar").val();
var alto_height = $(window).height();
alto_height = alto_height/4;
//Ajax call happening here
var vajx =$.ajax({url:url,type:"POST",data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}}).responseText;
//Now I have to use the variable vajx to post a message about the submition of the form ;
if(vajx!=""){
$("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(vajx);
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
})
});
/*]]>*/</script>
As you can see in the above image I am getting the response in the console . But when i try to save the response in the var vajx like mentioned in the script above its empty may I know why .
I am very new to Ajax() so need help
UPDATE
After looking into some examples given below and trying my own here is how I could fix it .
Answer
<script>
/*<![CDATA[*/
$(document).ready(function(){
$("#abusoForm #enviar").livequery("click",function(e){e.preventDefault();
console.log("Click is working");
var hidden = $('#mensajeAbuso').val();
var category = $('#opcmarcar').val();
var name=$('#nombre').val();
var phone=$('#telefono').val();
var mail=$('#email').val();
var cf_mail=$('#confirma_email').val();
var k="<?php echo $this->config->defaultLanguage?>";
var url="http://wstation.inmotico.com/index.php?page=avisoajax&type=spam&im_action=reportAbuse&im_core=showAds";
//url = 'proxy.php?url='+url;
var otro = $('#otro_email').val();
var E=$("#abusoForm #enviar").val();
var alto_height = $(window).height();
alto_height = alto_height/4;
//Ajax call happening here
//var vajx =$.ajax({url:url,type:"POST",data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}}).responseText;
var result = ''; // declare a var here
var vajx = $.ajax({
url: url,
type: "POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false},
success: function(data){
$(".appendcontentAbuso").html(data); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
});
/*vajx.done(function (data) {
result = data; // <-----------change here
});
if(result != ""){ // <---------------change here
// $("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(result); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}*/
console.log(data);
//$('#ajxResponse').html(vajx);
})
});
/*]]>*/</script>
Please notice that now I am initiating the popup inside the success: function
Thank you in advance
var vajx;
$.ajax({
url: url,
type:"POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}
)
.done(function( data ) {
vajx = data;
}
});
Try this:
//Ajax call happening here
var result = ''; // declare a var here
var vajx = $.ajax({
url: url,
type: "POST",
data: {
'h': hidden,
.....
async: false
}
});
vajx.done(function (data) {
result = data; // <-----------change here
});
if(result != ""){ // <---------------change here
$("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(result); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
and then you can change your if check little bit like this:
$.ajax has a success handler which handles the response received from the server. So you could do something like this:
$.ajax({
url:url,
type:"POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E},
async:false,
success:function(ret)
{
//the response received from url will be stored in "ret"
var vajx = ret;
// use your conditions here now
}
});

Categories

Resources