display a javascript function - javascript

I am creating an API and I want to show a code example in javascript that you can use to invoke the API.
I write a test function in javascript. I would like to be able to execute AND display the code for the javascript function(s) but I would rather only have one copy of the code to make maintenance easier.
Example, I have the following code:
function doauth_test(apikey,username,userpass)
{
$.ajax({
url: "/api/v1.2/user.php/doauth/" + username + "/" + userpass + "?apikey=" + apikey,
type: "GET",
success: function(data,textStatus,xhr) {
var obj = JSON.parse(data);
var authkey = obj.authkey; //store this somewhere for subsequent use
var user_id = obj.user_id; //store this somewhere for subsequent use
},
error: function(xhr, ajaxOptions, thrownError) {
alert("ERROR! Status code: " + xhr.status + " Response Text: " + xhr.responseText);
}
});
}
I want this code to be something I can EXECUTE and I want it to display the code in a DIV in my documentation example. But I do not want to (ideally) have two copies of this code.

You can call toString() on a function to get its source code.
Alternatively, you can use the DOM to get the text of the <script> tag.

Just use toString method for your function and it will return your function definition as a string.
alert(doauth_test.toString());
Hope it helps!

Related

javascript + django - typeError: X is undefined

I'm using p5.js to do some drawing using data from json fed by my Django backend. I have a my draw function defined at the base level of my html doc in the script element like so:
function draw(json) {
if (json["leaf_text"]) {
stroke(100)
ellipse(json["leaf_center_x"], json["leaf_center_y"], json["leaf_height"], json["leaf_width"]).rotate(json["leaf_rotate"]);
}
if (json["twig_text"]) {
stroke(100);
console.log("drawing twig....");
line(json["twig_base_x"], json["twig_base_y"], json["twig_tip_x"], json["twig_tip_y"]);
}
if (json["branch_text"]) {
stroke(150);
line(json["branch_base_x"], json["branch_base_y"], json["branch_tip_x"], json["branch_tip_y"]);
console.log("x1 " + json["branch_base_x"]);
console.log("x2 " + json["branch_base_y"]);
console.log("y1 " + json["branch_tip_x"]);
console.log("y2 " + json["branch_tip_y"]);
}
if (json["trunk_text"]) {
stroke(255);
line(json["trunk_base_x"], json["trunk_base_y"], json["trunk_tip_x"], json["trunk_tip_y"]);
}
}
This function is called upon receipt of a successful ajax response as follows. My problem is, I get a error in the js console because of the draw function.
TypeError: json is undefined
My understanding is that (please correct me where I am wrong) the 'draw' function is agnostic concerning whether or not 'json' exists or not and will wait and see what sort of object it is passed before it begins complaining that the parameter is not defined. Is this not the idea of a function in javascript?? I must be missing something. If this is the case, why would it complain that json is not defined?
if (json["leaf_text"]) {
$("#grow").click(
function(e) {
console.log("attempting ajax...");
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var open_parens = ($("#txt").val()).indexOf("(");
var close_parens = ($("#txt").val()).indexOf(")");
var child = $("#txt").val().slice(0, open_parens);
var parent = $("#txt").val().slice(open_parens + 1, close_parens);
$.ajax({
url: window.location.href,
type: "POST",
data: {
csrfmiddlewaretoken: csrftoken,
child: child,
parent: parent,
mode: "grow"
},
success: function(json) {
setup();
draw(json);
...
}
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
If you use import called json, you should use different name as parameter for draw function (for example: draw(json_bar) or, in import, re-name json (for example: import json as json_foo).

Computed Values in one function; pass them to another function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am working in javascript. I have two functions that both compute a value. Each function also makes an ajax call to a service and grabs some data. Normally, the data is just returned in an object. Both of these functions I want to occur on a button click, so I've wrapped both of my "Compute Functions" in another function. The compute functions set values. Those values that are set, how do I use them in my wrapper function? This may be something simple that I'm just not getting
function ComputeSum() {
$.ajax({
type: 'GET',
dataType: 'json',
url: constructedURL,
success:
function(data) {
callback(data);
stopSpinner();
var TheSum = 4+4;
return TheSum;
},
error: function (xhr, status, error) {
alert("Error - Something went wrong on the retrieval of already existing Hydraulic Data.");
//alert("Unable to communicate with server.Status is: " + status + "The error is: " + error + "The xhr is: " + xhr);
stopSpinner();
}
});
}
function ComputeDIf() {$.ajax({
type: 'GET',
dataType: 'json',
url: constructedURL,
success:
function(data) {
callback(data);
stopSpinner();
var TheDif = 10-2;
return TheDif;
},
error: function (xhr, status, error) {
alert("Error - Something went wrong on the retrieval of already existing Hydraulic Data.");
//alert("Unable to communicate with server.Status is: " + status + "The error is: " + error + "The xhr is: " + xhr);
stopSpinner();
}
});
}
So I have my two extra basic functions. I call these functions in another function thats attached to a button click
function Calculations() {
ComputeSum();
ComputeDif();
alert("The sum is: " + TheSum);
alert("The difference is: " + TheDif);
}
So my ajax call is returning an object but I also want to be able to use those values I created in the Compute Functions inside my wrapper function. Is this possible? What am I missing. Thanks in advance for your help.
Perhaps I'm not understanding the question, but why not use the return values like this:
function Calculations() {
var TheSum, TheDif;
TheSum = ComputeSum();
TheDif = ComputeDif();
alert("The sum is: " + TheSum);
alert("The difference is: " + TheDif);
}
The variables TheSum and TheDif are local variable and limited to the scope of each function. The use of var assures this.
You just assign the return values from the function to a local variable and then you can refer to that local variable within your function:
function Calculations() {
var sum = ComputeSum();
var dif = ComputeDif();
alert("The sum is: " + sum);
alert("The difference is: " + dif);
}

Prototype to jQuery Conversion Confusion

I have the following function:
function updateproductselectionxxx(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
var target = 'productselectionresult' + productassignment;
var myAjax = new Ajax.Updater(target, checkingurl, {
method: 'post',
parameters: pars
});
}
And I am currently in the process of converting all the javascript on this website to jQuery. Usually I can use something similar to:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
$.ajax({
type: 'POST',
url: 'shopajaxproductselection.asp',
data: $(form).serialize(),
success: function (response) {
$(form).find('productselectionresult' + productassignment).html(response);
}
});
return false;
}
And that does the trick, however I really only want to send over 1 field as indicated in the first function and I would also like to send along the information I am sending directly to the function upon it being called. JavaScript is definitely not my area of expertise but usually I can muddle through, but this time everything I have tried has caused errors and I'm not getting very far. Any help would be greatly appreciated.
Looks like a bit of confusion between POST and GET. Although the request method is set to POST in the older Prototype version the params are being sent via CGI which normally appear on the server as a GET. It's a bit hard to say more without seeing the server-side code, but you could try this, such that the jQuery version more closely mimics the old Prototype version:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
$.ajax({
type: 'POST',
url: url,
data: {},
success: function (response) {
$(form).find('#productselectionresult' + productassignment).html(response);
}
});
return false;
}
Note that I have added a hash # to the start of productselectionresult - this is crucial due to the difference in the way PrototypeJS works. In Prototype, you can use an ID selector like:
$('id')
whereas in jQuery it has to be:
$('#id')

jQuery Ajax failing to call to MVC 4 Controller method

I'm attempting to use jQuery in order to fire off an Ajax call after clicking a certain button. I've read several examples of the syntax and issues that may be encountered, but have failed to find a working solution for my cause. Here's the code.
Controller Method: (HomeController.cs)
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
jQuery Code:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});
}
And finally, I'm calling this function with:
$('.companyButton').click(function () {
compCode = $(this).text();
debug("Click event --> " + $(this).text());
changeCompany(compCode);
});
My debug message displays properly, and the Ajax call constantly fails with the following alert: R: [object Object] S: error E: Not Found
I'm not entirely sure what to make of that.
I know there are several questions on this topic, but none of them seem to resolve my issue and I'm honestly not sure what's wrong with these code blocks. Any insight would be appreciated.
EDIT:
In case it's worth noting, this is for a mobile device. Testing on Windows 8 Phone Emulator (Internet Explorer), alongside jQuery Mobile. Not sure if that affects Ajax at all
EDIT 2:
After taking a look at the raw network call, it seems that 'Url.Action("ChangeCompany", "Home")' is not being converted into the proper URL and is instead being called directly as if it were raw URL text. Is this due to an outdated jQuery, or some other factor?
Ok with your EDIT2 it seems you are using url: '#Url.Action("ChangeCompany", "Home")', in a separate JavaScript file. you can only write the razor code inside the .cshtml file and it is not working inside the .js files
You are missing some important parameters in your AJAX call. Change your AJAX call as below:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});}
You can then annotate your controller method with [HttpPost] attribute as below;
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
Note that your action is not returning companyCode directly. You're assigning it to Json result property therefore
In your success function to display result you need to have:
success: function (data)
{
alert("Company: " + data.result);
}
Also this: E: Not Found tells me that you may have some routing issues. If you set a break point inside of your ChangeCompany Action, is it being hit ?

Jsonp request using jquery to fetch bing web results

using this as a guide: http://msdn.microsoft.com/en-us/library/dd250846.aspx
can someone help me with the jquery call?
Do I actually pass in the javascript code for the callback, or just the name of the function?
BingSearch = function($bingUrl, $bingAppID, $keyword, $callBack) {
$bingUrl = $bingUrl + "?JsonType=callback&JsonCallback=" + $callBack + "&Appid=" + $bingAppID + "&query=" + encodeURI($keyword) + "&sources=web";
$.ajax({
dataType: 'jsonp',
jsonp: $callBack,
url: $bingUrl,
success: function(data) {
alert('success');
$callBack(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus);
}
});
};
Update
Ok so I changed this to:
BingSearch = function(bingUrl, bingAppID, keyword, callback) {
var url = bingUrl + "?method=?&JsonType=callback&Appid=" + bingAppID + "&query=" + encodeURI(keyword) + "&sources=web";
$.getJSON(url, callback);
};
Calling it like:
BingSearch(url, appid, searchkeyword, function(searchresults) {
alert('yes!');
};
Still getting the 'invalid label' error.
To use do jsonp with jQuery, replace the JsonCallback=UserCallback with JsonCallback=?. jQuery will then handle it like a regular $.ajax() request.
I suggest starting out with $.getJSON() to get used to the Bing API and moving back to $.ajax() when your ready to integrate it with your application.
Using the example from the Bing API docs:
var apikey = 'YOUR_API_KEY';
var url = 'http://api.bing.net/json.aspx?AppId='+apikey+'&Version=2.2&Market=en-US&Query=testign&Sources=web+spell&Web.Count=1&JsonType=callback&JsonCallback=?';
$.getJSON(url, function(data) { console.log(data); });
jsonp: needs to be set to a string (I think it can also be left out), as this is just the name of the dynamically created function used to receive the JSONP.
But the formal parameter $callBack needs to be a reference to a function, so either you use
function callback(result){ /*processResultHere*/ }
BingSearch(..,..,.., callback);
or
BingSearch..,..,.., function(result){ /*processResultHere*/ });
And just so you know it, the excessive use of $ really hurts my eyes :)
Also, function names beginning with a capital should be reserved for 'classes', as many syntax checkers will complain on functions with capitals being called without new in front..

Categories