0

I have a script that writes text on a canvas. It works fine. The problem is if I make an Ajax call to first get the string and then secondly write the string to the canvas, JavaScript seems to ignore the order that I want things done and write the string before the Ajax call; the result is the script prints to the canvas 'undefined'.

psuedocode:

//var str = ~some_ajax_call...  <---If I use this, the output is undefined.
var str = "hello world";

context.fillStyle    = '#00f';
context.font         = 'italic 30px sans-serif';
context.textBaseline = 'top';
context.fillText  (str, 0, 0);

2 Answers 2

1

Ajax is assync, so your code below the ajax call runs before the response from the server. You need to run your code only when the HTTP Response is received.

With jQuery, it would be something like this:

$.ajax({
  url: "sample.php",
  success: function(d) {
    context.fillStyle    = '#00f';
    context.font         = 'italic 30px sans-serif';
    context.textBaseline = 'top';
    context.fillText  (d, 0, 0);
});
Sign up to request clarification or add additional context in comments.

Comments

0

As ajax calls are asynchronous, you'll have to put your printing logic in the success callback of the ajax op.

For example:

var str = "hello world";

$.ajax({
    url: '/echo/json/',
    success: function(data){
        var context = document.getElementById('c').getContext('2d');
        context.fillStyle    = '#00f';
        context.font         = 'italic 30px sans-serif';
        context.textBaseline = 'top';
        context.fillText  (str, 0, 0);
    }
});

http://jsfiddle.net/BhENZ/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.