0

I want to run the first ajax call when it has completed run the function "saveToFile()" and after that has been completed run the second ajax call. Doesn't seem to work as coded. I'm fairly new to ajax so am struggling a little with this one.

// save composition to database 
$.ajax({ 
    type: "POST", 
    url: "_inc/save_to_db.php", 
    data: {jsonStr: canvasStr}, 
    success: function(data) {
            // this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
            saveToFile();

            $.ajax({
            type: "POST".
            url: "_inc/generate_thumbnail.php",
            data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
            });
        }
    });
3
  • Can you share saveToFile? Commented Jun 17, 2013 at 6:30
  • 2
    If it is a asynchronous function then you need to use a callback to sent the second ajax request Commented Jun 17, 2013 at 6:31
  • 1
    You need this: api.jquery.com/category/deferred-object Commented Jun 17, 2013 at 6:32

2 Answers 2

1

Works for me: http://jsbin.com/upujur/2/edit

The problem might be with the dot instead of comma in this line:

type: "POST".

Are you using a JavaScript console like FireBug or Developer Tools to debug your program?

Sign up to request clarification or add additional context in comments.

Comments

1

You could make the saveToFile function take as parameter a callback which will be executed once the AJAX call it performs is finished. For example:

$.ajax({ 
    type: "POST", 
    url: "_inc/save_to_db.php", 
    data: {jsonStr: canvasStr}, 
    success: function(data) {
        // this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
        saveToFile(function(result) {
            $.ajax({
                type: "POST",
                url: "_inc/generate_thumbnail.php",
                data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
            });
        });
    }
});

and your saveToFile function may now look like that:

function saveToFile(successCallback) {
    $.ajax({
        url: ...,
        type: ...,
        data: ...,
        success: successCallback
    });
}

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.