Display loading image in get method with knockout bindings - javascript

Simple function to get and load data from server:
function getdata(stepNumber){
return $.get("./api/data_count.php", {stepNumber: stepNumber})
.fail(function (textStatus, errorThrown){
console.error("Error ! Unable to get step " + number + " count." + "Error: " + errorThrown + ", Status: " + textStatus);
});
}
Using .done differed method to assign data to knockout observable:
getdata(1).done(function(data){
self.dataCount($.parseJSON(data));
});
through following html:
<td><span data-bind = "text: dataCount"></span></td>
All is working well with the code except that it takes around 15 seconds for query to return this count and I am not sure how to display a loading image or message with in following span while the response is awaited.
<span data-bind = "text: dataCount"></span>

It should be just a matter of toggling an observable to show and hide the loader.
something like:
var Vm = function() {
var self = this;
self.showLoader = ko.observable(false);
self.showResults = ko.pureComputed(function() {
return !self.showLoader();
})
self.getdata = function(stepNumber) {
self.showLoader(true);
return $.get("./api/data_count.php", {
stepNumber: stepNumber
})
.done(function(data) {
self.dataCount($.parseJSON(data));
self.showLoader(false);
})
.fail(function(textStatus, errorThrown) {
console.error("Error ! Unable to get step " + number + " count." + "Error: " + errorThrown + ", Status: " + textStatus);
self.showLoader(false);
});
}
return self;
}
<table>
<tr>
<td><span data-bind="text: dataCount, visible: showResults"><img src='path/to/loader' data-bind="visible: showLoader" /></span>
</td>
</tr>
</table>

Related

Parse cloud code is not logging/alerting on success or failure

I am a newbie in Parse.com cloud code. I am trying to query a table which has a particular column having a request parameter which I am supplying. The query is:
Parse.Cloud.define("newPostNotification", function(request, response) {
Parse.Cloud.useMasterKey();
var userId = request.params.userid;
console.log("User Id "+userId);
var query = new Parse.Query(Parse.ViewCount);
query.equalTo('userId', userId);
query.first({
success: function(object) {
/* var userString = request.params.username;
response.success(userString); */
alert("Success!");
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
I am utterly confused as why I cannot see the the alert messages for success or failure! Please rectify me where I am wrong!
You need to pass a JSON string.
For example: console.log({"Log message":"My message!"});
You can use console.log, console.error, or console.warn. Check the guide.
query.first({
success: function(object) {
console.log("Success!");
response.success();
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
response.error("Error " + error.code + " : " + error.message + " ;
}
});

How to add dynamic a javascript variable in jquery?

I add variable length list in a view with jquery.
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});
for every partialview, set a index value.for example
<input name="Days.index" autocomplete="off" value="96633b1d-9c0c-4760-9ca8-474ac28bd52a" type="hidden">
I want to add a script for every partialview.
var objCal1 = new AMIB.persianCalendar("objCal1", "dateid");
After append PartialView, i want to get last item added.
$("input[id*='Date']").last(function () {
var ??? = new AMIB.persianCalendar(???, $(this).attr('id'));});
How do i get last item addes, and set name for this variable?
Two questions, two answer:
1) To get the id of the last item that you added:
var last_id = $("input").last().attr("id");
Remember that you have to wait for your AJAX call to return before firing that, so add it within your AJAX function.
2) Name the variable whatever you like.
Here's an example of the total code:
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
var last_id = $("input").last().attr("id");
var amib_var = new AMIB.persianCalendar(last_id);
// DO SOMETHING WITH THE AMIB_VAR
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});

JavaScript .load does not show correct page results after .click

The below code allows the user to click as button and reject a friend request. Even though multiple results are shown on a page, it functions correctly as it uses wrapper.children('.decline').click(function() { to target the correct result.
After this happens the following $( "#containerFriends" ).load("friends.html #containerFriends" ); should refresh the page so that the latest results are displayed. However a completely blank page is shown, even when results should still exist. If I manually refresh the page, the correct results are shown.
I'm not sure what is wrong with the below and what is causing such an issue?
mainQuery.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id,
status: results[i].get('status'),
// Saves the object so that it can be used below to change the status//
fetchedObject: results[i]
});
}
var select = document.getElementById("FriendsConnected");
$.each(friends, function(i, v) {
var opt = v.username;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
$('#containerFriends').empty();
$('#containerFriendsConnected').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<img class="responsive-image friendImgOutline" src="' + item.imageURL + '" />' + '<br>');
wrapper.append('<div class="tag">' + item.username + '</div>');
wrapper.append('<div type="button" class="btn btn-danger mrs decline">' + 'Unfriend' + '</div>');
$('#containerFriends').append(wrapper);
//The following lets the user accept or decline a friend request by changing the status the status from Pending to Declined/////
wrapper.children('.decline').click(function() {
$(".decline").click(function() {
item.fetchedObject.set("status", "Rejected");
$( "#containerFriends" ).load("friends.html #containerFriends" );
item.fetchedObject.save(null, {
success: function(results) {
console.log("REJECTED");
},
error: function(contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I actually resolved this by calling the function again, this then ensured the data was upto date and refreshed the page. I believe the issue was that $('#containerFriends').append(wrapper); did'nt contain the updated data after the user .click

How to access result array returned in ajax?

Arg!! I had this working flawlessly and now I am back to banging head against the keyboard.
I want access defined columns inside the array, but I am getting undefined but if I display the results using an alert as detailed in snipped of code below I see the following:
[{"firstname":" Mr","0":" Mr","lastname":" Two","1":" Two","user_public_info_id":"3","2":"3","st_usage_id":null,"3":null},{"firstname":" Mr","0":" Mr","lastname":" Three","1":" Three","user_public_info_id":"5","2":"5","st_usage_id":null,"3":null}]
***
g
***
e
***
undefined
Here is the Ajax code:
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: "handler=getStActivitySharingList&stu_id="+stu_id,
datatype: "json",
success: function(result){
var count = 0;
if (result !== null)
{
//display results
alert(result + " <br />*** <br />" + result[0] +" <br />*** <br />" + result[1] + " <br />*** <br />" + result[0]["firstname"]);
//clears choice list
clearOptions();
//result = $.parseJSON(result); //if this is used cannot display result again
alert (result);
$.each(result, function (i, elem) {
alert("elem"+elem.st_usage_id ); //displays as undefined and won't break
if (elem.st_usage_id === null)
{
count++;
alert(elem.firstname + " "+ elem.lastname + " " + elem.user_public_info_id);
appendOption(elem);
}
});
}
alert(count);
if (count === 0){
noResultsAvailableOption();
}else{
resultsAvailableOption();
}
ShowDialog(false);
e.preventDefault();
},
error: function(){
alert("ajax failure: could not retrieve a list of contacts");
}
});
i not know how you return it from PHP, but in jquery try:
sucess: function (result)
{
console.log(JSON.parse(result)); // parse string to json
}
See json.org
To better answer this question is to implement better debugging procedures.
Here is the code that I used for debugging this issue. The breaking down of the xmlHttpRequest clearly displayed to me that issue was with the data and that I was encountering an illegal character exception when trying to encode the data to json.
A great way to solve any issue is to first implement the correct debugging procedures, and everything else will work itself out.
error: function(xmlHttpRequest, status, error){
alert("ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xmlHttpRequestStr= "";
for(x in xmlHttpRequest)
xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
alert(xmlHttpRequest);
}

converting Parse.com object to string

What I have is when a user enters a name into a textbox and clicks a button, the value in the textbox is saved to the Parse database.
What iI'm trying to do is get the name that was added and add it to a div.
On this Live Example, it's basically what I want, except it alerts [object Object] and not thomas in this case.
You need to use the specific part of the result you need. In your case, replace
query.first({
success: function (results) {
alert("Successfully retrieved " + results + " ");
divTag.innerHTML = results.toString();
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
with
query.first({
success: function (results) {
alert("Successfully retrieved " + results.attributes.FirstName + " ");
divTag.innerHTML = results.attributes.FirstName.toString();
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
Use this:
alert("Successfully retrieved " + results.get("FirstName") + " ");

Categories

Resources