AJAX not overwriting global variable JQUERY - php

$.each(data, function (index, info) {
var a = info.notes;
var b = info.permission;
//var c = null;
var c = null;
$.ajax({
url: "assets/getExpiration.php?expiry=" + info.expiration,
type: "GET",
dataType: "text"
}, function(data){
c = data;
});
var z = null;
switch(info.stars) {
case 0: z = "<img src='assets/img/0star.png'/>"; break;
case 1: z = "<img src='assets/img/1star.png'/>"; break;
case 2: z = "<img src='assets/img/2star.png'/>"; break;
case 3: z = "<img src='assets/img/3star.png'/>"; break;
default: z = "<label class='label label-danger'>" + c + "</label>"; break;
}
var notes = a.length > 0 ? "<i class='fa fa-file'></i>" : "";
var permission = b.length > 0 ? "<i class='fa fa-warning'></i>" : "";
if (info.status == 'EXPIRED') {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-danger disabled'>" + info.username + " " + permission + " " + notes + "</button>");
} else {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-primary'>" + info.username + " " + permission + " " + notes + "<br> " + z + "</button>");
}
});
c is not being edited. HOWEVER when I console.log(c) inside the $.ajax() it gives me the proper value. However when I console.log() outside of the $.ajax() it gives me 'null'. I've looked up MANY MANY MANY MANY stackoverflow similar questions but all the answers did not work or maybe I was just missing something.

Are you assuming that the code from:
var z = null;
switch(info.stars) {....
will wait for your ajax request to complete? If so, that's not quite how it works.
Ajax is going to fire of a request asynchronously whilst the rest of your code continues to execute (assuming you don't specify it should run synchronously <-- that's not a good idea though).
If you want to work with values returned by AJAX you need to add this code to the ajax options success property or similar which will be executed when it completes.

$.ajax is an asynchronous method that instantly returns, but will run the success and error functions after the HTTP request is completed in the background.
You will need to move your code into it's own function that is called inside the $.ajax method. Below is an example.
$.ajax({
url: "assets/getExpiration.php?expiry=" + info.expiration,
type: "GET",
dataType: "text"
}, function (data) {
c = data;
var z = null;
switch(info.stars) {
case 0: z = "<img src='assets/img/0star.png'/>"; break;
case 1: z = "<img src='assets/img/1star.png'/>"; break;
case 2: z = "<img src='assets/img/2star.png'/>"; break;
case 3: z = "<img src='assets/img/3star.png'/>"; break;
default: z = "<label class='label label-danger'>" + c + "</label>"; break;
}
var notes = a.length > 0 ? "<i class='fa fa-file'></i>" : "";
var permission = b.length > 0 ? "<i class='fa fa-warning'></i>" : "";
if (info.status == 'EXPIRED') {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-danger disabled'>" + info.username + " " + permission + " " + notes + "</button>");
} else {
$("#pendingCall" + info.callNum).append("<button onclick=\"loadPlayer('" + info.playerTag+ "', '" + info.status + "', "+ info.callNum +")\"class='btn btn-primary'>" + info.username + " " + permission + " " + notes + "<br> " + z + "</button>");
}
});

Related

Error in console output for json_encode to display the result in console?

FYI, I am working on localhost with wampserver, using PHP and AJAX, trying to display the JSON data rows (which are around 1526). and the problem is i am not able to display the rows which are based on the search conditions.
Output of print_r($result_array); in console output as below. here in below pic don't worry for console error this error is becoz of PHP array used in parsing JSON. This output i used to test weather my server PHP file is working correctly or not but it is working correctly.
After that i checked my encoding function, for which output of echo json_encode($result_array); i am getting red console error for some search condition and in other search condition i am able to display results correctly.
For example, below two images
I am not able to figure out what is happening to my code.
File search.php
<?php
// send a JSON encoded array to client
include('connection.php');
$sqlFlag = 0;
function queryDelimiter(){
global $sqlFlag;
if ($sqlFlag == 0){
$sqlFlag = 1;
return ' WHERE ';
}else{
return ' AND ';
}
}
$selectSQL = "SELECT * FROM tbl_main_lead_info";
if(isset($_POST['lead_status']) and strlen(trim($_POST['lead_status'])) > 0){
$selectSQL .= queryDelimiter()."LeadStatus = '".$_POST['lead_status']."'";
}
if(isset($_POST['lead_owner']) and strlen(trim($_POST['lead_owner'])) > 0){
$selectSQL .= queryDelimiter()."LeadAddedBy = '".$_POST['lead_owner']."'";
}
if(isset($_POST['company_name']) and strlen(trim($_POST['company_name'])) > 0){
$selectSQL .= queryDelimiter()."Company = '".$_POST['company_name']."'";
}
if(isset($_POST['tech_area']) and strlen(trim($_POST['tech_area'])) > 0){
$selectSQL .= queryDelimiter()."TechArea = '".$_POST['tech_area']."'";
}
if(isset($_POST['firm_size']) and strlen(trim($_POST['firm_size'])) > 0){
$selectSQL .= queryDelimiter()."FirmSize = '".$_POST['firm_size']."'";
}
if(isset($_POST['firm_type']) and strlen(trim($_POST['firm_type'])) > 0){
$selectSQL .= queryDelimiter()."FirmType = '".$_POST['firm_type']."'";
}
if(isset($_POST['country_name']) and strlen(trim($_POST['country_name'])) > 0){
$selectSQL .= queryDelimiter()."Country = '".$_POST['country_name']."'";
}
if(isset($_POST['state_name']) and strlen(trim($_POST['state_name'])) > 0){
$selectSQL .= queryDelimiter()."State = '".$_POST['state_name']."'";
}
if(isset($_POST['city_name']) and strlen(trim($_POST['city_name'])) > 0){
$selectSQL .= queryDelimiter()."City = '".$_POST['city_name']."'";
}
if(isset($_POST['start_date']) and strlen(trim($_POST['start_date'])) > 0){
$selectSQL .= queryDelimiter()."LastContactDate >='".$_POST['start_date']."'";
}
if(isset($_POST['end_date']) and strlen(trim($_POST['end_date'])) > 0){
$selectSQL .= queryDelimiter()."NextContactDate <= '".$_POST['end_date']."'";
}
$selectSQL .= " ORDER BY FirstName ASC, LastName ASC, Lead_Id ASC";
$result_array = array();
$result = $conn -> query ($selectSQL);
if(mysqli_num_rows($result) > 0){
while ($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
// print_r($result_array);
echo json_encode($result_array);
// $selectSQL = "SELECT * FROM tbl_main_lead_info as M, tbl_campaign_info as C";
$conn->close();
?>
File loadtable.js
// This is script to load table based on filter section
$(document).ready(function() {
// Campaign Submit Info
$('[name="search_submit"]').click(function(e) {
$('#load-csv-file-button').attr('style','display:none;');
$("#filterRecords").attr('style','display:block;');
$('#add_lead_info').attr('style','display:none;');
e.preventDefault();
// GET the admin and user id value
var adminvalue = $('#filterformpost').find('[name="adminvalue"]').val();
var useridvalue = $('#filterformpost').find('[name="useridvalue"]').val();
var lead_owner = $('#filterformpost').find('#lead_owner_select option:selected').val();
var lead_status = $('#filterformpost').find('#lead_status_select option:selected').val();
var company_name = $('#filterformpost').find('#company_name_select option:selected').val();
var tech_area = $('#filterformpost').find('#tech_area_select option:selected').val();
var firm_size = $('#filterformpost').find('#firm_size_select option:selected').val();
var firm_type = $('#filterformpost').find('#firm_type_select option:selected').val();
var country_name = $('#filterformpost').find('#country_name_select option:selected').val();
var city_name = $('#filterformpost').find('#city_name_select option:selected').val();
var state_name = $('#filterformpost').find('#state_name_select option:selected').val();
var start_date = $('#filterformpost').find('#start_date_search').val();
var end_date = $('#filterformpost').find('#end_date_search').val();
// console.log('adminvalue: '+adminvalue)
// console.log('useridvalue: '+useridvalue)
// console.log('lead_owner: '+lead_owner)
// console.log('country_name: '+country_name)
// console.log('State: '+state_name)
$.ajax({
type: "POST",
url: "./server/search.php",
data: {
"lead_owner": lead_owner,
"lead_status": lead_status,
"company_name": company_name,
"tech_area": tech_area,
"firm_size": firm_size,
"firm_type": firm_type,
"country_name": country_name,
"city_name": city_name,
"state_name": state_name,
"start_date": start_date,
"end_date": end_date
},
beforeSend: function() {
$('.search_lead_filter_message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success:function(data){
// console.log(data)
console.log("Data Length: "+data.length)
console.log(data)
if(data.length == 0){
$('.search_lead_filter_message_box').html('');
$("#filterRecords").html('No results fetched');
}
var result = $.parseJSON(data);
// console.log(result)
//###########################################
// Pagination code start
//###########################################
$('.search_lead_filter_message_box').html('');
$("#filterRecords").empty();
//###########################################
// Pagination code end
//###########################################
$("#pagination").attr('style', 'display:block;');
$("#number_of_rows").attr('style','display:block;');
$('#button-prev-next').attr('style','display:block;');
paginate_json_data(result, adminvalue, useridvalue)
}
});
});
});
function paginate_json_data(userDetails, adminvalue, useridvalue) {
adminvalue = adminvalue
useridvalue = useridvalue
userDetails = userDetails
var table = '';
table = $("<table></table>");
$('#pagination').html('<div id="nav-numbers" class="col nav"></div>');
$('#number_of_rows').html('');
$('#number_of_rows').html('<p1>Total number of leads fetched: ' + userDetails.length + '</p1>');
$('#button-prev-next').html('<button class="col PreviousButton" id="PreValue"><i class="ion-skip-backward"></i> Previous</button><button class="col NextButton" id="nextValue">Next <i class="ion-skip-forward"></i></button>');
var max_size = userDetails.length;
var sta = 0;
var elements_per_page = 10;
var limit = elements_per_page;
if(max_size<10){
// #####################################
// NUMBER OF ROWS A < 10 START START
// #####################################
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Email</th><th style="width: 150px;">Phone</th><th>City</th><th>State</th><th>Country</th><th>Lead Status</th></thead>');
table.append('<tbody id="myTable"></tbody>');
goFun_Modified(sta, max_size);
function goFun_Modified(sta, limit) {
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + (i+1) + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.php?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td style="width: 150px;" >' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].City + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td></tr>';
console.log(tab)
$('#myTable').append(tab)
}
} // Function ended
$("#filterRecords").html(table);
$('#nextValue').click(function() {
// checks if it's the last page
if (currentPage < maxPage) {
currentPage++;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("End of page");
}
});
$('#PreValue').click(function() {
// checks if it's the first page
if (currentPage > 0) {
currentPage--;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("Start of page")
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + (i+1) + '</button>');
}
$('.nav button').click(function() {
var start = $(this).text()-1;
// $(this).css({"background-color": "#e67e22", "color": "#ffffff"});
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun_Modified(start * 10, limit);
let $self = $(this);
// gets index of button relative to it's siblings
// https://api.jquery.com/index/
currentPage = $self.index();
$pagingBtn.removeClass('active');
$self.addClass('active');
});
// saves all the paging buttons for reusing, instead of calling $() every time
let $pagingBtn = $('#nav-numbers .btn');
let maxPage = $pagingBtn.length - 1;
let currentPage = 0;
$('.nav button')[0].click()
// #####################################
// NUMBER OF ROWS A < 10 END
// #####################################
}else{
// #####################################
// NUMBER OF ROWS A > 10 START
// #####################################
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Email</th><th>Phone</th><th>City</th><th>State</th><th>Country</th><th>Lead Status</th></thead>');
table.append('<tbody id="myTable"></tbody>');
goFun(sta, limit);
function goFun(sta, limit) {
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + (i+1) + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.php?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td>' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].City + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td></tr>';
$('#myTable').append(tab)
}
$("#filterRecords").html(table);
}// FUNCTION ENDED
$('#nextValue').click(function() {
var next = limit;
if (max_size >= next) {
def = limit + elements_per_page;
limit = def
$('#myTable').empty();
if (limit > max_size) {
def = max_size;
}
goFun(next, def);
}
// checks if it's the last page
if (currentPage < maxPage) {
currentPage++;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("End of page");
}
});
$('#PreValue').click(function() {
var pre = limit - (2 * elements_per_page);
if (pre >= 0) {
limit = limit - elements_per_page;
$('#myTable').empty();
goFun(pre, limit);
}
// checks if it's the first page
if (currentPage > 0) {
currentPage--;
$pagingBtn.removeClass('active');
$pagingBtn.eq(currentPage).addClass('active')
} else {
alert("Start of page")
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + (i+1) + '</button>');
if(i == number){
}
}
$('.nav button').click(function() {
var start = $(this).text()-1;
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun(start * 10, limit);
let $self = $(this);
// gets index of button relative to it's siblings
// https://api.jquery.com/index/
currentPage = $self.index();
$pagingBtn.removeClass('active');
$self.addClass('active');
});
// saves all the paging buttons for reusing, instead of calling $() every time
let $pagingBtn = $('#nav-numbers .btn');
let maxPage = $pagingBtn.length - 1;
let currentPage = 0;
$('.nav button')[0].click()
// #####################################
// NUMBER OF ROWS A > 10 END
// #####################################
}
}
Updated:
Try add content-type specs to http header:
header("Content-Type: application/json");
and set UNICODE feature in json_encode:
echo json_encode($result_array, JSON_UNESCAPED_UNICODE);

Make it pretty using php

object(stdClass)#1 (1) {
["return"]=>
string(43362) "[{"Searchstring":"?showitemlist=1&Keyword=blue&acctwebguid=12bad325-a118-4778-825a-cc7d5308e24f&orderby=ItemName%20DESC&requestguid=29E60B17-8601-4839-AD00-00DB0D45A2CB","Recordcount":15446},{"Maxretail":7.42000000,"Displayname":"","Suplitemno":"COA09B/K","Supplieritemid":"D7784D83-F63D-4219-BDB1-F7AE76F74CC8","Minretail":5.99000000,"Minqty":25,"Rushavailable":0,"Imagepath":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/medium/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597800","Imagepathsm":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/small/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597799","Prodtime":10,"Imagepathlg":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/large/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597800","Companyname":"Graphik Business Accessories","Displayno":"","Imagepathmd":"images/products/EA8E5917-F1D9-4089-BC09-DDE2FF03452F/medium/D7784D83-F63D-4219-BDB1-F7AE76F74CC8.jpg?_=1423597800","Shownopricing":0,"Itemname":"Zume Coaster Set"},{"Maxretail":50.38000000,"Displayname":"","Suplitemno":"7003-47","Supplieritemid":"F7374437-2DF5-4D4B-B654-32F7C7B8971E","Minretail":39.98000000,"Minqty":10,"Rushavailable":0,"Imagepath":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","addlImagesLarge":["images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_b_1.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_b_3.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_d.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_d_2.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/7003_47-7003_47bk_d_3.jpg?_=1438623370"],"Imagepathsm":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","Prodtime":5,"Imagepathlg":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/large/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","addlImagesSmall":["images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_b_1.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_b_3.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_d.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_d_2.jpg?_=1438623370","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/small/7003_47-7003_47bk_d_3.jpg?_=1438623371"],"Companyname":"Leed&apos;s / Leeds","Displayno":"","Imagepathmd":"images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/F7374437-2DF5-4D4B-B654-32F7C7B8971E.jpg?_=1438623367","addlImagesMed":["images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_b_1.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_b_3.jpg?_=1438623368","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_d.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_d_2.jpg?_=1438623369","images/products/A0FB382C-C7AE-11D3-896A-00105A7027AA/medium/7003_47-7003_47bk_d_3.jpg?_=1438623370"],"Shownopricing":0,"Itemname":"Zoom® Audio Decibel Bluetooth Speaker"},.......
<script>
$(document).ready(function() {
var data = '[{"Maxretail":...,"Itemname":"Youth Chameleon T-Shirt"]';
var table = '<table><thead><th>First Name</th><th>Last Name</th><th>Image</th><th>More</th></thead><tbody>';
var obj = $.parseJSON(data);
$.each(obj, function() {
table += '<tr><td>' + this['Itemname'] + '</td><td>' + this['Supplieritemid'] + '</td><td><img src="https://cdn.distributorcentral.com/' + this['Imagepath'] + ' alt="' + this['Itemname'] + '" /></td><td><img src="https://cdn.distributorcentral.com/' + this['addlImagesSmall'] + ' alt="' + this['Itemname'] + '" />' + this['addlImagesSmall'] + '</td></tr>';
});
table += '</tbody></table>';
document.getElementById("datalist").innerHTML = table;
});

PHP-jQuery: Display a timer on each table row where end time is not set

I have a function that displays a countup timer but I've only been able to make it work for a single row. I'd like to make a timer appear on each row where the end time of the action has not yet been set.
This is the full code.
<script>
$('document').ready(function()
{
var uni_id = //value of id needed to query the database table;
$.ajax({
type : 'POST',
url : 'get_time.php',
dataType: 'json',
data : {uni_id: uni_id},
cache: false,
success : function(result)
{
for (var i = 0; i < result.length; i++){
var startDateTime = new Date(result[i].uni_start_time); //Not sure if it's wrong to add all returning values here but so far it works but only for a single row on the table.
var startStamp = startDateTime.getTime();
var newDate = new Date();
var newStamp = newDate.getTime();
var timer;
var rec_id = result[i].rec_id;
function updateTimer() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var days = Math.floor(diff/(24*60*60));
diff = diff-(days*24*60*60);
var hours = Math.floor(diff/(60*60));
diff = diff-(hours*60*60);
var minutes = Math.floor(diff/(60));
diff = diff-(minutes*60);
var seconds = diff;
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
$("#on_going_"+rec_id).html(hours+':'+minutes+':'+seconds);
}
setInterval(updateTimer, 1000);
$('#uni_time_table tbody').append(
'<tr>'
+'<td class="center hidden" id="'+result[i].rec_id+'">' + result[i].rec_id + '</td>'
+'<td class="center">' + result[i].uni_id + '</td>'
+'<td>' + result[i].uni_name + '</td>'
+'<td>' + result[i].uni_loc + '</td>'
+'<td class="center">' + result[i].uni_date + '</span></td>'
+'<td class="center">' + result[i].uni_start_time + '</td>'
+(result[i].uni_end_time == null ?
'<td class="center"></td>' //this will always be empty if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_end_time + '</td>'
)
+(result[i].uni_end_time == null ?
'<td class="center" id="on_going_'+result[i].rec_id+'"></td>' //the timer will only be triggered here if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_total_time + '</td>' //this will display the total time as long as the uni_end_time is set.
)
+'</tr>');
}
}
});
});
</script>
So far, only the first entry in the table displays the timer. Every time I add another entry, that second entry just remains blank while the timer still works with the first entry.
How can I make the timer work for each row on the table?
EDIT: Sample Data from json
rec_id "1"
uni_date "2016-10-28"
uni_loc "Custom Location"
uni_id "2356"
uni_name "Custom Name"
uni_start_time "10/28/2016 09:04:28"
uni_end_time null
uni_total_time null // this shows null because end_time is empty which is when the timer should kick in.
Here is a solution for you with little modifications of your code:
var startStamp = [];
function updateTimer(result) {
var newDate = new Date();
var newStamp = newDate.getTime();
for (var j = 0; j < result.length; j++) {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp[j])/1000);
var days = Math.floor(diff/(24*60*60));
diff = diff-(days*24*60*60);
var hours = Math.floor(diff/(60*60));
diff = diff-(hours*60*60);
var minutes = Math.floor(diff/(60));
diff = diff-(minutes*60);
var seconds = diff;
days = (String(days).length >= 2) ? days : '0' + days;
hours = (String(hours).length >= 2) ? hours : '0' + hours;
minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
$("#on_going_"+result[j].rec_id).html(hours+':'+minutes+':'+seconds);
}
}
$('document').ready(function()
{
var uni_id = 1;//
$.ajax({
type : 'POST',
url : 'get_time.php',
dataType: 'json',
data : {uni_id: uni_id},
cache: false,
success : function(result) {
for (var i = 0; i < result.length; i++) {
var startDateTime = new Date(result[i].uni_start_time);
startStamp[i] = startDateTime.getTime();
$('#uni_time_table tbody').append(
'<tr>'
+ '<td class="center hidden" id="' + result[i].rec_id + '">' + result[i].rec_id + '</td>'
+ '<td class="center">' + result[i].uni_id + '</td>'
+ '<td>' + result[i].uni_name + '</td>'
+ '<td>' + result[i].uni_loc + '</td>'
+ '<td class="center">' + result[i].uni_date + '</span></td>'
+ '<td class="center">' + result[i].uni_start_time + '</td>'
+ (result[i].uni_end_time == null ?
'<td class="center"></td>' //this will always be empty if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_end_time + '</td>'
)
+ (result[i].uni_end_time == null ?
'<td class="center" id="on_going_' + result[i].rec_id + '"></td>' //the timer will only be triggered here if the uni_end_time is not set.
:
'<td class="center">' + result[i].uni_total_time + '</td>' //this will display the total time as long as the uni_end_time is set.
)
+ '</tr>');
}
setInterval((function () {
updateTimer(result);
}), 1000);
}
});
});

How can I loop all json data and insert into my HTML?

I'd like to insert the Json data into my file.php. And so each group of them are insert into group of divs. (with the same style etc.)
I have a feeling the way I am using is not smart... better solutions are very welcome. Thanks guys.
$.ajax({
url: feedURL,
jsonpCallback: 'jsonpCallback',
contentType:"application/json",
dataType: 'jsonp',
success: function(json) {
for (var i=0; i < 15; i++) {
var date = new Date(json.posts.data[i].created_time);
var months = ["/01/", "/02/", "/03/", "/04/", "/05/", "/06/", "/07/",
"/08/", "/09/", "/10/", "/11/", "/12/"];
$("#description").html(json.posts.data[i].message);
$("#caption").html(json.posts.data[i].caption);
$("#expire_date").html(date.getDate() + months[date.getMonth()] + date.getFullYear());
$("#fb_link").html(
'<a href="' + json.posts.data[i].link + '">'
+ 'Total Like: ' + json.posts.data[i].likes.summary.total_count
+ ' Total Share: ' + json.posts.data[i].shares.count
+ ' View on Facebook' + '</a>'
);
$("#profile_img").html('<img src="' + json.picture.data.url + '">');
$("#profile_name").html(json.name);
$("#full_fb_photo").html('<img src="' + json.posts.data[i].full_picture + '">');
}
},
error: function(e) {
console.log(e.message);
}
});
You can write your code in flowing way. Uncountable date print in your loop. If I know your data format, I will give you exact way.
Try this code.
for (var prop in json.posts.data) {
$("#description").html(json.posts.data[prop].message);
// other same as
}
Thanks guys, i have figured out in this way.
$.ajax({
url: feedURL,
jsonpCallback: 'jsonpCallback',
contentType:"application/json",
dataType: 'jsonp',
success: function(json) {
var social_list = "";
for (i=0; i < 15; i++) {
var date = new Date(json.posts.data[i].created_time);
var months = ["/01/", "/02/", "/03/", "/04/", "/05/", "/06/", "/07/",
"/08/", "/09/", "/10/", "/11/", "/12/"];
social_list += "<div class='social_item'><div class='item'><div class='heading'>";
social_list += "<img src='" + json.picture.data.url + "'/><span>" + json.name + "</span><i class='fa fa-facebook'></i></div>";
social_list += "<div class='content'><p>Created on" + date.getDate() + months[date.getMonth()] + date.getFullYear() + "</p>";
social_list += "<div><img src='" + json.posts.data[i].full_picture + "' /></div>";
social_list += "<p name=" + i + ">" + json.posts.data[i].message + "</p>";
social_list += "<div><a href='" + json.posts.data[i].link + "'> Total Likes: " + json.posts.data[i].likes.summary.total_count + "Total Share: " + json.posts.data[i].shares.count + " View on Facebook </a></div>";
social_list += "</div></div></div>"
}
$('#social_list').html(social_list);

Validating array of inputs using javascript

I hav a rather large form it has 8 fields for entering books .
Now for user to add more books there is a button add more books ,on click of which a javascript function is called and 7 out of 8 fields are duplicated.
User can add maximum 6 books , and all the input fields created dynamically have their names as arrays . I am able to post them and store in a table , Now i want to validate them using javascript.
I have been tryng to do this since a week and am a new to Javascript . Please help me.
MY JAVASCRIPT CODE
function addInput(divName){
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit)
{
alert("You have reached the limit of adding " + counter + " inputs");
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML ="<table>"+ "<tr align='right'>" + "<td>"+ " Name of book" + (counter + 1) + " " +" : <input type='text' name='bname1[]' > "+"</td>" + "</tr>"+"<tr align='right'>"+ "<td>"+" Name of Authour"+(counter + 1)+" "+": <input type='text' name='aname1[]'>"+"</td>"+"</tr>"+"<tr align='right'>"+"<td>"+"Publisher"+(counter+1)+" "+": <input tyme='text' name='pub1[]'>"+"</td>"+"</tr>"+ "<tr align='right'>" +"<td>"+ "ISDN Number " + (counter + 1) +" "+ ": <input type='text' name='isdn1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" +"<td>"+ " Edition " + (counter + 1) + " "+": <input type='text' name='edi1[]'> "+"</td>" + "</tr>"+"<tr align='right'>" + "<td>"+ "Price"+(counter + 1) +" "+ " :<input type='number' name='cost1[]'>"+"</td>"+"</tr>"+"<tr align='right'>" + "<td>"+ "Number of copies"+(counter + 1) +" "+ ": <input type='number' name ='num1[]'> "+"</td>" + "</tr>"+ "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter=counter+1;
}
}
there is divsion in the html form to which all this is added.
Please help !
thanx in advance ..
here is your solution. http://codebins.com/codes/home/4ldqpbq
HTML
<div id="testDiv">
</div>
<button onclick="addInput('testDiv')">
Add New Items
</button>
<button onclick="validate('testDiv')">
Validate
</button>
JavaScript
var counter = 0;
var limit = 6
function addInput(divName) {
var bname1 = new Array();
var abname1 = new Array();
var cost1 = new Array();
var num1 = new Array();
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<table>" + "<tr align='right'>" + "<td>" + " Name of book" + (counter + 1) + " " + " : <input type='text' name='bname1[]' > " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Name of Authour" + (counter + 1) + " " + ": <input type='text' name='aname1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Publisher" + (counter + 1) + " " + ": <input tyme='text' name='pub1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "ISDN Number " + (counter + 1) + " " + ": <input type='text' name='isdn1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + " Edition " + (counter + 1) + " " + ": <input type='text' name='edi1[]'> " + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Price" + (counter + 1) + " " + " :<input type='number' name='cost1[]'>" + "</td>" + "</tr>" + "<tr align='right'>" + "<td>" + "Number of copies" + (counter + 1) + " " + ": <input type='number' name ='num1[]'> " + "</td>" + "</tr>" + "</table>";
// alert("counter +1 is "+counter+1);
document.getElementById(divName).appendChild(newdiv);
counter = counter + 1;
}
}
function validate(divName) {
var container = document.getElementById(divName).getElementsByTagName("input");
for (var len = container.length, i = 0; i < len; i++) {
// if only requried validation
if (container[i].value == "") {
container[i].style.borderColor = "red"
} else {
container[i].style.border = ""
}
//if you want saperate validation for each
switch (container[i].name) {
case "bname1[]":
//validate according to filed
break;
case "aname1[]":
//validate according to filed
break;
case "pub1[]":
//validate according to filed
break;
case "isdn1[]":
//validate according to filed
break;
case "edi1[]":
//validate according to filed
break;
case "cost1[]":
//validate according to filed
break;
case "num1[]":
//validate according to filed
break;
}
}
}
Couple of suggestions for you to consider:
1) consider grouping ALL the fields you want to duplicate inside a single div in your form.
Then when the user wants to add new item (book) all you will need to do will be copy the content of this div. This way you will maintain only one copy of field-set.
2) consider dynamic generic form validation too. You add the validation rules to your form field definition with extra attributes i.e. [<input ... validationRules="mandatory,minimumLength=10..." />] I think that you can achieve something similar with JQuery, but I personally prefer NOT to use large libraries to do small jobs.
3) consider giving your fields unique ids too.
use
var bname= document.getElementsByName('bname1[]');
var aname=document.getElementsByName('aname1[]'); .........
for(var i=0;i<bname.length;i++)
{
//Your validations
}
for(var i=0;i<aname.length;i++)
{
//Your validations
}.....
..
do this for all elements in your code..
Validation function example:
function validate_field(f) { // f is input element
var name = f.name; // or also f.getAttribute('name')
var value = f.value; // or also f.getAttribute('value'), but should be defined
var error_div = document.getElementById(name+'err');
//alert('name '+name+' value '+value);
if (name.indexOf('bname') == 0) { // if validate book name
if (value == '') { // e.g. book name should not be empty string?
error_div.innerHTML = 'book name cannot be empty!';
return false; // field is wrong
}
}
else if (name.indexOf('aname') == 0) { // if validate author name
if (value.length<2) {
error_div.innerHTML = 'author\'s name is too short!';
return false; // at least two characters long name? :)
}
}
else if (name.indexOf('pub') == 0) { // if validate publisher
if (value.length<2) {
error_div.innerHTML = 'publisher\'s name is too short!';
return false;
}
}
else if (name.indexOf('isdn') == 0) { // if validate ISDN Number
if (value == '') {
error_div.innerHTML = 'ISDN cannot be empty!';
return false;
}
}
else if (name.indexOf('edi') == 0) { // if validate Edition
if (value == '') {
error_div.innerHTML = 'edition cannot be empty!';
return false;
}
}
else if (name.indexOf('cost') == 0) { // if validate Price
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please write a price using digits!';
return false;
}
}
else if (name.indexOf('num') == 0) { // if validate Number of copies
if (value=='') {
error_div.innerHTML = 'Cannot be empty!';
return false;
}
if (isNaN(value)) {
error_div.innerHTML = 'Please number of copies via digits!';
return false;
}
}
error_div.innerHTML = 'ok';
return true; // field is ok
// you can also have a look at http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
}
Full working script here: pastebin.com/UkVP2uLb

Categories