BioL February 2016

jquery (a)synchronous request to wait for

I'm really new in javascript and I got my first problem with jquery and AJAX request. I have many toggles on a page and when I click them, I have to ask a REST service to query if I can or not. If I can I will show an alert box with are you sure blablabla and if not an alert that says that the user can't.

Here is the main problem, If i use async:false it works but as I could read it's not a good practice (and chrome remember me that is not) so what is the good way to do that?

I'm using backbone and I don't want for every toggle to set up a method to handle the click and a second method to handle the call back.

What is the good way of doing that?

startService: function(serviceName){
        var confirm = true;

        var $paid = this.model.getPaidTo(serviceName);
        console.log(this.model.getPaidTo(serviceName));
        //Here the consol.log is always undefined if I use async: true

        if ($paid == 'false'){
            confirm = confirm("Are you sure to start" + this.model.services[serviceName].price + ". Continue ?");
        }

        if(confirm){
            console.log("start " + serviceName + " service")
            return true;
        }
        return false;
    },

Model:

getPaidTo: function(serviceName){
        var self = this;
        var Url = require.apiUrl + "profile/girl/" + this.loginModel.id + "/checkservice/" + serviceName;

        $.ajax({
            type: "GET",
            url: Url,
            data: {},
            success: function(data){
                return data.data.service;
            },
            error: function(data){
                self.error = 'error';
                return 'error';
            }
        });
    }

Best regards

Answers


BioL February 2016

Thanks Slaks,

It's working perfectly. Here is the way I did the modification:

startService: function(serviceName){
        var self = this;
        var confirm = true;

        //var $paid = this.model.getPaidTo(serviceName);
        this.model.getPaidTo(serviceName).done(function(data){
            $paid = data.data.service;

            if ($paid == 'false'){
                confirm = window.confirm("Are you sure to start" + self.model.services[serviceName].price + ". Continue ?");
            }

            if(confirm){
                console.log("start " + serviceName + " service");
            }

        }).fail(function(){
            alert('error');
        });
    },

Model:

getPaidTo: function(serviceName){
        var Url = require.apiUrl + "profile/girl/" + this.loginModel.id + "/checkservice/" + serviceName;

        return $.ajax({
            type: "GET",
            url: Url
        });
    }

Hope it will helps other people.

Best regards

Post Status

Asked in February 2016
Viewed 3,570 times
Voted 11
Answered 1 times

Search




Leave an answer