0

I am trying to get image in Base64 format outside of

var codedPic;
var purl = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';

var codedPic = convertImgToBase64(purl, function(base64Img){ console.log('attempt 1: ' + base64Img); });

console.log('attempt 2: ' + codedPic);

It is getting results of attempt 1 but for attempt 2 it displays undefined. But I need it working too. Can anyone help me please?

Please feel free to amend this jsfiddle: http://jsfiddle.net/s7x0otdc/2/

qqruza
  • 1,385
  • 4
  • 20
  • 41

2 Answers2

0

(in fiddle) after you complete the conversion, you call callback, therefore nothing is stored in codedPic variable. you can fix it by using return codedPic; instead of using callback or you can do everything you need in that callback function (because after completing callback function you lose "hers" variables)

i suppose there is some way with global vars.. but just now i don't know how i would do that

Jimmmy
  • 579
  • 12
  • 26
0

EDIT:

New demo to show you how to modularize your code. The encoded picture is available outside of your conversion function (more precisely in your global variable codedPic). But you have to wait for your callback to be triggered to be sure it now has the correct value.

http://jsfiddle.net/s7x0otdc/7/


Well you have several mistakes in your code.

  1. As pointed out by Jimmmy, your function does not return anything, so the assignment var codedPic = convertImgToBase64(purl /* ... */ ); is useless as codedPic will remain undefined.
  2. Time to read How to return the response from an asynchronous call? to understand why you need to use callbacks, and that you have to put any code that depends on a server response inside a callback. Since your conversion function needs to wait for the load event of your image, you will get data into dataURL at an unkown moment in the future. When this moment arrives, JS will trigger your callback and give it that data as argument, as per your conversion function specifies. So only your callback can safely assign your desired data into a global variable, and trigger any action that depend on that data.

Demo: http://jsfiddle.net/s7x0otdc/5/

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • Thank you but is there any way to get base64Img value outside of codedPic finction??? – qqruza Nov 12 '15 at 18:53
  • Well it **is** available outside of the **`convertImgToBase64`** function, and assigned to `codedPic` variable… The problem is **when** the value is correct. Only once your callback is triggered you know you can safely use what is inside `codedPic`. So the idea is to call anything that depends on that value, from that callback. Let me update the jsfiddle to show you how you could use functions to get modularity. – ghybs Nov 12 '15 at 19:06