How do I call this javascript function? - javascript

As documented here: http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/
I am trying to use this function:
(
function getTemplateAjax(path, callback) {
var source;
var template;
$.ajax({
url: path,
success: function(data) {
source = data;
template = Handlebars.compile(source);
//execute the callback if passed
if (callback) callback(template);
}
});
}
//run our template loader with callback
(getTemplateAjax('js/templates/handlebarsdemo.handlebars', function(source) {
//do something with compiled template
$('body').html(template);
})()
)()
I am new to JS, so how can I use this?
I am trying to:
pass the path of the handlebars file
pass a json object which will be inserted in the template and an html should be returned back by the functions.
Update:
Got the answer, there was a typo in the code: this works.
While calling the function, the argument was source but was being used as template.
function getTemplateAjax(path, callback) {
var source;
var template;
$.ajax({
url: path,
success: function(data) {
source = data;
template = Handlebars.compile(source);
if (callback) callback(template);
}
});
}
getTemplateAjax('js/templates/handlebarsdemo.handlebars', function(template) {
data = {title: "hello!" , body: "world!"}
$('body').html(template(data));
})

The code is correct and you seem to be calling it correctly.
You should make sure that you have jQuery properly setup (just check the value of the jQuery global variable - it should not be "undefined").
Also, you should check if the handlebars really is where you think it is - maybe you should be using an absolute URL instead of a relative one.

First try to check whether your are goint in that function or not. If you are then check you are getting response from ajax call or not... and use try...exception - so that if something wrong in ajax setting you know it straightaway.
You can show results only if you do get the results back from your ajax call.

Related

Why is Javascript contained in a string variable executing as soon as it is assigned to another string variable?

This one will require some setup for you to understand what I am trying to do. It involves both templating and asynchronous calls. I am aware of the intricacies and nuances of async calls.
I have a piece of javascript, in a .js file. The script contains some "tags" that need to be replaced with actual variables, which are different on each use. You will notice the "{{tags}}" embedded in the script. You will also notice that the script contains an ajax call to a C# Generic Handler. :
// this is template code from LoadFlights.js, called from LoadFlights() in main.js...
$.ajax({
type: "POST",
url: "js/handlers/LoadFlights.ashx",
dataType: "text",
cache: false,
data: {
DateStart: "{{DATESTART}}",
DateEnd: "{{DATEEND}}",
Specific: JSON.stringify({DAY: "{{DAY}}", DEP: "{{DEP}}", CARRIER: "{{CARRIER}}", FLT: "{{FLT}}", LEGCD: "{{LEGCD}}"})
},
success: function (result) {
callback_LoadFlights(result);
},
error: function (result) {
alert(result.responseText);
return false;
}
});
function callback_LoadFlights(result) {
alert(result);
}
// end
I get the script with a jquery .get() call, and in the .done() callback, I attempt to assign the retrieved script code to a variable.
function runScript(source, parameters) {
if (URLExists(source)) {
var getScript = $.get({
url: source,
dataType: "script"
})
.done(function (scriptCode) {
var code = scriptCode;
// replace any passed parameters...
for (var p in parameters) {
code = code.replace("{{" + p + "}}", parameters[p]);
}
// remove any unused parameter placeholders...
while (code.indexOf("{{") >= 0) {
code = code.substr(0, code.indexOf("{{")) + code.substr(code.indexOf("}}") + 2);
}
var s = document.createElement('script');
s.type = "text/javascript";
s.text = code;
document.body.appendChild(s);
})
.fail(function () {
alert("Failed to retrieve script: " + source);
})
}
(I omitted the else for brevity sake.)
What happens is that on this line:
var code = scriptCode;
The code immediately executes, and the Generic Handler call fires, and immediately fails with "invalid date format" (the first line that attempts to use DateStart) because DateStart still equals "{{DATESTART}}". None of the code that replaces the tags executes.
Even if I set a breakpoint on that line and attempt to step INTO it to see what might be happening, it still immediately fires the generic handler call.
In the debugger, I typeof'd both code and scriptCode in the Immediate Window, and both return "string".
I'm tempted to believe that a JavaScript error of some sort is occurring, immediately killing the JavaScript code block and stopping it's execution.
But HOW is the Generic Handler being fired then? By all appearances, it seems as though the javascript retrieved by the .get().done() is being executed by simply assigning it to another variable. Is this even possible? Can anyone see what is wrong here?
Take a look at the documentation for jQuery.ajax(): http://api.jquery.com/jquery.ajax/
When the dataType is script:
"script": Evaluates the response as JavaScript and returns it as plain text.
So jQuery is evaluating your javascript before you've had a chance to parse it. Then it gives you the text of the script, but by this point it's too late. Try changing the datatype to 'text' then parse it.

How to store $.getJSON object in global variable and navigate through it later

I'm experimenting with JQuery and trying to create a function to get dynamic data from a JSON returned API and store it in a global variable (I don't know if this is the right/best way to do this).
What I have so far is
function getdata(url){
var data = $.ajax({
type: 'GET',
url: url
});
return data;
};
So far everything works fine, but this returns an object with a "responseJSON" key and I can't seem to find a way to navigate to this key and then do a $.each loop through the arrays in it.
So the questions are:
Is this the right / way ( if not please explain your answer)
How do you navigate through a multidimensional object containing arrays in the "responseJSON" key.
Another approach is to pass a callback to your function so you can set the response handler within the function and less code when you call your getData method
function getdata(url, callback){
var data = $.ajax({
type: 'GET',
url: url
}).done(callback).error(function(){
alert('Oppps...something went wrong')
});
return data;
};
getData('urlstring', function(data){
/* doSomething with data */
})
AJAX is asynchronous. That means it runs in the background while the rest of your script runs. At a point in the future when the AJAX call completes, then you can access it.
In jQuery, $.ajax returns a promise. So what you can do is the following:
getdata('/path/to/your.json').done(function(data){
// Use your JSON data here
console.log(data);
});
What happens is that once the AJAX call is done, your .done() function will run and you will have access to the data returned.
Don't try to access the properties of the $.ajax object (the responseJSON won't be populated until the call is finished). Use callbacks to get at the returned data.
If you want the json data to be in global scope, just define a global variable (that is, outside the function), and then in the function fill it with the returned data. Something like so:
var api_response;
function get_data(url) {
$.post(url, function(j) { api_response = j; }, "json");
// or
$.getJSON(url, function(j) { api_response = j; });
}
You don't even need to create a function for this and can use jquery's own $.getJSON (the or case).

How to extract ajax response data from the success callback

Sorry if this is a duplicate but I couldn't find any satisfying answers in the previous posts.
$(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
// Data received here
}
});
});
[or]
someFunction() {
return $.ajax({
// Call and receive data
});
}
var myVariable;
someFunction().done(function(data) {
myVariable = data;
// Do stuff with myVariable
});
The above code works just fine. However, this ajax request is made on page load and I want to process this data later on. I know I can include the processing logic inside the callback but I don't want to do that. Assigning the response to a global variable is not working either because of the asynchronous nature of the call.
In both the above ways, the 'data' is confined either to the success callback or the done callback and I want to access it outside of these if possible. This was previously possible with jQuery 'async:false' flag but this is deprecated in jQuery 1.8.
Any suggestions are appreciated. Thank you.
You can "outsource" the callback to a normal function, so you can put it somewhere, you like it:
$(function() {
$.ajax({
url: 'ajax/test.html',
success: yourOwnCallback
});
});
somehwere else you can define your callback
function yourOwnCallback(data) {
// Data received and processed here
}
this is even possible with object methods as well
This solution might not be idea but I hope it helps.
Set the variable upon callback.
Wherever you need to process the data, check if variable is set and if not wait somehow.
Try:
$(document).ready(function(){
var myVar = false;
$.ajax({
url: 'ajax/test.html',
success: function(data) {
myVar=data;
}
});
someFunction(){ //this is invoked when you need processing
while(myVar==false){}
... do some other stuff ..
}
});
Or
someFunction(){
if(myVar==false){
setTimeout(someFunction(),100); //try again in 100ms
return;
}
.. do some other stuff ..
}

Javascript - local scope objects not accessible from nested function

I am trying to have a function grab an object from a php file on another page. I'm using the jQuery ajax function to to do the json grab, which is working correctly. The issue is when I try to return that object from the function.
The first time I log the object (from within the success function) it is correct in the console, but the returned object from the function getGantt() logs as "undefined".
How do I get this object out of the function?
My code:
function getGantt(requestNumber){
var ganttObject;
$.ajax({
type: "POST",
url: "get_gantt.php",
data: {request_number: requestNumber},
success: function(returnValue){
ganttObject = $.parseJSON(returnValue);
console.log(ganttObject); //this logs a correct object in the console
}
});
return ganttObject;
}
$(function(){ //document ready function
var requestNumber = $('#request_number').text();
var ganttObject = getGantt(requestNumber);
console.log(ganttObject); //this logs "undefined"
}); //end document ready function
The A in Ajax is an important part of the acronym. Asynchronous JavaScript and XML is asynchronous.
$.ajax({success:someFunction}) means Make an HTTP request and when the response arrives, run someFunction
return ganttObject runs before the response arrives.
You should do anything you want to do with the data inside someFunction and not try to return data to the calling function.
The A in AJAX stands for asynchronous. So the call immediately returns and as soon as it finishes, the success callback is called.
So, simply change your code to use a callback:
function getGantt(requestNumber, callback) {
var ganttObject;
$.ajax({
type: "POST",
dataType: 'json',
url: "get_gantt.php",
data: {request_number: requestNumber},
success: function(returnValue){
callback(returnValue);
}
});
}
$(function() {
var requestNumber = $('#request_number').text();
var ganttObject = getGantt(requestNumber, function(ganttObject) {
console.log(ganttObject);
});
});
Btw, I've also removed this parseJSON stuff - setting dataType to json does the job and is less dirty.
I know why it's not returning it at least. The ganttObject may be in the same scope, but the success function is ultimately running in the readyState callback from the XMLHTTP object, so it's on a different thread than the getGantt function. Can you make the $(function(){... code apart of your success function?

How might I populate an object property using a JSON-encoded server response?

How can i turn this:
<? echo json_encode($myArrays); ?>
...into this:
_rowData: [
{ name: "Most Recent", view: "recentView" },
{ name: "Most Popular", view: "popularView" },
{ name: "Staff Picks", view: "staffView" }
],
My script returns that ^, but i dont know how to put the data into the string, _rowData ?
P.S. I am using Dashcode, trying to dynamically load items into a List Controller
So far, i have this:
var recentListControllerXHR = $.ajax("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php", function(data){
return(JSON.stringify(data));
}, 'text');
rowData: recentListControllerXHR,
Ok - your problem appears to be a misunderstanding of how asynchronous APIs work. $.ajax() makes a request, and at some point in the future calls the provided callback with the response.
Assuming you have a name for the object you're populating, you can fill in the desired property using something like this:
var someObject = {
...
rowData: null,
...
};
// at this point, someObject is incomplete...
$.getJSON("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php",
function(data)
{
// called whenever the server gets around to sending back the data
someObject.rowData = data;
// at this point, someObject is complete.
});
Note that I'm using jQuery's built-in support for JSON here. You can use the json.org library instead if you wish, but getJSON() is rather convenient if you don't have any unusual needs when parsing the data.
Try this:
var rowData;
$.getJSON("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php", function(data) {
rowData = data;
});
But note that rowData is not available until the callback function (see second parameter of getJSON call) has been called.
The question's essentially already been answered using another method, but, if you're interested in using the $.ajax method as opposed to the $.getJSON method, this is how you would do that:
var rowData;
$.ajax({
url: "http://tarnfeldweb.com/applewebapps/ajax/recentApps.php",
type: 'get',
dataType: 'json' // could also be 'jsonp' if the call is going to another site...
success: function(data){
rowData = data;
}
});
Just another option, that's all...
Looks like you don't understand how $.ajax works (looks like nobody do).
$.ajax is an asynchronous function, which means it does not return anything. It only prepares a function to be invoked later, when the data has been received.
Your code should look more like that:
var obj = {
...
_rowData: [],
...
};
$.getJSON("http://tarnfeldweb.com/applewebapps/ajax/recentApps.php", function(data)
{
// Now data contains your row data,
// you can either fill the global object
obj._rowData = data;
doSomethingWith(obj);
// or use data directly
doSomethingWith({
...
_rowData: data
...
});
});
// Note that code below will be executed before the AJAX data is received
Your function will return the data on a successful response.
You have declared the callback function:
function(data){
return(JSON.stringify(data));
}
So, 'data' will contain any data that was returned from the request, if you're declaring your content type as text/json (or application/json - I don't remember off the top of my head) and
rendering your JSON as text in the response you should be good.
What you probably want to do is have your function declare the variable as rowData and go from there, so do something like:
function(rowData){
// do something with the rowdata
}
I doubt you need the stringify method unless you're trying to write the data out as text.

Categories