quoc bao Pham
quoc bao Pham

Reputation: 321

How to use Ajax on Angular

I want to upload file on server and have progress bar. I use ajax to upload. Now, I want to convert them to angularjs. How to use ajax on angularjs. I'm researching ngularjs. Please, help me.Thanks HTML:

<form action="uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" name="file" multiple><br>
        <input type="submit" value="Upload File to Server">
    </form>

    <div class="progress">
        <div class="bar"></div >
        <div class="percent">0%</div >
    </div>

    <div id="status"></div>

and js file :

<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
        //console.log(percentVal, position, total);
    },
    success: function(xhr) {
        var percentVal = '100%';
        bar.width(percentVal)
        percent.html(percentVal);

    },
    complete: function(xhr) {
        status.html(xhr.responseText);
    }
}); 

})();       
</script>

Upvotes: 0

Views: 95

Answers (2)

Dinesh Jain
Dinesh Jain

Reputation: 149

dataService.DrivingScoreSendOffers=function(offers,callback){
         $.ajax({
            url:url,
            type: "POST/GET",
            cache:false,
            data:{
                "offers":offers,
            },
            success: function (data,textStatus,xhr) {
                callback(data);
            },
            error: function (xhr,exception) {
                 console.log(xhr);
                 console.log(exception);
            },
        });
        };

simple way to call ajax in your APP/Dashboard, in this dataService is just like the service in angularjs to interact with the server (follow the MVC architecture).

Upvotes: 0

wvdz
wvdz

Reputation: 16651

Use $http.

Example from that link:

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

As for showing the progress, this plugin looks very promising: Angular Loading Bar.

It will work even after just including it.

angular.module('myApp', ['angular-loading-bar'])

Upvotes: 1

Related Questions