I have a piece of code that retrieves the last question on a program and it is suposed to update the values of HTML5 progress bars with the latest values.
Now for some reason that I cannot find, when I console.log the data parameter, it is full. But when I try to use it nothing is shown.
Is there something wrong in the code that I cannot realize?
//Run timer
$(document).ready(function () {
if($('input[name=active_question]').val()!="")
{
start_timer();
}
});
function start_timer()
{
var x=0;
function doStuff() {
x++;
$('.timer').html(x+' sec');
console.log('Timer:'+x);
$.ajax({
method: "GET",
url: "/services/get_active_question/"
})
.done(function( data ) {
//It is time to regenerate the question values.
console.log('Data:'+data);
if(data['id']!=0)
{
regenerate_question(data);
}
});
}
setInterval(doStuff, 1000);
}
function regenerate_question(data)
{
if(data['id']!=0)
{
console.log('A: '+data['a']);
$('.progress-a').prop('value',data['a']);
$('.progress-b').prop('value',data['b']);
$('.progress-x').prop('value',data['x']);
$('.progress-y').prop('value',data['y']);
}
}
Your return from the ajax is json string. But the ajax is not identifying it as JSON. So you'll need to specify the dataType as JSON.
$.ajax({
method: "GET",
url: "/services/get_active_question/",
dataType: 'json'
}).done(function( data ) {
//It is time to regenerate the question values.
console.log('Data:'+data);
if(data['id']!=0)
regenerate_question(data);
});
Alternative way is to use
data = JSON.parse(data)
in the done function.
Related
I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}
What I want is a technique to refresh my div if there are changes in my database. Here is the point,
What i want: How can i condition to know if the first value from my database is lesser than the upcomming value.
In my situation, i put my ajax function to be run every 5secs here is it:
lastcountQueue is declared as global in javascript
function check_getqueue() {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
lastcountQueue = data[0]['count'];
}
});
}
Q:where would i put the condition something if lastcountQueue < data[0]['count]; condition means something if the data is lesser than lastcountQueue it means there was a change in my database portion.
Another Clear Situation for my question:
I want to make a function like these: the ajax will run every 5 seconds where it query a value to count my no. of queues in database. If my first query is giving me 5 value, and the second is giving me again another 5, then there must be nothing change happens, then if my third value gives me 4, where it is not equal to the last query, then i would do something
Probably something like this:
function check_getqueue() {
$.ajax({
url: siteurl+"sec_myclinic/checkingUpdates/"+clinicID+"/"+userID,
type: "POST",
dataType: "JSON",
success: function(data) {
var tmpCountQ = data[0]['count'];
if (tmpCountQ < lastcountQueue) {
// Process the change
}
lastcountQueue = tmpCountQ;
}
});
}
Here is the updated answer:
function check_getqueue() {
$.ajax({
url: siteurl + "sec_myclinic/checkingUpdates/" + clinicID + "/" + userID,
type: "POST",
dataType: "JSON",
success: function(data) {
if (data[0]['count'] != lastcountQueue) {
//Your logic here
lastcountQueue = data[0]['count'];
}
}
});
}
I need to execute 3 ajax requests. I know that they happen to be asynchronous by default (And making them synchronous messes up the VM, so I don't want to go that way.) The way I do it is by calling a function three times passing variables.
result = '';
parse(var1);
parse(var2);
parse(var3);
view();
function parse(variable) {
//ajax request here
$.ajax({
type: 'POST',
url: 'script.php',
data: {variable: variable},
success: function (data) {
//result stored in a global variable
result += data;
}
});
}
function view() {
//do something with result
}
But right now, the view() is triggered right away when the result isn't done cooking. How do I set them up to happen one after the other? I read about callbacks but they are very confusing since I don't have 3 distinct functions but just one taking different variables.
You could store your variables in an array and use a function to make your ajax call:
var variables = [var1, var2, var3];
function callParse() {
if(variables.length) {
var currentVar = variables.shift();
parse(currentVar);
}
else {
view();
}
}
function parse(variable){
//ajax request here
$.ajax({
type:"POST",
url:'script.php',
data:{variable:variable},
success:function(data)
{
result+=data;
callParse();
}
});
}
function view(){
//do something with result
}
Try chained promises - from: https://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/
$.when(
// Get the HTML
$.get("/feature/", function(html) {
globalStore.html = html;
}),
// Get the CSS
$.get("/assets/feature.css", function(css) {
globalStore.css = css;
}),
// Get the JS
$.getScript("/assets/feature.js")
).then(function() {
// All is ready now, so...
// Add CSS to page
$("<style />").html(globalStore.css).appendTo("head");
// Add HTML to page
$("body").append(globalStore.html);
});
You could try doing it this way:
parseAndView([var1, var2, var3]);
function parseAndView(vars, index) {
index = index || 0; //initialize index if not passed
//execute the AJAX call only if there are more variables to parse
if (index < vars.length)
//ajax request here
$.ajax({
type: "POST",
url: 'script.php',
data: {variable: vars[index]},
success: function (data) {
// result stored in a global variable
result += data;
// recursive call to parse another variable
parseAndView(vars, index++);
}
});
else
view();
}
function view() {
//do something with result
}
i've never used AJAX or JQuery before, but here's my attempt at dynamic loading(pulled from various examples here at stackoverflow)
this is the script i have in my view:(edited to comply with mayabelle's code.) doesn't throw either alert, and the breakpoint on DRequest never trips, but drequest produces results if called directly.
<script type="text/javascript">
$(document).ready(function () {
alert("testing123");
$response = DRequest;
alert("good at response");
$.ajax({
url: "request/drequest"
type: "GET",
dataType: "json",
success: function ($response) {
alert("I am an alert box2!");
// Do something with your response
var $tr = $('<tr>').append(
$('<td>').text($response.NeededByDate),
$('<td>').text($response.RequestedBy),
$('<td>').text($response.Username),
$('<td>').text($response.RequestedPCID),
$('<td>').text($response.RequestType_ID),
$('<td>').text($response.Division_ID),
$('<td>').text($response.ReqTypeIcon)
).appendTo('#requestTable');
console.log($tr.wrap('<p>').html());
}
});
setInterval(function () {
var url = '#';
$('body').load(url);
}, 300000);
});
</script>
is supposed to dynamically append one row at a time (until there are no more rows to add) from the DRequest JsonResult (this is producing results when called directly by way of the addressbar). this should reload the whole page every 5 minutes(300000 seconds).
the JsonResult looks like this
Public Function DRequest() As JsonResult
Dim Reqs = _db.dRequestGetAll
Return Json(Reqs, JsonRequestBehavior.AllowGet)
End Function
where "_db.dRequestGetAll" returns a collection of dRequest rows like so:
Public Function dRequestGetAll() As IEnumerable(Of DRequest)
Return From r In _PITcontext.Requests Where r.CompletedDate Is Nothing Select r
End Function
so. what did i miss?
EDIT: i replaced the javascript from the original post with the most current version since comments can't handle more than 600 characters.
Try like this:
$(document).ready(function () {
$.ajax({
url: url to your controller action,
type: "GET",
dataType: "json",
success: function (response) {
// Do something with your response
}
});
}
Also, in your code above you are calling your variable $response but then in your each loop you are trying to access response (no $ prefix).
I think you should be using $.map() instead of $.each(). It returns an array of your elements. Differences are discussed here.
I am having problems with a JSON AJAX callback when the returned JSON object contains no data. My code is as follows:
$.ajax({
type: "POST",
url: "includes/get_menu_name.php",
headers: {"cache-control": "no-cache"},
data: data,
success: function(html) {
//alert(html);
var app_data = "";
if (html.MenuData != 0) {
$.each( $.parseJSON(html).MenuData, function() {
app_data += "<li data-short='"+this['dish_short']+"' data-desc='"+this['dish_desc']+"' data-dish_id='"+this['dish_id']+"'>"+this['dish_name']+"</li>";
});
$('.listbox').show();
$('.nameslist').html(app_data);
$('li').hover(function() {
$(this).addClass('hover2');
},function(){
$(this).removeClass('hover2');
});
if (html == "") {
$('.listbox').hide();
}
$('li').click(function() {
//alert($('li', this).data('short'));
$('.price').val("");
var main_name = $(this, 'li').text();
$('.main_name').val(main_name);
//$('.price').val($(this).find('.ajaxid').text());
if(main_name.length > 40) {
$('.short_name').val($(this).data('short'))
} else {
$('.short_name').val(main_name);
}
if($(this).data('desc')!="") {
$('.dish_desc').val($(this).data('desc'));
}
var dish_id=$(this).data('dish_id');
$('.main_name').data('dish_id', dish_id);
$('.listbox').hide();
});
}
}
});//end ajax
The error comes back as:
TypeError:$.parseJSON(...) is null
I have tried various methods to check if there is data within the callback but none seem to work. I am very new to using JSON and is wondering whether I should add a different call back via the php page if there is no data to return, however would like to find out if there is a way to do this via the javascript.
$.ajax with post will return HTML in string format you need something like this!
success:function(html)
{
if(html)
{
try
{
html = JSON.parse(html);
if(html.MenuData)
{
// do something interesting
}
else
{
// failed
}
}
catch(e)
{
// failed
}
}
else
{
// failed because response is empty
}
}
Here you can specify dataType to use as json
$.ajax({
type: 'POST',
url: ajaxURL,
data:data,
dataType: 'json',
success: function(data){
JSON.parse(data);
}
});
And in server side script you must have to encode data using json_encode function.
While fetching json via ajax, here are a few things to note (incase it catches your issue too)
1) Content-Type
Json parsing will work fluently when Content-type: application/json
A html fetch (meaning Content-Type: text/html or equivalent) needs manually parsing json as String.
2) Jquery version
This shouldn't be a problem since it has subsided since version: 1.5 (you might be using latest one, 1.9)
Here is a link to the json related bug: http://bugs.jquery.com/ticket/8108
For json intensive coding, people often use jquery-json (http://code.google.com/p/jquery-json/) which a wrapper over simple jquery. You may want to consider if fix isn't easy.
I hope it answers atleast partially. Thanks..