How to create checkbox with getJson - javascript

Please i will be happy to get help on how to display checkbox along with my data returned with getJSON as shown in the image
Below is the code of my ajax/getJSON:
$.ajax({
type:"post",
url:"clsAddCart.php",
data:dataString,
cache: false,
success:function(data){
// $("#display_info").html("Item Added Successfully");
//display cart data
var url="clsGetCartData.php";
$.getJSON(url,'transID='+$('#transID').val(),
function(result)
{
$("#answer tbody").empty();
var alltrans=result["alldata"]; //get the list
for( i in alltrans)
{
var cartdata=alltrans[i]; //get
var cartID=cartdata["cartID"];
var partName=cartdata["partName"];
var qty=cartdata["qty"];
var productID=cartdata["productID"];
var Sellprice=cartdata["Sellprice"];
var Discount=cartdata["Discount"];
var Total=cartdata["Total"];
var myid="<input type='checkbox' name='uid[]' value = 1>";//=cartdata["myid"];
var myDel=Document.createElement("input");
myDel.setAttribute('type','checkbox');
myDel.setAttribute('name','DelItem');
myDel.setAttribute('value',cartdata["cartID"]);
var htmlCode="<tr id='"+productID+"'>";
htmlCode+="<td>"+myid+"</td>";
htmlCode+="<td>"+cartID+"</td>";
htmlCode+="<td>"+partName+"</td>";
htmlCode+="<td>"+Sellprice+"</td>";
htmlCode+="<td>"+qty+"</td>";
htmlCode+="<td>"+Discount+"</td>";
htmlCode+="<td>"+Total+"</td>";
htmlCode+="<td>"+ document.body.appendChild(myDel);+"</td>";
/* htmlCode+="<td>"+qty+"</td>";
htmlCode+="<td>"+Sellprice+"</td>";*/
htmlCode+="</tr>";
$("#answer tbody").append(htmlCode);
} //end for loop
$("#answer tr").click(function()
{
dataSelected($(this).attr("id"));
}
);
} //end success callback function
); //end method call to getJSON
It shows and error
(Uncaught TypeError: Document.createElement is not a function)
I will be very happy to receive your help.
Thank you.

Replace this
htmlCode+="<td>"+ document.body.appendChild(myDel);+"</td>";
By
htmlCode+='<td><input type="checkbox" id="delete'+myid+'" name="delete'+myid+'" value=""></td>';

Related

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

How to restore Jesson's value and put it into outside variable

I have a problem with this code
I manage to take the values from the json and put them into variables but I can not use them outside the function
what am i doing wrong ?
var sensor_name1;
var lat1;
var lng1;
var sensor_name2;
var lat2;
var lng2;
var sensor_name3;
var lat3;
var lng3;
$(function (){
var $sensors = $('#sensors');
$.ajax({
type:'GET',
url:'http://127.0.0.1:5000/',
success: function(sensors){
$.each(sensors, function(i, sensor) {
if (i==0){
$sensors.append(sensor_name1=sensor.name, lat1=sensor.lat, lng1=sensor.lng);
}
if(i==1){
$sensors.append(sensor_name2=sensor.name, lat2=sensor.lat, lng2=sensor.lng);
}
if (i==2){
$sensors.append(sensor_name3=sensor.name, lat3=sensor.lat, lng3=sensor.lng);
}
});
console.log('sensor one : ',sensor_name1, lat1, lng1);
console.log('sensor tow : ',sensor_name2, lat2, lng2);
console.log('sensor three : ',sensor_name3, lat3, lng3);
}
});
});
Hi and welcome on Stack Overflow :)
JavaScript Ajax is asynchronous and you execute console.log() before these variables receive a value.
But in your case you pass to append() which accepts a htmlString, Element, Text, Array or jQuery parameter a assignment of value expression. You don't append a child, but you declared it using append()
You must have to wait for response from server and after use that.
$(function () {
var $sensors = $('#sensors');
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:5000/',
success: function (sensors) {
$.each(sensors, function (i, sensor) {
let sensorInfo = 'sensor #'+i+': '+sensor.name+' '+sensor.lat+' '+sensor.lng;
console.log(sensorInfo);
$sensors.append('<p>'+sensorInfo+'</p>')
});
}
});
});
Greetings, plum!
Sources:
Asynchronous on MDN: https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous
jQuery Docs: https://api.jquery.com/jQuery.get/#jQuery-get-url-data-success-dataType

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

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 variables into ajax function JQuery

I have an AJAX function triggerd by a click which basically copies one table row into another table.
The problem I am having is that I get the required variables from the original table row before the AJAX request however these variables don't seem to be passed to the success function and they come out as undefined.
Is there anyway to pass the variables to the function ?
$('.addfile_popup').on('click', '.add2_fl', function(){
var file_id1=$(this).data('file');
var id=$('.useri').val();
var file_name1=$(this).closest('tr').children('td:first').text();
var upload_date1=$(this).closest('tr').children('td').eq(1).text();
var upload_desc=$(this).closest('tr').children('td').eq(2).text();
var job_idx=$(this).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data:data,
success:function(html){
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
});
});
$('.addfile_popup').on('click', '.add2_fl', function(){
var file_id1=$(this).data('file');
var id=$('.useri').val();
var file_name1=$(this).closest('tr').children('td:first').text();
var upload_date1=$(this).closest('tr').children('td').eq(1).text();
var upload_desc=$(this).closest('tr').children('td').eq(2).text();
var job_idx=$(this).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
// closure function that wrap your variables
function success(file_id1, file_name1, upload_date1 ... ) {
return function(html) {
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data:data,
success: success(file_id1, file_name1, upload_date1 ...)
});
});
You need to use a closure. You can read about them here: How do JavaScript closures work?
This should work:
$('.addfile_popup').on('click', '.add2_fl', function(){
var me = this;
(function() {
var file_id1=$(me).data('file');
var id=$('.useri').val();
var file_name1=$(me).closest('tr').children('td:first').text();
var upload_date1=$(me).closest('tr').children('td').eq(1).text();
var upload_desc=$(me).closest('tr').children('td').eq(2).text();
var job_idx=$(me).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data: {
job_id: job_idx,
file_id: file_id1,
user_id: id
},
success:function(html){
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
});//end ajax
})();
});
Note also I've changed how you pass data to the AJAX call.

Categories

Resources