Kuubs
Kuubs

Reputation: 1340

Promises and uploading data

I've got some problems regarding sending a form online or saving it locally. I have an Phonegap application which is just a simple form which get saved to a database, or if that fails, locally.

I have everything set up only this fucntion. Firstly I thought, I just do it with Boooleans, run the fucntion and if everything goed well return True. But that doesn't work because the code just gets executed before I have a value to compare, which means the value will be always false.

This is the code now:

if(uploadDataAndImage(formData))
{
 //Its true, do my things
}
else
{
//Its false
}

This is the boolean fucntion:

function uploadDataAndImage(dataForm) {

                var localURL = dataForm.cardurl;
                console.log(localURL);

                if(localURL == "")
                {
                    $$.ajax({
                        type: "POST",
                        url: "upload.php",
                        crossDomain: true,
                        data: dataForm,
                        success:function(data)
                        {
                            console.log("Upload to server without card");
                            return true;
                        },
                        error: function()
                        {
                            console.log("Form couldn't upload to the server");
                            //alert("Couldnt upload to server, saving locally");
                            return false;
                        }
                    });

                }
                else{
                    //set upload options
                    var options = new FileUploadOptions();

                    options.chunkedMode = false;

                    console.log("Start upload picture");

                    var ft = new FileTransfer();
                    ft.upload(deLokaleURL, encodeURI("uploaderino.php"), win, fail, options);

                    function win(r) {
                        console.log("Code = " + r.responseCode);
                        console.log("R" + r.response);
                        console.log("Sent = " + r.bytesSent);

                        dataForm.cardurl = r.response;
                        var dataString = JSON.stringify(dataForm);



                        $$.ajax({
                            type: "POST",
                            url: "upload.php",
                            crossDomain: true,
                            data: dataForm,
                            success:function(data)
                            {
                                console.log("Upload to server with card");
                                return true;
                            },
                            error: function()
                            {
                                console.log("Form couldn't upload to the server, do nothing");
                                return false;

                            }
                        });



                    }

                    function fail(error) {
                        //alert("An error has occurred: Code = " + error.code);
                        console.log("An error has occurred: Code = " + error.code);
                        console.log("upload error source " + error.source);
                        console.log("upload error target " + error.target);


                        showMessage("Image upload has failed, get a better internet connection and try again!" , function(){console.log("Upload van de form is mislukt!")});
                        return false;

                    }
                }



            }

But this obviously doesn't work. Now I've done some research and asked soem questions and I've found Promises. But I cannot seem to grasp how I can use this.

I thought something like this:

var deferred = $.Deferred();

                deferred.resolve(uploadDataAndImage(formData));

                deferred.done(function(value) {
                  //Upload went well so do my things
                });

But that is not how it works, right/?

Upvotes: 1

Views: 1309

Answers (3)

Vic
Vic

Reputation: 8961

You can use promises, something like this:

uploadDataAndImage(formData)
    .done(function(){
        // Its true, do my things
    }).fail(function(){
        //Its false
    });

function uploadDataAndImage(dataForm) {
    var deferred = $.Deferred();
    var localURL = dataForm.cardurl;
    console.log(localURL);

    if (localURL == "") {
        $$.ajax({
            type: "POST",
            url: "upload.php",
            crossDomain: true,
            data: dataForm,
            success: function(data) {
                console.log("Upload to server without card");
                deferred.resolve();
            },
            error: function() {
                console.log("Form couldn't upload to the server");
                //alert("Couldnt upload to server, saving locally");
                deferred.reject();
            }
        });

    } else {
        //set upload options
        var options = new FileUploadOptions();

        options.chunkedMode = false;

        console.log("Start upload picture");

        var ft = new FileTransfer();
        ft.upload(deLokaleURL, encodeURI("uploaderino.php"), win, fail, options);

        function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("R" + r.response);
            console.log("Sent = " + r.bytesSent);

            dataForm.cardurl = r.response;
            var dataString = JSON.stringify(dataForm);



            $$.ajax({
                type: "POST",
                url: "upload.php",
                crossDomain: true,
                data: dataForm,
                success: function(data) {
                    console.log("Upload to server with card");
                    deferred.resolve();
                },
                error: function() {
                    console.log("Form couldn't upload to the server, do nothing");
                    deferred.reject();

                }
            });



        }

        function fail(error) {
            //alert("An error has occurred: Code = " + error.code);
            console.log("An error has occurred: Code = " + error.code);
            console.log("upload error source " + error.source);
            console.log("upload error target " + error.target);


            showMessage("Image upload has failed, get a better internet connection and try again!", function() {
                console.log("Upload van de form is mislukt!")
            });
            deferred.reject();

        }
    }
    return deferred.promise();
}

Upvotes: 1

Jesse Buitenhuis
Jesse Buitenhuis

Reputation: 670

Use deferred inside the uploadDataAndImage to return a promise. You can then use then() and catch() to do something when the ajax call is finished.

function uploadDataAndImage() {
  var deferred = $.Deferred();

  $$.ajax({
    type: "POST",
    url: "upload.php",
    crossDomain: true,
    data: dataForm,
    success:function(data) {
      deferred.resolve();
    }, error: function(e) {
      deferred.reject(e);
    }
  });

  return deferred.promise;
}

uploadDataAndImage(formData).then(function() {
  //Its true, do my things
}).catch(function() {
  //Its false
});

Upvotes: 2

Jamie Hutber
Jamie Hutber

Reputation: 28076

I'd just set it up to use a callBack function. Something like this maybe

uploadDataAndImage(formData, function(data){
     console.log(data);
     if(data){
         //do something in here that needs doing as the ajax call was true
     }
     else
     {
        //Do something after the ajax returned an error...
     }
})

function uploadDataAndImage(dataForm, callBack) {

                var localURL = dataForm.cardurl;
                console.log(localURL);

                if(localURL == "")
                {
                    $$.ajax({
                        type: "POST",
                        url: "upload.php",
                        crossDomain: true,
                        data: dataForm,
                        success:function(data)
                        {
                            console.log("Upload to server without card");
                            callBack(true);
                        },
                        error: function()
                        {
                            callBack(false);
                        }
                    });

                }
                else{
                    //set upload options
                    var options = new FileUploadOptions();

                    options.chunkedMode = false;

                    console.log("Start upload picture");

                    var ft = new FileTransfer();
                    ft.upload(deLokaleURL, encodeURI("uploaderino.php"), win, fail, options);

                    function win(r) {
                        console.log("Code = " + r.responseCode);
                        console.log("R" + r.response);
                        console.log("Sent = " + r.bytesSent);

                        dataForm.cardurl = r.response;
                        var dataString = JSON.stringify(dataForm);



                        $$.ajax({
                            type: "POST",
                            url: "upload.php",
                            crossDomain: true,
                            data: dataForm,
                            success:function(data)
                            {
                                callBack(true);
                            },
                            error: function()
                            {
                                callBack(false);

                            }
                        });



                    }

                    function fail(error) {
                        //alert("An error has occurred: Code = " + error.code);
                        console.log("An error has occurred: Code = " + error.code);
                        console.log("upload error source " + error.source);
                        console.log("upload error target " + error.target);


                        showMessage("Image upload has failed, get a better internet connection and try again!" , function(){console.log("Upload van de form is mislukt!")});
                        return false;

                    }
                }



            }

You can play around with what you want the function to do, I'm not 100% sure what you're wanting :) But whatever you put in the function will execute after the ajax calls have been made.

Upvotes: 1

Related Questions