Calling jQuery Function with Javascript Function - javascript

Having some trouble getting this to work, specifically with $.getJSON(). I want to wrap the getJSON function from jQuery in a Javascript function like so:
function reload_data() {
$.getJSON("data/source", function(data) {
$.d = data;
});
}
But when I call reload_data() it doesn't execute the jQuery function inside. Any ideas?

You're not telling us enough. I will just take a guess!
If you are calling this function, and then immediately checking $.d for the results, that is not going to work because you don't allow time for the asynchronous AJAX request to complete...
reload_data();
alert($.d); // What?! It's not displaying the updated results?!
You'll have to utilize a callback structure, like jQuery uses, in order to make it work...
reload_data(function() {
alert($.d);
});
function reload_data(func) {
$.getJSON("data/source", function(data) {
$.d = data;
//Execute the callback, now that this functions job is done
if(func)
func();
});
}

Put an Alert in side the function to know its getting called.
and a try catch around the jQuery call to see if there is an error
function reload_data() {
alert('reload_data start');
try{
$.getJSON("data/source", function(data) {
$.d = data;
});
}
catch (ex){
alert ('error in jQuery call:' + ex)
}
}

Thanks for the help everyone, but the solution was actually really simple. It was just a matter of synchronization. The page was reloading before the JSON data got reloaded, so that's why I wasn't seeing an error.

Related

jQuery wait for a function to complete before new fires

I have two functions in jQuery that I want to fire in a specific order. The first function is an ajax function which updates a partial view. The other one is supposed to do some styling on the partial view, once the ajax function has completed - this function takes a parameter.
ajaxFunction();
stylingFunction(params);
I have tried the following:
ajaxFunction(function() {
stylingFunction(params)
});
Also, I have tried to use a callback:
ajaxFunction(stylingfunction(params));
ajaxFunction(callback)
{
//Do update
callback()
}
None of these do however work. The styling appears shortly where after it dissapears because the partial view is getting updated. Where am I going wrong here?
Both functions are written in my "parent" view.
You can use .done() and .fail() chained to the $.ajax call ...
I created a couple callback functions with psuedo-code inside the successCallback() since you said you only need to run the styling function "sometimes". You will want to test whatever condition inside that function to determine if you want to run the styling function. Hope this helps.
(function($) {
$(function() { //document.ready
$.ajax({ cache: false,
url: "/blah/vlah/lah",
data: { somedata: somedata }
})
.done(successCallback)
.fail(failCallback);
});
function successCallback(data) {
if (someCondition) {
stylingFunction(params);
}
};
function failCallback(jqXHR, status, error) {
console.log(jqXHR);
console.log(error);
console.log(status);
};
})(jQuery);
I created another gist which handles ajax event delegation, you may want to review and incorporate anything that seems helpful to your situation.
https://gist.github.com/inceptzero/a753d020648f49da90f8
I also created this gist on github for an ajax request queue which is a bit more elegant and robust.
https://gist.github.com/inceptzero/e64756f9162ca6aeeee5
Since you are using jQuery you could const ajaxFunc = callback => $.ajax({...}).done( data => callback) Also you could use async/await. You can read more about it on MDN.

Writing jQuery inside a Javascript function not working

I have a js file called example.js which has a line as follows:
gridOptions.api.setRowData(createRowData());
Then there's another file data.js which has the createRowData() function that should return ROW_DATA. It is as follows:
function createRowData() {
jQuery.getJSON('/file.txt',function(ROW_DATA){
return ROW_DATA;
});
}
But, whenever this createRowData() function is called from example.js file, it does not go inside the jQuery block and simply comes to the last curly bracket. Can anyone please tell me what is going wrong here??
I believe that you're not getting the value because getJSON is asynchronous as others have said. createRowData is retrieving the value at a later time rather than when it's called.
Here is one way to get the data with promises. I commented what's going on below:
function createRowData() {
//return a new promise
return new Promise(function(resolve, reject){
jQuery.getJSON('/file.txt',function(ROW_DATA){
//on reject, send an error
if (ROW_DATA === null) reject("Error fetching data");
//on resolve, send the row data
return resolve(ROW_DATA);
});
});
}
//use then to describe what happens after the ajax request is done
gridOptions.api.setRowData(createRowData()).then(function(rowdata){
return rowdata; //log data or error
})
Edit: to do a synchronous ajax request, you may be able to do something like this, referring to this SO question.
function createRowData() {
$.ajax({
url: "/file.txt'",
async: false,
success: function(rowdata){
return rowdata
}
})
}
To read some data to a variable like you mentioned, nodejs may help because it can handle reading input/output, and probably to a variable as well.:
You get JSON from the file, pass the result to the callback function, and then return it. Return it where??
As I said, your anonymous function is a callback one.
Program says: When you are done reading from the file, call this function, OK?.
While you do that, I am doing something else.
And that is what it does. The program, would go on, until the file is read, when your callback anonymous function would be called.
You can do sth like this.
createRowData(gridOptions.api);
// add code here if you want this code to execute even before you get the response
function createRowData(api) {
jQuery.getJSON('/file.txt',function(ROW_DATA,api){
api.setRowData(ROW_DATA);
//Whatever else you want to do. In case you want this to be done only
//after the values have been read
});
}
If you want to wait, for the file to be read, just, dont do anything after the function, but put it inside the callback function.

How to make function response synchronous with the other statements in the other function

function test() {
/*some business logic*/
return response;
}
function calculate() {
if (test() == true) {
console.log("Success");
} else {
console.log("Fail");
}
}
my test function is in different js file which does some business processing (processing takes some time) on data and return boolean response.
I am calling test function from calculate function (in different js file).
I am expecting console output as 'success'(test function always return true), but it is giving me 'Fail'. But if I debug this code and wait sometimes on '(if(test()==true))' then i get expected output . Basically it is a synchronization issue. How can i solve that?
I try to modify your code little bit to cater for your need which make use of JQuery Deferred object.
If you comment out "deferred.reject()", you should get the case when your function is considered as failed.
It would make your function waiting for another function to give a response.
var test = function(){
var deferred = $.Deferred();
setTimeout(function(){
deferred.resolve(); //deferred.reject();
},3000);
return deferred.promise();
};
test().done(function(){
console.log("success");})
.fail(function(){
console.log("fail");})
I think from the codes above, you would not have any problems to get "Success" route run. It really depends on how does your business logic run. If they are running in asynchronize manner then you should probably using event driven model to run your calculation logic. For example, you register an event via document.addEventListener('testCompleted', caculate()) and then you fire this event in test().
Hope it helps.

Make js functions execute one after another

Note : No jQuery
I have four functions and I want to call them one after another ie. call a function after the previously called function is executed (in core js, not jquery). I tried searching in the internet but I could not find a satisfied answer. Here is what I've done so far :
function func1() {
noAjaxCall.click();
return true;
}
function func2() {
ajaxCall.click(); <--------- sending an ajax request
return true;
}
function func3() {
noAjaxCall.click();
return true;
}
function func4() {
//anything here
}
if(func1())
if(func2())
if(func3())
func4();
What happens is that, func3 is not called. Why this happens and any work around to this?
Thanks!
I'm sure you're not doing what you expect.
The AjaxCall is not really done when func3 will be called, cause... it's asynchronous.
I prefere you find the real solution (what you really wanna do) than trying to solve this problem.
Could you give the real goal you try to achieve?
edit
Let's imagime the handle on 'click' for ajaxCall. I know u don't have jQuery on the app but I create what I know.
function requester(){
//do some asyn work
$.ajax({ //...
success: function() {
//HERE call the other functions
}
});
}

Callback in jQuery wrapper function

I have written a function that retrieves a html template, then binds data using jQuery.tmpl. I think it's fairly neat and tidy and encapsulates what I need and provides me a reusable function. My question however is can it be improved.
My main concern is what if the $.get method fails, and also how the callBack function is executed.
function Bind(templateURL, templateData, templateTarget, callBack){
var req = $.get(templateURL);
req.success(function(templateHtml) {
$(templateTarget).html(''); //clear
$(templateHtml).tmpl(templateData).appendTo(templateTarget); //add deal
callBack();
});
}
You can pass the result of tmpl() directly to html() to clear your target container and append the new content at the same time. You can also chain the result of $.get() into your success handler to avoid using a local variable:
function Bind(templateURL, templateData, templateTarget, callBack)
{
$.get(templateURL).success(function(templateHtml) {
$(templateTarget).html($(templateHtml).tmpl(templateData));
callBack();
});
}
If $.get() fails, nothing will happen since you do not register an error handler. What that handler would do is up to you, but you might want to display an appropriate message in an alert box or somewhere on the page.
Your second concern is less clear. As it stands, callBack will only be called on success, and without arguments.
You can use $.ajax to assign and error calback. ex:
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
Check the api http://api.jquery.com/jQuery.ajax/

Categories