$("#login").click(function(){
$.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){
console.log(data); //get whatever i have in login box and sends to my handler returning the json array
});
template = $("#hidebody");
if(!data['error']){
template.show();
//$("#greeting")
}
else
{
template.hide();
}
return false;
});
So far the top part works, which means whatever name i type in username box it is send to my handler login.php, when i do a console.log, and so on console i get my json array back from my database which works, now I need some help writing a if and else statment where the comment box appears after the person logs in, which hides the userbox, and password box, and as a greet statment displaying the person name from the database.
Since Javascript is an asynchronous language, there's no guarantee that the data from $.getJSON will be available unless passed through a callback or returned in a promise. In my below example, I pulled the function definitions out into their own variables instead of defining them inline, to help illustrate the flow of the program.
// Define a login method which grabs data and passes it to a callback
var login = function (username, callback) {
$.getJSON("handlers/Login.php?name=" + username, callback);
};
// Define a method which handles the response returned from the login URL
var handleResponse = function (data) {
console.log(data);
var template = $('#hidebody');
if(!data['error']) {
template.show();
} else {
template.hide();
}
};
// Register the onClick event which calls the login method
$("#login").click(login($('#username').val(), handleResponse));
Since getJSON is going to run asynchronously you need to add your data handling functionality into that callback where you are currently logging the data.
Something like this:
$("#login").click(function(){
$.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){
console.log(data); //get whatever i have in login box and sends to my handler returning the json array
template = $("#hidebody");
// Any other logic for parsing / handling of returned JSON
if(!data['error']){
template.show();
//$("#greeting")
}
else
{
template.hide();
}
});
return false;
});
Related
I am trying to use simple getJson call to get Json object from server.
On server side everything looks good. Json is created and returned:
But on the front-end my object is not mapped to returned Json from server. It is undefined in first call and that value and then it goes one more time through getJson and returns real object.
This is my code:
btnSaveNewMeeting.onclick = function () {
var vm = {
'Title': $('#eventTitle').val(),
'StartAt': $('#startdatepicker').val() + ' ' + $('#starttimepicker').val(),
'EndAt': $('#enddatepicker').val() + ' ' + $('#endtimepicker').val()
}
var meetings = GetAllScheduledMeetings();
if (CheckIfMeetingsAreOverlapping(vm.StartAt, vm.EndAt, meetings)) {
addNewMeetingModal.style.display = "none";
$.ajax({
type: 'POST',
url: "/Meeting/Create",
data: vm,
success: function () {
$('#calendar').fullCalendar('refetchEvents');
}
});
ClearPopupFormValues();
}
}
So I want to get value from GetAllScheduledMeetings(); and put it in meetings object.
var meetings = GetAllScheduledMeetings();
function GetAllScheduledMeetings() {
$.getJSON("/Meeting/GetAllScheduledMeetings", function (result) {
return result;
});
}
So GetAllScheduledMeetings() should only make a call to server and return result. But that doesn't happened.
When I debug in console of a browser what is happening is this:
1. on button click GetAllScheduledMeetings() gets invoked.
2. getJson makes a call to server and json object is created there and returned.
3. it goes back to front-end but skips whole return result; part and returns undefine value to var meeting = GetAllScheduledMeetings();
4. I get few exceptions because meeting is undefine
5. GetAllScheduledMeetings() gets called again for some reason, after all of this has happened and in this call result gets real values from server.
Does someone knows why is this happening? Why two calls are made and why in the first call I do not get data from server?
GetAllScheduledMeetings never returns anything (so, returns undefined) and "is async", so, at the moment of execution, when using meetings, there is a very high probabilty for the variable to be undefined.
You'll need to recode GetAllScheduledMeetings to pass you all "if block" as a callback or use any other way to work with async code (Promises for instance).
function GetAllScheduledMeetings() {
$.getJSON("/Meeting/GetAllScheduledMeetings", function (result) { // This anonymous function is called asynchronously and returns result *in the blue*
return result;
});
// GetAllScheduledMeetings doesn't specify a return value so it's retVal is undefined
}
SOLUTION:
Since $.getJSON or $.ajax calls are asynchronous by default all you need to do is make them synchronous by adding: async: false to call definition.
I am trying to call a web-service with in javascript and get the data from web-service.
I want to trigger the ajax call again when the data returned by web services changes.
Here is code i tried with, but failed to trigger callback again when data from server changes.
var request=$.get("http://localhost:8080/messanger/webresources/myresource",function(data){
if(data=="something"){
//do something
}
else if(data=="something else"){
//do something else
}
});
When the data from web-services changes, i want to execute the get request again!!!
Please suggest the concept to do this...
I would suggest recursive call of function that calls the service. It is beeing called just as long as the result differs from the previous one. But im still not sure if it is what zou want:)
var previousResult = null;
function callMyService() {
var request = $.get("http://localhost:8080/messanger/webresources/myresource", function (data) {
if (data == previousResult) {
// returned data is the same as last call
}
else {
// save the previous result to global variable
previousResult = data;
// recursive call
callMyService();
}
});
}
Then call is wherever you need to:
callMyService()
I have a function that queries a database for info, when a button is clicked. This info gets written to innerHTML of a label. When this function returns, I read the innerHTML of this label. Problem is, it always returns the old value, not the new value that was pulled from the database. The label on the scree is displaying the correct value, though. When I click the button again, the value that I was expecting on the previous click, is now given. Seems like a timing issue but can't seem to figure it out.
example:
SQL Data - cost = 10
I expect to see 10 alerted to me when I click the button. I get a blank alerted to me, even though 10 is now in the label. When I click the button again, 10 is alerted, but 20 is now in the label.
function getInfo() {
var ctlMonthly = document.getElementById("cellMonthlyCost")
getSQLData(ctlMonthly);
alert(ctlMonthly.innerHTML);
}
function getSQLData(ctlCell){
...
var my_ctlCell = document.getElementById(ctlCell);
$.each(objData.items, function() {
my_ctlCell.innerHTML = this.Param1
});
...
}
Thanks.
you need to add the alert after the data is received from the database. I am assuming that you're sending an ajax request to fetch data. You will be able to get the new value in the callback of you're ajax request function.
Currently what is happening in your code is that
1. getSQLData(ctlMonthly);
// This sends a request to the data base to fetch data
2. alert(ctlMonthly.innerHTML);
// This shows the current value in an alert
3. data is received and shown in the label
This process happens so fast that you don't notice the difference between step 2 and 3.
Is this what you want?
I used a callback function
function getInfo() {
var ctlMonthly = document.getElementById("cellMonthlyCost")
getSQLData(ctlMonthly,alertInfo);
}
function alertInfo(info){
alert(info);
}
function getSQLDate(ctlCell,callbackFn){
...
var my_ctlCell = document.getElementById(ctlCell);
$.each(objData.items, function() {
my_ctlCell.innerHTML = this.Param1;
callbackFn(this.Param1);
});
...
}
to piggyback on Himanshu's answer, your request to your server is async. Meaning javascript will execute the GET request and continue on with the script, when the requests comes back from the server it will run whatever callback you give it. ( i.e. update label tag )
assuming getSQLData is a ajax call or something promised based, something like:
function getSQLData(ctlCell){
return $.get('/sql/data').done(function () {
var my_ctlCell = document.getElementById(ctlCell);
$.each(objData.items, function() {
my_ctlCell.innerHTML = this.Param1
});
});
}
you can change your code to:
function getInfo() {
var ctlMonthly = document.getElementById("cellMonthlyCost")
getSQLData(ctlMonthly)
.done(function () {
alert(ctlMonthly.innerHTML);
});
}
Basically the difference is your telling javascript to alert the innerHTML after the requests comes back from the server.
The more correct answer would be to alert the data straight from the response instead of reading from the DOM.
I'm trying to use the same method name for both a function and a method (a function of an object) and calling the function from inside the method. However, the function does not get called at all. These are the relevant bits of the function:
function post(url, data, success, error) {
console.log("Sending"); // This doesn't get even called
var request = new XMLHttpRequest(); // Nor a request is made
// ... (more code here)
}
And the relevant bits of the method
function u(parameter) {
// ... more code here
this.post = function(success, error) { // post request
this.on("submit", function(e) { // Loop through all the nodes
e.preventDefault(); // Stop the browser from sending a request
console.log("Going to send your data"); // This works
post(u(this).attr("action"), u(this).serialize(), success, error); // Post the actual data
console.log("Got here"); // Well it's async, but it also gets here
});
return this;
}
return this;
}
It is supposed to be called from this script when the form is sent:
u("form").post(function(){
alert("Yay, it worked");
}, function(){
alert("Something went wrong");
});
It successfully calls the method and both of the messages are shown. However, the Sending from the function is NOT logged and no request is performed. I'm thinking either a problem with scope or with the function name being overwritten, but I'm not an expert here so any help would be appreciated. Why is the function post() not being called?. There's absolutely no error shown in the console.
After some testing, I can confirm the problem is that they share the name. So, how could I have the same name shared for a method and a function? The method would only be called like u("form").post(callA, callB); and the function like post(url, data, callA, callB)l;
It's your call of the u function that is problematic. You forgot the new keyword, which made the this context be the global scope object - on which you then are overwriting the global post variable.
Two fixes:
Use (new u("form")).post(…); or make your constructor new-agnostic
Don't put the post function in the global scope. Use the module pattern.
I have a JavaScript class that handles queries to a local DB (on a WebOs device). Now what I want to do is, create a model with all my basic queries to simplify my code.
So first I create a function:
getLists: function(){
this.query( 'SELECT * FROM lists ORDER BY rowID DESC', {
onSuccess: enyo.bind(this,function(data) { this.getData(data); } ),
onError: function() { return false; } } );
}
And than I have my callback function which receives the data:
getData: function(data){
return data;
}
Now what I would like to do, is call it like this from my app:
var data = getLists();
The problem is, this is not returning the data from my callback function (getData). My question is how can I have "getLists" return the data from the callback?
Thank you
You're thinking imperial: C follows B follows A. Forget about that.
AJAX and modern JavaScript works differently. You never say "get data now", you say "call X when data is available".
So the solution is to write some code which does something useful with the data. Let's call this function a. Instead of:
var data = conn.getData();
a( data );
b( data );
c( data );
you do
conn.getData( a ); // a has to call b which calls c.
Eventually, the data will be there and a will be called with data as an argument.
See? You don't chain calls to a() and b() as in traditional programming. Instead, you create functions that do what you want and pass those functions around.
You don't get to. The first A in AJAX is Asynchronous. The requests happen "out of time" with the other processing. Your call to getLists returns after it launches the AJAX request, and the callback function is called when the remote server responds to the AJAX request.
-- Edited for comments --
If you want to "watch" a variable you can use something like this:
// Set up a container for the data to return to.
var retData;
// Modify the getData function to assign to the global variable
getData: function (data) {
retData = data;
}
// Start the "wait" process.
var myInterval = setInterval(function () {
if (retData == undefined) {
return;
}
// when the return data shows up stop waiting.
clearInterval(myInterval);
// some other data processing here in this function
// or trigger the actual processing function.
// don't have to pass retData to it, it's global, the
// data handler function can retrieve it itself.
myDataHandler();
}, 1000);
// make the ajax call here.
getLists();