Call function after some period time - javascript

I'm having a problem and don't know how to solve it. I have two functions in Javascript, both are called via AJAX, first function get values and insert records in DB and second function reads from DB and show the results. Since first function get values remotely sometimes response times are larger than second function and for that reason second function executes before first. What I need is to call buildTablesFromDB() only if AJAX call for buildClassification() is done. This is how my code looks like:
$(document).ready(function() {
function buildTablesFromDB() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/reader.php",
success: function(data) {
$("#clasification-data").html();
if (data.response === false) {
$(".alert").show();
$(".close").after(data.error);
} else {
if (data.html_content.position.length != 0) {
$("#clasification-holder").show();
var iterator = data.html_content.position;
var tr = "";
$.each(iterator, function(key, value) {
tr += "<tr>";
tr += '<td><img src="' + value.team_image + '" alt="' + value.team_name + '" title="' + value.team_name + '"> ' + value.team_name + '</td>';
tr += '<td>' + value.team_jj + '</td>';
tr += '<td>' + value.team_jg + '</td>';
tr += '<td>' + value.team_jp + '</td>';
tr += '<td>' + value.team_difference + '</td>';
tr += '<td><span class="glyphicon glyphicon-play"></span><span class="glyphicon glyphicon-stop"></span></td>';
tr += '</tr>';
});
$("#clasification-data").html(tr);
}
}
},
error: function() {
request.abort();
}
});
}
function buildClassification() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
// some error
}
},
error: function() {
request.abort();
}
});
}
window.setInterval(function() {
buildClassification();
}, 1800000); // Updates table results each 30 minutes
window.setInterval(function() {
buildTablesFromDB();
}, 1800000); // Updates table results each 30 minutes
buildClassification();
buildTablesFromDB();
});
How I can get this done?

you can call buildTablesFromDB() in the callback method of buildClassification()
e.g.
....
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
//
}else{
buildTablesFromDB();
}
},

Related

Display font awesome in jQuery AJAX

I want to display fontawesome icon if the user level is equal to 1 or etc. How can i do that in this code. i got an error if i used if else statement inside. Thanks in advance!
function show_product(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('User/userData')?>',
async : true,
dataType : 'json',
success : function(data){
var html = '';
var i;
var q = '';
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].create_at+'</td>'+
'<td>'+data[i].user_email+'</td>'+
'<td>'+data[i].user_name+'</td>'+
'<td>'+data[i].user_lastname+'</td>'+
'<td>'if (data[i].user_level == '1') {
++
}'</td>'+
'<td>'+data[i].status+'</td>'+
'</tr>';
}
$('#show_data').html(html);
}
});
}
You can do using the ternary operator
function show_product(){
$.ajax({
type : 'ajax',
url : '<?php echo site_url('User/userData')?>',
async : true,
dataType : 'json',
success : function(data){
var html = '';
var i;
var q = '';
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+data[i].create_at+'</td>'+
'<td>'+data[i].user_email+'</td>'+
'<td>'+data[i].user_name+'</td>'+
'<td>'+data[i].user_lastname+'</td>'+
'<td>'+ data[i].user_level==1?'<i class="fa"></i>':'<i class="fa"></i></td>'
+
'<td>'+data[i].status+'</td>'+
'</tr>';
}
$('#show_data').html(html);
}
});
}
The problem is most likely because the code don't know that you want run the if statement.
'<td>'if (data[i].user_level == '1') as you can see there is nothing separating the string <td> and the statement if (data[i].user_level == '1')
Try something like this:
function show_product() {
$.ajax({
type: 'ajax',
url: '<?php echo site_url('
User / userData ')?>',
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var q = '';
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>' + data[i].create_at + '</td>' +
'<td>' + data[i].user_email + '</td>' +
'<td>' + data[i].user_name + '</td>' +
'<td>' + data[i].user_lastname + '</td>' +
'<td>';
if (data[i].user_level == '1') {
html += '<i class="fas fas-user"></i>'
}
html += '</td>' +
'<td>' + data[i].status + '</td>' +
'</tr>';
}
$('#show_data').html(html);
}
});
}

Laravel: Variables showing as undefined when appending to table

I'm retrieving data from a database via AJAX GET call, ater succesfull response I print the data by appending an html template to my table, I am getting the results back all right (in JSON format) but when appending them to table they all appear as undefined:
Here is my controller method:
public function index()
{
$reviews = Review::all();
return response()->json([
'success' => 'Todas las opiniones recogidas',
'reviews' => $reviews,
]);
}
This is my JQuery code where I append the results, I'm fairly certain the error is in here:
$.ajax({
async: true,
url: '/reviews',
type: 'GET',
dataType: 'JSON',
success: function (data) {
$('.row[data-link=' + linked_entry + ']').remove();
$.each(data, function (index, item) {
var reviews_row = '<tr class="row" data-link="reviews">';
reviews_row += '<td>' + data.body + '</td>';
reviews_row += '<td>' + data.author + '</td>';
reviews_row += '<td>' + data.site + '</td>';
reviews_row += '<td style="text-align:center;"><input type="checkbox" name="isVisible" '+(data.isVisible ? 'checked' : '')+'></td>';
reviews_row += '</tr>';
$('.entry_table_container[data-link=' + linked_entry + ']').append(reviews_row);
});
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Change this:
$.each(data, function (index, item) {
To this:
$.each(data.reviews, function (index, item) {
and then:
item.body, item.author etc in your loop as one of the other contributors mentioned

Loading Ajax Data Dynamically

I have a bunch of jQuery functions which gets JSON data from a MySQL database and displays it on certain pages within my application.
i have about 15 of these functions that look similar to the below and i would like to tidy them up and convert them to one major function which returns data based on the variables passed to the function. IE getdata(subscriptions) would display the subscriptions.
My issue is i'm not sure how to pass the column names to the function from the ajax query and remove the value.column-name from the function.
Example function from application
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value+
'</td><td>' + value.subscription_name +
'</td><td>' + value.subscription_cycle +
'</td><td>' + value.subscription_cost +
'</td><td>' + value.subscription_retail +
'</td><td>' + value.subscription_profit +
'</td><td>' + value.subscription_margin +
'</td><td>' + value.subscription_markup +
'</td></tr>';
});
$('#subscription-results').html(trHTML);
},
});
}
Any help is very much appreciated as i'm fairly new to jQuery
You can refer to this code:
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
$('#subscription-results').html(parseColumns(response));
},
});
}
function parseColumns(columns) {
var html = '';
if (Object.prototype.toString.apply(columns) === '[object Array]') {
$.each(columns, function(key, value) {
html += parseColumn(value);
})
} else {
html += parseColumn(columns);
}
function parseColumn(column) {
var trHTML = '<tr><td>' + column + '</td>';
for (var key in column) {
trHTML += '<td>' + column[key] + '</td>'
}
trHTML += '</tr>';
return trHTML;
}
return html;
}

MVC: Get JSON data from a controller using AJAX failed

I'm trying to query data using AJAX from a controller, my controller is:
[HttpGet]
public ActionResult GetTestStatus(string userName)
{
var db = new SREvalEntities();
var allTests = db.Tests
.Where(x => string.Equals(x.Owner, userName))
.Select(x => new { CreateDate = x.CreateDate, EndDate = x.EndDate, Status = x.Status })
.OrderByDescending(x => x.CreateDate)
.ToList();
return Json(allTests, JsonRequestBehavior.AllowGet);
}
And my javascript code in an extern file is:
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
}
});
$("#ShowDetail").html(txt);
}
When I tried to debug this function, the code will never excute to
$("#ShowDetail").html(txt);
And my page will never be changed. How can I get it work? Thanks.
As you are using $.ajax(), which is asynchronous. Thus the $("#ShowDetail").html(txt) is called before the value is returned from API.
You should set the html() after the each block
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias.value }, //Use the value property here
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt); //Move code to set text here
}
});
}
Try the following function
function Filter() {
var userAlias = $("#UserAliasInput").val();//change this
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt);//place this in the success function
}
});
}

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN
function createCheckBoxPlatform(data) {
var platform = "";
$.each(data, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' + getOS();
});
$('#platform').append((platform));
}
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
I think you have to turn around your logic. The createCheckBoxPlatform loop will have completed before the getOS() ajax call returns, unless it's a synchronous call.
You could split the functions into pieces, gather the getOS data for each data point you have, then construct the checkboxes when your ajax call returns.
You can make your ajax call async and have to make no changes to your current logic. But your execution will stop till you don't get the callback to your ajax call.
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
async: true,
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value.
Maybe you could first, get the os list and then output what you need, like this:
function createCheckBoxPlatform(myDatas) {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (osList) {
var os = '<div>';
$.each(osList, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
$.each(myDdatas, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>'+os
});
$('#platform').append((platform));
}
});
}

Categories

Resources