XMLHttpRequest cannot load http://example.co/task_manager/v1/register. Invalid HTTP status code 404


#1

hallo there,

i have created a rest service for user login, register and logout. this one:

and i have tested it with Advanced Rest Client and it is working very well.

I try to write the code on client side but it seems something is getting wrong as i am a new to this one.

these are my files

app.js

var app = angular.module('myApp', ['ionic','ngCordova','ngRoute', 'ngAnimate', 'toaster'])

app.config(['$routeProvider',
  function ($routeProvider) {
    $routeProvider.
    when('/login', {
        title: 'Login',
        templateUrl: 'partials/login.html',
        controller: 'authCtrl'
    })
        .when('/logout', {
            title: 'Logout',
            templateUrl: 'partials/login.html',
            controller: 'logoutCtrl'
        })
        .when('/signup', {
            title: 'Signup',
            templateUrl: 'partials/signup.html',
            controller: 'authCtrl'
        })
        .when('/dashboard', {
            title: 'Dashboard',
            templateUrl: 'partials/dashboard.html',
            controller: 'authCtrl'
        })
        .when('/', {
            title: 'Login',
            templateUrl: 'partials/login.html',
            controller: 'authCtrl',
            role: '0'
        })
        .otherwise({
            redirectTo: '/login'
        });
}])
.run(function ($rootScope, $location, Data) {
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
        $rootScope.authenticated = false;
        Data.get('session').then(function (results) {
            if (results.uid) {
                $rootScope.authenticated = true;
                $rootScope.uid = results.uid;
                $rootScope.name = results.name;
                $rootScope.email = results.email;
            } else {
                var nextUrl = next.$$route.originalPath;
                if (nextUrl == '/signup' || nextUrl == '/login') {

                } else {
                    $location.path("/login");
                }
            }
        });
    });
});    

authCtrl.js

app.controller('authCtrl', function ($scope, $rootScope, $routeParams, $location, $http, Data) {
//initially set those objects to null to avoid undefined error
$scope.login = {};
$scope.register = {};
$scope.doLogin = function () {
    Data.post('login', {
        }).then(function (results) {
        Data.toast(results);
        if (results.status == "success") {
            $location.path('dashboard');
        }
    });
};
$scope.register = {name:'',email:'',password:''};
$scope.Register = function (register) {
    Data.post('register', {
      		name: register.name,
			email: register.email,
			password: register.password
	    }).then(function (results) {
        Data.toast(results);
        if (results.status == "success") {
            $location.path('dashboard');
        }
    });
};
$scope.logout = function () {
    Data.get('logout').then(function (results) {
        Data.toast(results);
        $location.path('login');
    });
}
});

signup.html

<div class="breadcrumbs" id="breadcrumbs">
<ul class="breadcrumb">
    <li>
        <a href="#">Home</a>
    </li>
    <li class="active">SignUp</li>
</ul>
</div>
 <div class="page-content">
<div class="row">
    <div class="space-6"></div>
    <div class="col-sm-6 col-sm-offset-1">
        <div id="login-box" class="login-box visible widget-box no-border">
            <div class="widget-body">
                <div class="widget-main">
                    <form name="signupForm" class="form-horizontal" role="form">
                          <div class="form-group">
                            <label class="col-sm-5 control-label no-padding-right" for="name">Name</label>
                            <div class="col-sm-7">
                                <span class="block input-icon input-icon-right">
                            <input type="text" class="form-control" placeholder="Name" ng-model="register.name" />
                        </span>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="col-sm-5 control-label no-padding-right" for="email">Email</label>
                            <div class="col-sm-7">
                                <span class="block input-icon input-icon-right">
                                    <input type="text" class="form-control" placeholder="Email" name="email" ng-model="register.email" focus/>
                                    <span ng-show="signupForm.email.$error.email" class="help-inline">Email is not valid</span> 
                                </span>
                            </div>
                        </div>
                  
                        <div class="form-group">
                            <label class="col-sm-5 control-label no-padding-right" for="password">Password</label>
                            <div class="col-sm-7">
                                <span class="block input-icon input-icon-right">
                            <input type="password" class="form-control" name = "password" placeholder="Password" ng-model="register.password" required/>
                            <small class="errorMessage" data-ng-show="signupForm.password.$dirty && signupForm.password.$invalid"> Enter Password.</small>
                        </span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-5 control-label no-padding-right" for="password2">Confirm Password</label>
                            <div class="col-sm-7">
                                <span class="block input-icon input-icon-right">
                            <input type="password" class="form-control" name="password2" placeholder="Password Again" ng-model="register.password2" password-match="register.password" required/>                                
                            <small class="errorMessage" data-ng-show="signupForm.password2.$dirty && signupForm.password2.$error.required"> Enter password again.</small>

                           <small class="errorMessage" data-ng-show="signupForm.password2.$dirty && signupForm.password2.$error.passwordNoMatch && !signupForm.password2.$error.required"> Password do not match.</small>

                        </span>
                            </div>
                        </div>
                                        
                       
                        <div class="form-group">
                            <span class="lbl col-sm-5"> </span>
                            <div class="col-sm-7">
                                <button type="submit" class="width-35 pull-right btn btn-sm btn-primary" ng-click="Register(register)" data-ng-disabled="signupForm.$invalid">
                                    Sign Up
                                </button>
                            </div>
                        </div>
                        </fieldset>
                        <span class="lbl col-sm-5"> </span>
                        <div class="col-sm-7">Already have an account? <a href="#/login">SignIn</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>

i have found solution for the CORS issue by adding the headers in apache server so the problems is not there.

i have always the error of the topic:
XMLHttpRequest cannot load http://example.co/task_manager/v1/register. Invalid HTTP status code 404

and also

OPTIONS http://example.com/task_manager/v1/register ionic.bundle.js:18654

i am afraid about authCtrl.js about the register function.

thank you


Login authentication from database
#2

Of course you’re getting a 404 on http://example.co/task_manager/v1/register1 since this link does not exists. I’m guessing that the author of the post used it as an example.

You should put a valid link to your own server (the place where you’ve put the service code).


#3

hi @Hitman666

of course i use the real url of my server (http://blace.co/task_manager/v1/register) where i have upload my rest service with this error :slight_smile:

i use the Advanced Rest client in chrome and the rest service is working great. I am able to post.


#4

In that case, what seems to be the error? The one you paste above is clearly not the correct one then. Just a heads up - if your api call returns 404, you can be certain that you’re targeting the wrong url.


#5

of course the real error is with the real url

http://blace.co/task_manager/v1/register

i use this url in Advanced Rest client and i am able to post with success.

i am not sure what is going on with my authCtrl.js


#6

Post the contents of your Data service, maybe I’ll figure it from there.


#7

thank you

here you are.

<?php

require_once '../include/DbHandler.php';
require_once '../include/PassHash.php';
require '.././libs/Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

// User id from db - Global Variable
$user_id = NULL;

/**
* Adding Middle Layer to authenticate every request
* Checking if the request has valid api key in the 'Authorization' header
*/
function authenticate(\Slim\Route $route) {
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();

// Verifying Authorization Header
if (isset($headers['Authorization'])) {
    $db = new DbHandler();

    // get the api key
    $api_key = $headers['Authorization'];
    // validating api key
    if (!$db->isValidApiKey($api_key)) {
        // api key is not present in users table
        $response["error"] = true;
        $response["message"] = "Access Denied. Invalid Api key";
        echoRespnse(401, $response);
        $app->stop();
    } else {
        global $user_id;
        // get user primary key id
        $user_id = $db->getUserId($api_key);
    }
} else {
    // api key is missing in header
    $response["error"] = true;
    $response["message"] = "Api key is misssing";
    echoRespnse(400, $response);
    $app->stop();
  }
 }

  /**
  * ----------- METHODS WITHOUT AUTHENTICATION ---------------------------------
  */
  /**
 * User Registration
 * url - /register
 * method - POST
 * params - name, email, password
*/
$app->post('/register', function() use ($app) {
        // check for required params
        verifyRequiredParams(array('name', 'email', 'password'));

        $response = array();

        // reading post params
        $name = $app->request->post('name');
        $email = $app->request->post('email');
        $password = $app->request->post('password');

        // validating email address
        validateEmail($email);

        $db = new DbHandler();
        $res = $db->createUser($name, $email, $password);

        if ($res == USER_CREATED_SUCCESSFULLY) {
            $response["error"] = false;
            $response["message"] = "You are successfully registered";
        } else if ($res == USER_CREATE_FAILED) {
            $response["error"] = true;
            $response["message"] = "Oops! An error occurred while registereing";
        } else if ($res == USER_ALREADY_EXISTED) {
            $response["error"] = true;
            $response["message"] = "Sorry, this email already existed";
        }
        // echo json response
        echoRespnse(201, $response);
    });

/**
 * User Login
 * url - /login
 * method - POST
 * params - email, password
 */
$app->post('/login', function() use ($app) {
        // check for required params
        verifyRequiredParams(array('email', 'password'));

        // reading post params
        $email = $app->request()->post('email');
        $password = $app->request()->post('password');
        $response = array();

        $db = new DbHandler();
        // check for correct email and password
        if ($db->checkLogin($email, $password)) {
            // get the user by email
            $user = $db->getUserByEmail($email);

            if ($user != NULL) {
                $response["error"] = false;
                $response['name'] = $user['name'];
                $response['email'] = $user['email'];
                $response['apiKey'] = $user['api_key'];
                $response['createdAt'] = $user['created_at'];
            } else {
                // unknown error occurred
                $response['error'] = true;
                $response['message'] = "An error occurred. Please try again";
            }
        } else {
            // user credentials are wrong
            $response['error'] = true;
            $response['message'] = 'Login failed. Incorrect credentials';
        }

        echoRespnse(200, $response);
    });

/*
 * ------------------------ METHODS WITH AUTHENTICATION ------------------------
 */

/**
 * Listing all tasks of particual user
 * method GET
 * url /tasks          
 */
$app->get('/tasks', 'authenticate', function() {
        global $user_id;
        $response = array();
        $db = new DbHandler();

        // fetching all user tasks
        $result = $db->getAllUserTasks($user_id);

        $response["error"] = false;
        $response["tasks"] = array();

        // looping through result and preparing tasks array
        while ($task = $result->fetch_assoc()) {
            $tmp = array();
            $tmp["id"] = $task["id"];
            $tmp["task"] = $task["task"];
            $tmp["status"] = $task["status"];
            $tmp["createdAt"] = $task["created_at"];
            array_push($response["tasks"], $tmp);
        }

        echoRespnse(200, $response);
    });

/**
 * Listing single task of particual user
 * method GET
 * url /tasks/:id
 * Will return 404 if the task doesn't belongs to user
 */
$app->get('/tasks/:id', 'authenticate', function($task_id) {
        global $user_id;
        $response = array();
        $db = new DbHandler();

        // fetch task
        $result = $db->getTask($task_id, $user_id);

        if ($result != NULL) {
            $response["error"] = false;
            $response["id"] = $result["id"];
            $response["task"] = $result["task"];
            $response["status"] = $result["status"];
            $response["createdAt"] = $result["created_at"];
            echoRespnse(200, $response);
        } else {
            $response["error"] = true;
            $response["message"] = "The requested resource doesn't exists";
            echoRespnse(404, $response);
        }
    });

/**
 * Creating new task in db
 * method POST
 * params - name
 * url - /tasks/
 */
$app->post('/tasks', 'authenticate', function() use ($app) {
        // check for required params
        verifyRequiredParams(array('task'));

        $response = array();
        $task = $app->request->post('task');

        global $user_id;
        $db = new DbHandler();

        // creating new task
        $task_id = $db->createTask($user_id, $task);

        if ($task_id != NULL) {
            $response["error"] = false;
            $response["message"] = "Task created successfully";
            $response["task_id"] = $task_id;
            echoRespnse(201, $response);
        } else {
            $response["error"] = true;
            $response["message"] = "Failed to create task. Please try again";
            echoRespnse(200, $response);
        }            
    });

/**
 * Updating existing task
 * method PUT
 * params task, status
 * url - /tasks/:id
 */
$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
        // check for required params
        verifyRequiredParams(array('task', 'status'));

        global $user_id;            
        $task = $app->request->put('task');
        $status = $app->request->put('status');

        $db = new DbHandler();
        $response = array();

        // updating task
        $result = $db->updateTask($user_id, $task_id, $task, $status);
        if ($result) {
            // task updated successfully
            $response["error"] = false;
            $response["message"] = "Task updated successfully";
        } else {
            // task failed to update
            $response["error"] = true;
            $response["message"] = "Task failed to update. Please try again!";
        }
        echoRespnse(200, $response);
    });

/**
 * Deleting task. Users can delete only their tasks
 * method DELETE
 * url /tasks
 */
$app->delete('/tasks/:id', 'authenticate', function($task_id) use($app) {
        global $user_id;

        $db = new DbHandler();
        $response = array();
        $result = $db->deleteTask($user_id, $task_id);
        if ($result) {
            // task deleted successfully
            $response["error"] = false;
            $response["message"] = "Task deleted succesfully";
        } else {
            // task failed to delete
            $response["error"] = true;
            $response["message"] = "Task failed to delete. Please try again!";
        }
        echoRespnse(200, $response);
    });

/**
 * Verifying required params posted or not
 */
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
    $app = \Slim\Slim::getInstance();
    parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
    if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
        $error = true;
        $error_fields .= $field . ', ';
    }
}

if ($error) {
    // Required field(s) are missing or empty
    // echo error json and stop the app
    $response = array();
    $app = \Slim\Slim::getInstance();
    $response["error"] = true;
    $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
    echoRespnse(400, $response);
    $app->stop();
 }
}

/**
 * Validating email address
 */
function validateEmail($email) {
$app = \Slim\Slim::getInstance();
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $response["error"] = true;
    $response["message"] = 'Email address is not valid';
    echoRespnse(400, $response);
    $app->stop();
 }
}

/**
 * Echoing json response to client
 * @param String $status_code Http response code
 * @param Int $response Json response
 */
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);

// setting response content type to json
$app->contentType('application/json');

echo json_encode($response);
}

$app->run();
?>

#8

Are you setting CORS headers on PHP ?


#9

hallo @cybernatic

in this php file i have not set. But i have ovewhelmed CORS issue on the server. i have enabled in the .htaccess file. Before did that i had errors of CORS but not anymore. so i believe it is not anymore CORS ISSUE


#10

in angularjs there is an addon for sending POST requests you have to change headers on request.
Its may be issue with ‘Content-Type’

Try to add this in your config

var q = $q.defer();

// $http.post(apiURL,{‘name’:searchTerm}, config)

$http({
	method: 'POST',
	url:sugURL,
	data: "q=" + searchTerm,
	headers: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Application-request':'TRUE' 
				 
			}
}).then(function(result){
    return !validateResponse(result)? q.reject(new Error('Invalid Response')):q.resolve(result.data);
   },function(err){
     console.log('search/'+searchTerm+' Failed');
     q.reject(err);
  });

return q.promise;


#11

you mean all of this?? in my config.php on the server??

var q = $q.defer();

// $http.post(apiURL,{'name':searchTerm}, config)

$http({
method: 'POST',
url:sugURL,
data: "q=" + searchTerm,
headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Application-request':'TRUE' 

		}
}).then(function(result){
return !validateResponse(result)? q.reject(new Error('Invalid Response')):q.resolve(result.data);
},function(err){
 console.log('search/'+searchTerm+' Failed');
 q.reject(err);
 });
return q.promise;

#12

No its in app.
Its making a request from app.


#13

ohh i see.
ok @cybernatic i am at work right now, i will try it when i am back home and let you know!

thank you very much for the interest and the help!


#14

Ok will be glad if its helps.
For now im building an app which uses REST API.
So this code from there =)
Will be waiting for your reply,helps or not anyway write… Will be searching foward for solution


#15

ok i think i have put the code in the right file, a config.xml inside the app`s folder.

so now the file looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="com.ionicframework.angularcodeauthenticationapp735189" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>angularcode-authentication-app</name>
<description>
    An Ionic Framework and Cordova project.
</description>
<author email="hi@ionicframework" href="http://ionicframework.com/">
  Ionic Framework Team
</author>
<content src="index.html"/>
<access origin="*"/>
<preference name="webviewbounce" value="false"/>
<preference name="UIWebViewBounce" value="false"/>
<preference name="DisallowOverscroll" value="true"/>
<preference name="android-minSdkVersion" value="16"/>
<preference name="BackupWebStorage" value="none"/>
<feature name="StatusBar">
<param name="ios-package" value="CDVStatusBar" onload="true"/>
</feature>
var q = $q.defer();

// $http.post(apiURL,{'name':searchTerm}, config)

$http({
method: 'POST',
url:sugURL,
data: "q=" + searchTerm,
headers: {
		'Content-Type': 'application/x-www-form-urlencoded',
		'Application-request':'TRUE' 

	}
}).then(function(result){
return !validateResponse(result)? q.reject(new Error('Invalid Response')):q.resolve(result.data);
},function(err){
console.log('search/'+searchTerm+' Failed');
q.reject(err);
 });
return q.promise;
</widget>

and unfortunately it is not working :frowning:

maybe i have place it in wrong file?

this is my data.js

app.factory("Data", ['$http', 'toaster',
function ($http, toaster) { // This service connects to our REST API

    var serviceBase = 'http://blace.co/task_manager/v1/';

    var obj = {};
    obj.toast = function (data) {
        toaster.pop(data.status, "", data.message, 10000, 'trustedHtml');
    }
    obj.get = function (q) {
        return $http.get(serviceBase + q).then(function (results) {
            return results.data;
        });
    };
    obj.post = function (q, object) {
        return $http.post(serviceBase + q, object).then(function (results) {
            return results.data;
        });
    };
    obj.put = function (q, object) {
        return $http.put(serviceBase + q, object).then(function (results) {
            return results.data;
        });
    };
    obj.delete = function (q) {
        return $http.delete(serviceBase + q).then(function (results) {
            return results.data;
        });
    };

    return obj;
}]);

and this is my app.js

var app = angular.module('myApp', ['ionic','ngCordova','ngRoute', 'ngAnimate', 'toaster'])

app.config(['$routeProvider',
function ($routeProvider) {
    $routeProvider.
    when('/login', {
        title: 'Login',
        templateUrl: 'partials/login.html',
        controller: 'authCtrl'
    })
        .when('/logout', {
            title: 'Logout',
            templateUrl: 'partials/login.html',
            controller: 'logoutCtrl'
        })
        .when('/signup', {
            title: 'Signup',
            templateUrl: 'partials/signup.html',
            controller: 'authCtrl'
        })
        .when('/dashboard', {
            title: 'Dashboard',
            templateUrl: 'partials/dashboard.html',
            controller: 'authCtrl'
        })
        .when('/', {
            title: 'Login',
            templateUrl: 'partials/login.html',
            controller: 'authCtrl',
            role: '0'
        })
        .otherwise({
            redirectTo: '/login'
        });
  }])
 .run(function ($rootScope, $location, Data) {
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
        $rootScope.authenticated = false;
        Data.get('session').then(function (results) {
            if (results.uid) {
                $rootScope.authenticated = true;
                $rootScope.uid = results.uid;
                $rootScope.name = results.name;
                $rootScope.email = results.email;
            } else {
                var nextUrl = next.$$route.originalPath;
                if (nextUrl == '/signup' || nextUrl == '/login') {

                } else {
                    $location.path("/login");
                }
            }
        });
     });
   });

#16

No its wrong!
You have to put this code at service.js or app.js where you doing HTTP request to your webserver dude


#17

here on your data.js you have to add header option
like this

obj.get = function (q) {
    return $http.get(serviceBase + q).then(function (results) {
        return results.data;
    });
};

will be someting like

$http({

method: ‘GET’,
url:‘http://your.tld’,//YOUR URL HERE
data: “q=” + searchTerm,//YOUR DATA
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘Application-request’:‘TRUE’

	}

}).then(function(result){
return !validateResponse(result)? q.reject(new Error(‘Invalid Response’)):q.resolve(result.data);
},function(err){
console.log(‘search/’+searchTerm+’ Failed’);
q.reject(err);
});


#18

hi @cybernatic

thank you dude for your interest!

forgive me but i am kind of newbie on this one.

so if i understand right i shoud add to the functions of get, post, put, delete with headers.

for example this one:

obj.toast = function (data) {
        toaster.pop(data.status, "", data.message, 10000, 'trustedHtml');
    }

should be

$http({
 method: 'GET',
 url:'http://your.tld',//YOUR URL HERE
 data: "q=" + searchTerm,//YOUR DATA
 headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Application-request':'TRUE'
 }
}).then(function(result){
return !validateResponse(result)? q.reject(new Error('Invalid Response')):q.resolve(result.data);
},function(err){
console.log('search/'+searchTerm+' Failed');
q.reject(err);
});

something like this?

but in this one there is nowhere the toaster which makes the connection with the REST API.

toaster.js

'use strict';

/*
 * AngularJS Toaster
 * Version: 0.4.4
 *
 * Copyright 2013 Jiri Kavulak.  
 * All Rights Reserved.  
 * Use, reproduction, distribution, and modification of this code is subject to the terms and 
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Author: Jiri Kavulak
 * Related to project of John Papa and Hans Fjällemark
 */

angular.module('toaster', ['ngAnimate'])
.service('toaster', ['$rootScope', function ($rootScope) {
 this.pop = function (type, title, body, timeout, bodyOutputType) {
    this.toast = {
        type: type,
        title: title,
        body: body,
        timeout: timeout,
        bodyOutputType: bodyOutputType
    };
    $rootScope.$broadcast('toaster-newToast');
   };

  this.clear = function () {
    $rootScope.$broadcast('toaster-clearToasts');
  };
}])
.constant('toasterConfig', {
'limit': 0,                   // limits max number of toasts 
'tap-to-dismiss': true,
'newest-on-top': true,
//'fade-in': 1000,            // done in css
//'on-fade-in': undefined,    // not implemented
//'fade-out': 1000,           // done in css
// 'on-fade-out': undefined,  // not implemented
//'extended-time-out': 1000,    // not implemented
'time-out': 5000, // Set timeOut and extendedTimeout to 0 to make it sticky
'icon-classes': {
    error: 'toast-error',
    info: 'toast-info',
    success: 'toast-success',
    warning: 'toast-warning'
},
'body-output-type': '', // Options: '', 'trustedHtml', 'template'
'body-template': 'toasterBodyTmpl.html',
'icon-class': 'toast-info',
'position-class': 'toast-bottom-left',
'title-class': 'toast-title',
'message-class': 'toast-message'
})
.directive('toasterContainer', ['$compile', '$timeout', '$sce', 'toasterConfig', 'toaster',
function ($compile, $timeout, $sce, toasterConfig, toaster) {
return {
    replace: true,
    restrict: 'EA',
    link: function (scope, elm, attrs) {

        var id = 0;

        var mergedConfig = toasterConfig;
        if (attrs.toasterOptions) {
            angular.extend(mergedConfig, scope.$eval(attrs.toasterOptions));
        }

        scope.config = {
            position: mergedConfig['position-class'],
            title: mergedConfig['title-class'],
            message: mergedConfig['message-class'],
            tap: mergedConfig['tap-to-dismiss']
        };

        scope.configureTimer = function configureTimer(toast) {
            var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out'];
            if (timeout > 0)
                setTimeout(toast, timeout);
        };

        function addToast(toast) {
            toast.type = mergedConfig['icon-classes'][toast.type];
            if (!toast.type)
                toast.type = mergedConfig['icon-class'];

            id++;
            angular.extend(toast, { id: id });

            // Set the toast.bodyOutputType to the default if it isn't set
            toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type']
            switch (toast.bodyOutputType) {
                case 'trustedHtml':
                    toast.html = $sce.trustAsHtml(toast.body);
                    break;
                case 'template':
                    toast.bodyTemplate = toast.body || mergedConfig['body-template'];
                    break;
            }

            scope.configureTimer(toast);

            if (mergedConfig['newest-on-top'] === true) {
                scope.toasters.unshift(toast);
                if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                    scope.toasters.pop();
                }
            } else {
                scope.toasters.push(toast);
                if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                    scope.toasters.shift();
                }
            }
        }

        function setTimeout(toast, time) {
            toast.timeout = $timeout(function () {
                scope.removeToast(toast.id);
            }, time);
        }

        scope.toasters = [];
        scope.$on('toaster-newToast', function () {
            addToast(toaster.toast);
        });

        scope.$on('toaster-clearToasts', function () {
            scope.toasters.splice(0, scope.toasters.length);
        });
    },
    controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {

        $scope.stopTimer = function (toast) {
            if (toast.timeout) {
                $timeout.cancel(toast.timeout);
                toast.timeout = null;
            }
        };

        $scope.restartTimer = function (toast) {
            if (!toast.timeout)
                $scope.configureTimer(toast);
        };

        $scope.removeToast = function (id) {
            var i = 0;
            for (i; i < $scope.toasters.length; i++) {
                if ($scope.toasters[i].id === id)
                    break;
            }
            $scope.toasters.splice(i, 1);
        };

        $scope.remove = function (id) {
            if ($scope.config.tap === true) {
                $scope.removeToast(id);
            }
        };
    }],
    template:
    '<div  id="toast-container" ng-class="config.position">' +
        '<div ng-repeat="toaster in toasters" class="toast" ng-class="toaster.type" ng-    click="remove(toaster.id)" ng-mouseover="stopTimer(toaster)"  ng-mouseout="restartTimer(toaster)">' +
          '<div ng-class="config.title">{{toaster.title}}</div>' +
          '<div ng-class="config.message" ng-switch on="toaster.bodyOutputType">' +
            '<div ng-switch-when="trustedHtml" ng-bind-html="toaster.html"></div>' +
            '<div ng-switch-when="template"><div ng-include="toaster.bodyTemplate"></div></div>' +
            '<div ng-switch-default >{{toaster.body}}</div>' +
          '</div>' +
        '</div>' +
    '</div>'
   };
}]);

i tried this one for POST for the register of my app

 $http({
 method: 'POST',
 url:'http://blace.co/task_manager/v1/register',//YOUR URL HERE
 data: 'q=',//YOUR DATA
 headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Application-request':'TRUE'
 }
}).then(function(result){
return !validateResponse(result)? q.reject(new Error('Invalid Response')):q.resolve(result.data);
},function(err){
console.log('search/'+searchTerm+' Failed');
q.reject(err);
});

but i have this error

TypeError: Data.post is not a function

and i do not know what to incluce in this one

 data: 'q=',//YOUR DATA

thank you!


#19

is not
data in $http method.
Its about your DATA service. Please if you can post all js files i will try to help. Thanks


#20

Hi @cybernatic

really thank you very much for your help. I am at work right now, so in 3 hours i will post them. I know this is a forum, but could you share your email to send them there too?

thank you very much!