How to carry "getjson" functionality from one func to another? - javascript

Basically I have a getjson call to call for a bunch load of data. Now I am getting sick of the amount of if data is null else checks.
For Example:
if (data.Height == "") {
$('#DataHeight').html('No Data is Available');
}
else {
$('#DataHeight').html(data.Height);
}
Reason being is the user has to be alerted asap that data is not available.
So I went off and am trying to write a DataCheck.js to include and handle all this outside of my pretty little page :D.
Function:
function DataNullCheck(ObjectName) {
if (data.ObjectName == "") {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}
and to call it inside my function
function getdata() {
$.ajaxSetup({
cache: false
});
$.getJSON(urldefault, function (data) {
DataNullCheck('Height');
.......
And Data is undefined. Because it is not within the JSON call?
Any help or hints towards the right direction would be appreciated especially an explanation of why it works one way or another. Thanks in advance.
How would I carry through the getJson call functionality to my little function?

Pass data as a parameter to your function:
function DataNullCheck(data, ObjectName) { // you can check for null any property of data
// e.g. DataNullcheck(data, "Width"), or
// DataNullCheck(data, "Height") etc.
if (!data[ObjectName]) {
$('"#Data' + ObjectName + '"').html('No Datablurgh');
}
else {
$('"#Data' + ObjectName + '"').html(data.ObjectName);
}
}

Related

Can I automate the calculate process and direct update to the table using Laravel Framework?

I'm new in programming, and I'm currently working on a rubric assessment module with Laravel Framework.
This is my code to handle the calculation of the marks in the Controller. However, I would like to update the calculation in real time without refreshing the page. Due to I'm lacking of knowledge in Javascript and JQuery, I would like to ask is there any way or sample code to perform the process in real time?
foreach ($rubricArtifactDetails as $rubricArtifactDetail) {
foreach ($rubricCriteriaDetails as $rubricCriteriaDetail) {
if ($rubricArtifactDetail['rubricArtifactId'] == $rubricCriteriaDetail['rubricArtifactId']) {
$finalMark = 0;
if ($rubricCriteriaDetail['markSupervisor'] !== null && $rubricCriteriaDetail['markModerator'] !== null) {
$finalMark = ($rubricCriteriaDetail['markSupervisor'] + $rubricCriteriaDetail['markModerator']) / 2;
} elseif ($rubricCriteriaDetail['markSupervisor'] === 0 || $rubricCriteriaDetail['markModerator'] === 0) {
$finalMark = ($rubricCriteriaDetail['markSupervisor'] + $rubricCriteriaDetail['markModerator']) / 2;
} elseif ($rubricCriteriaDetail['markSupervisor'] === null && $rubricCriteriaDetail['markModerator'] === null) {
$finalMark = 0;
} elseif ($rubricCriteriaDetail['markSupervisor'] === null) {
$finalMark = $rubricCriteriaDetail['markModerator'] / 2;
} elseif ($rubricCriteriaDetail['markModerator'] === null) {
$finalMark = $rubricCriteriaDetail['markSupervisor'] / 2;
}
$finalMarkArray[$t] = $finalMark;
$t++;
}
}
}
This is my sample output for the rubrics, however it only update the marks by clicking the submit button.
https://imgur.com/a/36Ui93K
The only way to achieve this in realtime, you need to use AJAX.
jQuery's $.ajax is one of the simplest method to perform this task.
Create an independent web route for calculation and link it to the respective controller's method.
Create a $.ajax function in your view or script file. (Though *.blade.php is better place to execute this function as you'll be able to access the variables much easily.)
// Javascript part
$.ajax({
url: `{{ route() }}`,
method: 'GET/POST/PUT/DELETE',
data: {
// If you want to send some params to the controller.
// You will receive the contents in `$request` object.
},
done: result => {
// This callback is only called when your request succeeds.
// This is the place where you need to update your HTML via DOM manipulation.
},
fail: result => {
// This callback is only called when your request fails.
},
always: () => {
// This callback is always called after a specific request is completed.
}
});
<?php
class TestController extends Controller {
public function calculate(Request $request) {
// DO YOUR CALCULATION
// Instead of returning view, return a JSON from here.
return response()->json(['status' => true, 'result' => 'YOUR_RESULT']);
}
}
?>
jQuery API Documentation: https://api.jquery.com/jquery.ajax/
Laravel JSON Response Documentation: https://laravel.com/docs/7.x/responses#json-responses

Dynamics CRM 2016 Javascript forEach not supported

So I am trying to write javascript code for a ribbon button in Dynamics CRM 2016 that will grab a phone number from a list of Leads that can be seen in the Active Leads window.
However, when I try to run it, I get an error telling me
As I step into my code (I'm debugging), I see this error
Here is the code I am working with.
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
// this should iterate through the list
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
//this should get the id and name of the selected lead
getPhoneNumber(selected, SelectedEntityTypeName);
});
}
//I should have the lead ID and Name here, but it is returning null
function getPhoneNumber(id, entityName) {
var query = "telephone1";
Sdk.WebApi.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
// I'm trying to capture the number and display it via alert.
alert(telephone1);
},
function (error) {
alert(error);
})
}
Any help is appreciated.
What you have is an javascript error. In js you can only use forEach on an array. SelectedControlSelectedItemIds is an object not an array.
To loop though an object, you can do the following.
for (var key in SelectedControlSelectedItemIds){
if(SelectedControlSelectedItemIds.hasOwnProperty(key)){
getPhoneNumber(SelectedControlSelectedItemIds[key], SelectedEntityTypeName)
}
}
Okay, so I figured it out. I had help, so I refuse to take full credit.
First, I had to download the SDK.WEBAPI.
I then had to add the webAPI to my Javascript Actions in the Ribbon Tool Bench.
Then, I had to create a function to remove the brackets around the
SelectedControlSelectedItemIds
Firstly, I had to use the API WITH the forEach method in order for it to work.
These are the revisions to my code.
function removeBraces(str) {
str = str.replace(/[{}]/g, "");
return str;
}
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
//alert(SelectedEntityTypeName);
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
getPhoneNumber(removeBraces(selected), SelectedEntityTypeName);
// alert(selected);
});
}
function getPhoneNumber(id, entityName) {
var query = "telephone1";
SDK.WEBAPI.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
formatted = telephone1.replace(/[- )(]/g,'');
dialready = "1" + formatted;
withcolon = dialready.replace(/(.{1})/g,"$1:")
number = telephone1;
if (Xrm.Page.context.getUserName() == "Jerry Ryback") {
url = "http://111.222.333.444/cgi-bin/api-send_key";
} else if(Xrm.Page.context.getUserName() == "Frank Jane") {
url = "http://222.333.444.555/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bob Gilfred"){
url = "http://333.444.555.666/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Cheryl Bradley"){
url = "http://444.555.666.777/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bill Dunny"){
url = "http://555.666.777.888/cgi-bin/api-send_key";
}
if (url != "") {
var params = "passcode=admin&keys=" + withcolon + "SEND";
var http = new XMLHttpRequest();
http.open("GET", url + "?" + params, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
}
},
function (error) {
// alert(error);
})
}
To elaborate, once I successfully get the number, I remove the parenthesis, dashes and white-space. Then, I add a "1" to the beginning. Finally, I insert colons in between each number. Then, I create an HTTP command and send it to the office phone of whoever is using CRM at the time. The user eval and HTTP message is my code. I'm showing you all of this because it was a great learning experience, and this feature really adds to the functionality.
I hope some of you find this useful.
Thanks for the help.

how to return results to the calling function (development of a firefox extension)

In my firefox extension I have a sqlite-database with some tables. Using executeAsync(), I updated the tables, inserted some new data and selected some values. The select-case cause me some problems.
Within the handleCompletion()-function I can pass the retrieved data from the table to another function (and can alerting the results, for example). But I would like to pass the result back to the calling function. I searched the net for an answer to my problem, but I can't find a solution.
What I found:
retrieveData: function() {
var rows = new Array();
if (this.dbConn.connectionReady){
statement = this.dbConn.createAsyncStatement("SELECT * " +
"FROM 'domains' " +
";");
statement.executeAsync ({
handleResult: function(aResultSet) {
var i = 0;
for (let row = aResultSet.getNextRow(); row; row = aResultSet.getNextRow()) {
rows[i] = row;
++i;
}
},
handleError: function(anError) {
alert("error");
},
handleCompletion: function(aReason) {
if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
// something went wrong
alert("error2");
}
}
});
}
return rows;
}
This code does not return the expected results. The statement is executed after the method returned the Array "rows". So, my calling function can never receive the data from the table...
How can I solve this problem? Is there something like a timeout for returning the datarows of the table?
Thanks a lot for help!
You should ideally be dealing in callbacks in the above example. Thats how the SQLite API developers intended the API to be used. :)
retrieveData: function(_callback) {
...
statement.executeAsync ({
...
handleCompletion: function(aReason) {
...
_callback(rows);
}
});
}
And where you call the function:
retrieveData(function(rows) {
// do stuff with rows here
});

Help modify a javascript - need to open link instead of displaying result

I'm trying to modify the code from this script. Basically I'm trying to get the script to send the browser to another page rather than display the results in a div.
This is the code in question:
<script type="text/javascript">
function openOneSlot() {
SpinningWheel.addSlot({1: 'First', 2: 'Second'});
SpinningWheel.setCancelAction(cancel);
SpinningWheel.setDoneAction(done);
SpinningWheel.open();
}
function done() {
var results = SpinningWheel.getSelectedValues();
document.getElementById('result').innerHTML = 'values: ' + results.values.join(' ') + '<br />keys: ' + results.keys.join(', ');
}
function cancel() {
document.getElementById('result').innerHTML = 'cancelled!';
}
window.addEventListener('load', function(){ setTimeout(function(){ window.scrollTo(0,0); }, 100); }, true);
</script>
I've changed the 'done' function to as follows:
function done() {
var results = SpinningWheel.getSelectedValues();
if (SpinningWheel.getSelectedValues() == "1,First")
{
window.location="first.html";
}
else if (SpinningWheel.getSelectedValues() == "2,Second")
{
window.location="second.html";
}
else
{
alert("Damn, Still not working..");
}
But now I'm lost as I'm very new to javascript.. Can anyone help the noob to get this working?
:)
Try this:
function done() {
var results = SpinningWheel.getSelectedValues();
if (results.values[0] == "First")
{
window.location.href="first.html";
}
else if (results.values[0] == "Second")
{
window.location.href="second.html";
}
else
{
alert("Damn, Still not working..");
}
The returned values appear to be an array of all the slots. Since yours has only one slot, I'm only looking at the first array position of the "results.values" array.
Try location.href instead of window.location
Note that this particular thing (changing page) is done differently across different browsers so you should google "javascript redirect " if you run into trouble on a particular browser
Look at what is returned by SpinningWheel.getSelectedValues(). It is an object with two properties keys and values. Therefore, it will not equal "1,First". Check into what is in those properties, and base your conditionals on those.
To pass your variables through, use the following syntax:
window.location = "first.html?var1Name=" + var1 + "&var2Name=" + var2;
To get the value of those variables on your first.html and second.html pages, you can use the window's query string to get hold of their values:
http://www.eggheadcafe.com/articles/20020107.asp
You would want to look at the window.location.search property.

jQuery Dynamic Function and Variable

I am trying to create a function that handles the 'keyup' event for several input fields and passes the input value to a php script. Here's the code I have so far
$(document).ready(function () {
$("#email").keyup(function () {
val = $("input#email").val();
what = 'email';
aFunction(val, what);
});
});
function aFunction(val, what) {
var dataString = what + '=' + val;
var error = "email_check";
$.post("key.php", dataString, function (data) {
//if (data.[error] == 'invalid'){
if (data.email_check == 'invalid') {
$("#ppp").html('error');
} else {
$("#ppp").html('good to go');
}
}, "json");
//return false;
}
When I uncomment
//if (data.[error] == 'invalid'){
and comment out
if (data.email_check == 'invalid'){
My the script doesnt execute and js file doesn't load into the firebug script console - I assume means there's an error because when I undo that and refresh I can view it. I've tried added single and double quotes to the variable. Also, it would be helpful if there was a way to see what the is error is, but I don't know how to do that.
Your primary problem here is that you should use either dot notation ("data.error") or array notation ("data['error']") but not both ("data.['error']").
Javascript does not support braces in identifiers.
If the key is actually just error, you can write if (data.error == 'invalid').
If it is [error], you'll need to write if (data['[error]'] == 'invalid)`.
To see syntax errors, go to Firebug's Console tab.

Categories

Resources