For Loop Array of Javascript Objects

var dog1 = {name:”frank”, breed:”mix”};

var dog2 = {name:”abby”, breed:”mix”};

var dogArray = [];

dogArray.push(dog1);

dogArray.push(dog2);

I have found some JavaScript engines are OK with this:

for(var x = 0; x < dogArray.length; x++){

But many are not, and it needs to be declared as:

for(var x = 0; x < Object.keys(dogArray).length; x++){

Cloudinary, jQuery and HTML to upload image

I have found the Cloudinary documentation poor. Here I have listed the code and steps to upload images to your cloudinary account using jQuery.

COPYING AND PASTING THIS WONT WORK, YOU MUST READ TEXT INSTRUCTIONS UNDERNEATH!

 

 

HTML and jQuery

<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>

//PLACE OPENING SCRIPT TAG HERE

$(document).ready(function () {
// $(“#cloudinary-input”).attr(“data-form-data”, jsonData);
console.log(Math.floor(Date.now() / 1000));
});
function upload() {

var params = {
api_key: ‘1112222’,
public_id: ‘samplepublicid’,
timestamp: ‘1448741653’, //Math.floor(Date.now() / 1000);,
cloud_name: ‘mycloudname’,
signature: ‘9a19e11286b77e7e4f9ba2cb1f8dd4cb40cd67bc’

};

var input = $(“#cloudinary-input”);
input.attr(“data-form-data”, JSON.stringify(params));
input.bind(“fileuploaddone”, function (e, data) {
test(data);
});
input.cloudinary_fileupload();
input.fileupload(‘option’, ‘formData’).file;
input.fileupload(‘add’, {files: document.getElementById(“cloudinary-input”).files});
}

function test(data){
alert(‘success’);
}

//PLACE CLOSING SCRIPT TAG HERE

</head>
<body>
<h1>Hello World!</h1>
<form >
<input id=”cloudinary-input” name=”file” type=”file” class=”cloudinary-fileupload”
data-cloudinary-field=”image_upload”
data-form-data=”” />
<input id=”image_upload” type=”hidden” value=””/>
<input type=”button” value=”Upload” onclick=”upload()”/>
</form
<div class=”.cloudinary-fileupload” src=””/>
</body>
</html>

Ok, that is the base. Now read this:

You need to download the jquery files listed below and put them in the head of your HTML file. You can get them from Cloudinarys jQuery github js directory here. Make sure you have the src attribute pointing to where you’ve downloaded them.

Untitled

You need to customise the value of the ‘params’ object to match your own. A guide to where you can find the values is here:

  • api_key – You can see this in your cloudinary dashboard.
  • public_id – An optional attribute, make it up.
  • timestamp – This is a unix timestamp. you can generate it with the following javascript: Math.floor(Date.now() / 1000); YOUR TIMESTAMP CANNOT BE MORE THAN 1 HOUR OLD
  • cloud_name – This can be seen in your cloudinary dashboard too, at the time of writing, I saw it in the top right hand side of the screen.
  • signature  – THIS IS THE PART WHERE YOU NEED TO PAY ATTENTION. SEE BELOW

Generating a Signature for Cloudinary jQuery Call

  1. lay our the parameters you are using in a string as such: public_id=samplepublicid&timestamp=1448741653. The format is key=value&key=value. They must be in alphabetical order.
  2. In the cloudinary dashboard, find your ‘API Secret’. Assume my API secret is: ‘glenirissecret’.
  3. Tag your secret on to the end of your newly formed string, eg: public_id=samplepublicid&timestamp=1448741653glenirissecret
  4. Generate a SHA1 hash code. You can Google PHP or Java code to do this, however, you can also use this site to do so:     http://www.sha1-online.com/
  5. You should now have a hash value of 9a19e11286b77e7e4f9ba2cb1f8dd4cb40cd67bc
  6. The hash code you generate is now the value of your signature param.
  7. Substitute into your values to my code above and refresh the HTML. Upon uploading your image, you should see an alert box with ‘succcess’!

With inspiration and help from:

Cloudinary Support Form

Telerik Forum

$parse

What the jebus is this:

$parse(states[i].data.lorryDriverStatus)(model)

It says,

treat the value of ‘states[i].data.lorryDriverStatus‘ as a function and pass it ‘model‘ as a paramter.

Angular, continually making me believe its a pile of steaming shite.

Cross Domain Json (jsonp) Request

From the ever knowledgeable Wikipedia:

JSONP or “JSON with padding” is a communication technique used in JavaScript. It provides a method to request data from a server in a different domain, something prohibited by typical web browsers because of the same origin policy.

Recently, I had the requirement, whereby I needed to send several calls, via javascript, to a server. The catch was, that I needed the server to return the results of my calls, in the order in which the calls were made. Making the calls synchronous achieved this. Heres how:

(With inspiration from  this AJAX guy)

function getJson(arrayOfIds){

       jsonRequest = createSyncCORSRequest(“get”, host + “/info/get/”+arrayOfIds.join);

     if (jsonRequest) {
          jsonRequest.onloadend = function() {
               if(jsonRequest .status==200){
                    var jsonResponse = $j.parseJSON(jsonRequest.responseText);
                         functionWhichProcessesJsonResponse(jsonResponse );

              }
          };
          jsonRequest.send();
     }
}
function createSyncCORSRequest(method, url) {
     var xhr = null;
     if (typeof XDomainRequest != “undefined”) {
          xhr = new XDomainRequest();
          xhr.open(method, url,false);//false parameter makes it synchronous
          xhr.setRequestHeader(‘accept’, “application/json”);
     } else {
          xhr = new XMLHttpRequest();
          xhr.open(method, url,false);//false parameter makes it synchronous
          xhr.setRequestHeader(‘accept’, “application/json”);
     }
     return xhr;
}

cross-domain-json

Nelson Vivas, impersonating json leaping from one domain to the next.

Easily find the contents of a JavaScript Object

Instead of tracing the source of a function and going thourgh it to find the elements of a JavaScript Object, place this function in your code (temporrarily) to see what an Object consists of.

var YOUR_JAVASCRIPT_OBJECT = new Object();
YOUR_JAVASCRIPT_OBJECT.name = 'joe';
YOUR_JAVASCRIPT_OBJECT.age = '95';
//below is the loop which prints the contents of our object 
//this would be pretty useful if we cannot see the above code
var object_params;
       for (object_params in YOUR_JAVASCRIPT_OBJECT)
       {
           alert("Your JavaScript has this property: " + object_params);
       }
javascript object contents

The Romford Pele always knew what his JavaScript Objects contained.


Javascript Sets

Recently while writing JavaScript (not jQuery) code, I required the use of a set. In Java, this functionality is provided by the Set collection.

The specifics of which are a collection of object where no duplicates are allowed. As no such object exists (to my knowledge) in JavaScript  I wrote it myself *smug*.

To implement a set in JavaScript  I created an array. I do not want any duplicates in this array and I want to be able to check if an item already exists in the array.

Lets say I have a list of cars.

var car_1 = ‘Ford’;
var car_2 = ‘Nissan’;
var car_3 = ‘Mitsubishi’;
var car_4 = ‘Nissan’;

I want to create an array of cars but with no duplicates:

var cars = []; //an empty array

If I want to add a car to the set (array named cars), only if it does not already exist in the JavaScript set I do so like so:

cars = growSet(cars,car_1);

The growSet function:

/*takes a setname and an item to add to said set. Returns the set with the item added to it.no duplicates */
function growSet(setName,setUnit){

       var exists = false;
          for(var i = 0; i<setName.length; i++){
               if((setName[i]==setUnit)){
                    exists = true;
               }
          }
          if(exists==false){
               if(!(setUnit==’Select All’))
          setName.push(setUnit);
          }
     return setName;
}

If I want to check if a car exists in the set (array named cars), I do so like so:

existsInSet(cars,car_1);

The boolean returning existsInSet function:

/*checks weather or not an item exists in a set without adding/removing said item to/from the set */
function existsInSet(setName,setUnit){
        var exists = false;
              for(var i = 0; i<setName.length; i++){
                     if((setName[i]==setUnit)){
                            exists = true;
                     }
              }
return exists;
}

If I want to remove a car from the set (array named cars), I do so like so:

cars = shrinkSet(cars,car_1);

The shrinkSet function:

/*takes a setname and an item to remove from said set. Returns the set with the item removed from it. */

function shrinkSet(setName,setUnit){
       var newSet = [];
          for(var i = 0; i<setName.length; i++){
               if(setName[i]==setUnit){
                    //do nothing                  

               }else{

                   newSet.push(setName[i]);
               }
     }
return newSet;

}
Finally, enjoy a picture of Dennis Bergkamp.

dennis bergkamp

Dennis Bergkamp, would rather fly than have duplicates in his JavaScript arrays.