Get token with Angularjs - javascript

I'm working on an Angularjs + Moodle + WebService APP
I have done a little Login page and have a question.
I'm getting the Token of my user via $.ajax and I can see it in my chrome console.
The thing is, I want to save that token for using it in WS moodle fuctions and I'm usin JSON.strungify to get the token, but I have not successed.
I just get -> {readystate: 1} as an alert, instead get a token. but in my console.info(response); I got the token as show the next image :
Thi is my code:
controller.js
var app = angular.module('mainApp', ['ngRoute', 'toaster', 'ngAnimate']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html'
})
.when('/dashboard', {
resolve: {
"check": function($location, $rootScope) {
if(!$rootScope.loggedIn){
$location.path('/');
}
}
},
templateUrl: 'dashboard.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('loginCtrl',
function($scope, $location, $rootScope) {
$scope.submit = function() {
/*if($scope.username == 'admin' && $scope.password == 'admin') {
$rootScope.loggedIn = true;
$location.path('/dashboard');
} else {
alert('Wrong Stuff');
}*/
$rootScope.loggedIn = true;
var username = $scope.username;
var password = $scope.password;
postCredentials(username, password/*, createSession*/);
};
function postCredentials(username, password, callback) {
if (username!==null || password!==null) {
var serverurl = 'https://comunidaddeaprendizaje.cl/ac-cap/login/token.php';
var data = {
username: username,
password: password,
service: 'moodle_mobile_app' // your webservice name
}
var response = $.ajax(
{ type: 'POST',
data: data,
url: serverurl,
dataType: 'JSON'
}
);
console.info(response);
dataString = JSON.stringify(response);
alert(dataString);
if (dataString.indexOf('error') > 0) {
alert('Invalid user credentials, please try again');
};
} else {
alert('Something Wrong');
}
}
}
);
login.html
div class="breadcrumbs" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
Home
</li>
<li class="active">Login</li>
</ul>
</div>
<div class="page-content">
<div class="row">
<div class="space-6"></div>
<div class="col-sm-10 col-sm-offset-1">
<div id="login-box" class="login-box visible widget-box no-border">
<div class="widget-body">
<div class="widget-main">
<h4>Login ACCAP</h4>
<div ng-controller="loginCtrl">
<form action="/" class="form-horizontal" id="myLogin">
<div class="form-group">
UserName:
<input type="text" class="form-control" id="username" ng-model="username" required focus><br>
Password:
<input type="password" class="form-control" id="password" ng-model="password" required>
</br>
<button type="button" class="width-35 pull-right btn btn-sm btn-primary" ng-click="submit()">
<div class="col-sm-7">
<i class="ace-icon fa fa-key"></i>
Login
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login APP</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/1.1.0/toaster.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.7/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.js"></script>
<script src="https://code.angularjs.org/1.2.0/angular-animate.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/1.1.0/toaster.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-view></div>
</body>
</html>
Thanks for your help!

The response variable is an object which contains a lot of information about the response. It is not the same as your response text.
Your second mistake is that your AJAX call is asynchronous, so you cannot obtain your response immediately after AJAX call. You need to wait for the response. Instead of
var response = $.ajax({
type: 'POST',
data: data,
url: serverurl,
dataType: 'JSON'
});
console.info(response);
dataString = JSON.stringify(response);
alert(dataString);
if(dataString.indexOf('error') > 0) {
alert('Invalid user credentials, please try again');
};
you should write
var response = $.ajax({
type: 'POST',
data: data,
url: serverurl,
dataType: 'JSON',
success: function(response) {
console.info(response);
dataString = JSON.stringify(response);
alert(dataString);
if(dataString.indexOf('error') > 0) {
alert('Invalid user credentials, please try again');
};
}
});

Related

ajax is not working in Laravel showing page not found

I want to send OTP with Laravel and ajax but when i'm calling ajax it shows error page not found...
HTML:
`
<div id="first_step">
<div class="col-md-4">
<input value="+91" type="text" placeholder="+1" id="country_code" name="country_code" />
</div>
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
`
script:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
var host = "{{URL::to('/')}}";
alert(host);
$.ajax({
type: "POST",
url: host+"/send_otp",
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
}); });
Route in web.php:
Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function');
//Route::post('/send_otp', 'AccountAuth\RegisterController#send_otp_function'); also try this
Controllers:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return Response::json($response);
}
Welcome to SO. As far as I understand and according to jQuery.ajax documentation you have forgotten to set datatype='json' in your ajax request. Your request should be:
$.ajax({
type: "POST",
url: host + "/send_otp",
datatype: 'json',
data: {
name: phone_number
},
success: function(msg) {
alert(msg);
},
error: function(request, status, error) {
alert(request.responseText);
}
});
I see a few things that could be throwing the error.
You are prepending the ajax url to post to with the variable host. It's not needed, you should try it this way:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {name:phone_number},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
As per Laravel documentation (https://laravel.com/docs/5.8/responses), you can return json responses like the below:
public function send_otp_function(Request $request)
{
$response = array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return response()->json($response);
}
You should be sending the csrf token with your post:
$('#send_otp_button').on('click', function(e) {
e.preventDefault();
var phone_number = $('#phone_number').val();
alert(phone_number);
$.ajax({
type: "POST",
url: "/send_otp", //remove the host variable here
data: {
_token: {{ csrf_token() }}, //csrf token
name:phone_number
},
success: function( msg ) {
alert( msg );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
HTML :
<!DOCTYPE html>
<html>
<head>
<title>Ajax Dynamic Dependent Dropdown in Laravel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
.box{
width:600px;
margin:0 auto;
border:1px solid #ccc;
}
</style>
</head>
<body>
<div id="first_step">
<div class="col-md-8">
<input type="text" autofocus id="phone_number" class="form-control" placeholder="Enter Phone Number" id="phone_number" name="phone_number" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-4">
</div>
<div class="col-md-8 " id="otp_input">
<input type="text" autofocus id="user_otp" class="form-control" placeholder="Enter OTP" name="otp" id="result" value="{{ old('phone_number') }}" />
</div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication1"> </div>
<div class="col-md-12" style="padding-bottom: 10px;" id="mobile_verfication">
<input type="button" class="log-teal-btn small" id="send_otp_button" value="Verify Phone Number"/>
</div>
</div>
{{ csrf_field() }}
</body>
</html>
<script>
$(document).ready(function(){
$('#send_otp_button').on('click', function(e) {
var select = $('#phone_number').val();
alert(select);
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, _token:_token},
success:function(result)
{
alert(result);
}
})
});
});
</script>
Web.php(Route File)
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/dynamic_dependent', 'DynamicDependent#index');
Route::post('dynamic_dependent/fetch', 'DynamicDependent#fetch')->name('dynamicdependent.fetch');
?>
//DynamicDepdendent.php (Controller)
<?php
//DynamicDepdendent.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$response = $request->get('select');
echo $response;
}
}
?>

Wiki API request not working

I used some sample code from the Wiki API docs but when I enter a search item, nothing happens. No errors in the console, just nothing. The URL itself works if I enter it into a browser so I think something with the code is not passing in the proper value. Is there an issue with how I'm calling the API? Below is the relevant code:
$(document).ready(function(){
$('#search-submit').click(function() {
getWiki($('#searchVal').val());
});
/*add code for get lucky function*/
});
function getWiki(searchParam) {
$.ajax( {
url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page='+searchParam+'&callback=?',
dataType: 'json',
type: 'POST',
headers: { 'Api-User-Agent': 'Example/1.0' },
success: function(data) {
var result = data;
pageTitle = result.title;
$(".search-box").html(pageTitle);
}
});
};
Here is the HTML:
<body>
<div class="container">
<div class="col-lg-12 header">
<h1>Search Wiki</h1>
</div>
<div class="row search-box">
<div class="col-lg-10">
<input placeholder=" Search" class="input" type="text" id="searchVal" name="searchVal"/></div>
<div class="col-lg-2"><button type="submit" id="search-submit" name="search-submit" class="btn-default">
<i class="fa fa-search fa-2x"></i>
</button></div>
</div>
<div class="row button-box text-center">
<div class="col-lg-12">
<button type="button" class="btn btn-primary" id="random">I'm Feeling Lucky</button></div>
</div>
</div>
</body>
The returned JSON has a parse property before the result, so it has to be data.parse.title to get the title etc.
$(document).ready(function() {
$('#search-submit').click(function() {
getWiki($('#searchVal').val());
});
/*add code for get lucky function*/
});
function getWiki(searchParam) {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=' + searchParam + '&callback=?',
dataType: 'json',
type: 'POST',
headers: {
'Api-User-Agent': 'Example/1.0'
},
success: function(data) {
var result = data.parse;
var pageTitle = result.title;
$(".search-box").html('The title is : ' + pageTitle);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Search for something : <input id="searchVal"><button id="search-submit">Search</button>
<br /><br /><br />
<div class="search-box"></div>

Laravel 5.2 : How to post and delete data Using Ajax?

I want to post some data using Ajax and I also want to delete some data using Ajax.
But the problem is while inputting the data, data posted in database. But My UI faces some problem, after saving the data, my save Button always clicked. But as I'm using Ajax, it shouldn't load or previous data should automatically vanish.
Same as for deleting also, while deleting data get deleted, but it's redirecting to another page?
How do I solve the problem?
Here is my UserController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Http\Response;
use App\User;
use App\Post;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller {
public function postSignUp(Request $request) {
$this->validate($request, [
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'password' => 'required|min:4'
]);
$user = new User();
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
if ($request->ajax()) {
return response()->json();
}
}
public function delete(Request $request, $id) {
$user = User::find($id);
$user->delete($request->all());
}
}
?>
Here is my Post data View page:
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity = "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin = "anonymous">
</head>
<body>
<script src = "https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div class="container">
<h2>Register Form</h2>
<div class="row col-lg-5">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="Email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="send(event)" class="btn btn-default" >Submit</button>
</div>
</div>
<script type="text/javascript">
function send(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "{{route('signup')}}",
data: {name: $("#name").val(),
email: $("#email").val(),
password: $("#password").val(),
_token: '{!! csrf_token() !!}'
}
});
}
</script>
</body>
</html>
Here is my delete data view page:
<html>
<head>
<title> User Details </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container">
<h3> User Details </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>User Name</td>
<td>User Email</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach($user as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->email}}</td>
<td>
Edit
<div id="deleteTheProduct">
{!! Form::open([
'method' => 'POST',
'action' => ['UserController#delete',$row->id],
'style'=>'display:inline'
]) !!}
{!! Form::hidden('id',$row->id)!!}
{!! Form::submit('Delete',['class'=>'btn btn-danger deleteUser','id' => 'btnDeleteUser', 'data-id' => $row->id]) !!}
{!!Form::close()!!}
</div>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$('.deleteUser').on('click', function (e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url(' / delete') }}'
+ '/' + dataId,
method: 'POST',
data: inputData,
success: function (data) {
console.log(data);
}
});
});
</script>
</body>
</html>
to prevent redirect problem just make .delete button as button not submit, I think this will fix your problem, if not please inform me,
to delete row please make following changes on your script code... first is yours code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
}
});
});
have some changes in above code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
// added code is
$object=$(this);
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
//if success status is successful and below code removes the parent row from the table
$($object).parents('tr').remove();
}
});
});
But as I'm using Ajax, it shouldn't load or previous data should automatically vanish
You will have to control that yourself, ajax is like a request to web server without reloading the page (or navigating) but the browser doesn't know what action to make after the ajax request. as you are using jQuery you can update your UI after Ajax request in success callback.
try for example returning the id of deleted object and in ajax success function.
success: function(data) {
jQuery('#'+data.id).remove();
}

AngularJS move part of Controller to Service

Consider the following code.
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/overlay-control.css" rel="stylesheet">
<link href="/css/list-control.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--<script src="/js/Services/UserService.js"></script>-->
<script src="/js/Controllers/MainController.js"></script>
<!--<script src="/js/Controllers/UserController.js"></script>-->
<script src="/js/bootstrap.min.js"></script>
</head>
<body ng-controller="MainController as myControl">
<div id="overlaycover" ng-click="myControl.showUpd(0)"></div>
<div id="overlaybox">
<div class="col-md-12">
<h4>Update:</h4>
<form ng-submit="myControl.updTodo()">
<div class="form-group">
<label for="updContent">Note:</label>
<textarea rows="5" cols="30" class="form-control" id="updContent" name="updContent" ng-model="noteupd.content"></textarea>
</div>
<div class="form-group">
<label for="updDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" class="form-control" id="updDeadline" name="updDeadline" ng-model="noteupd.deadline" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="updCompleted" name="updCompleted" ng-model="noteupd.completed" /> - Completed
</label>
</div>
<div class="form-group">
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<button type="submit" class="btn btn-info">Update</button>
</div>
</form>
Click utside the square to close.
</div>
</div>
<div class="container">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="listDiv">
<h1>Todo-list:</h1>
<p>
<img src="/images/legend-normal.png"> - Unfinished 
<img src="/images/legend-completed.png"> - Finished 
<img src="/images/legend-late.png"> - Late
</p>
<table class="table" id="list-table">
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
<th colspan="2">Modify:</th>
</tr>
<tr ng-repeat="todo in myControl.todos" ng-class="rowClass(todo.completed, todo.deadline)">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button type="button" class="btn btn-info" ng-click="myControl.showUpd(todo.id)">Update</button></td>
<td><button type="button" class="btn btn-danger" ng-click="myControl.delTodo(todo.id)">Delete</button></td>
</tr>
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="formDiv">
<h3>Add new note:</h3>
<form ng-submit="myControl.addTodo()">
<div class="form-group">
<label for="newUser">User:</label>
<select ng-model="noteadd.user" class="form-control" id="newUser" name="newUser">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newProject">Project:</label>
<select ng-model="noteadd.project" class="form-control" id="newProject" name="newProject">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newContent">Note:</label>
<textarea rows="5" cols="30" ng-model="noteadd.content" class="form-control" id="newContent" name="newContent"></textarea><br/>
</div>
<div class="form-group">
<label for="newDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" ng-model="noteadd.deadline" class="form-control" id="newDeadline" name="newDeadline" /><br/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add</button>
</div>
</form>
</div>
</div>
</body>
</html>
AngularJS Controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$scope.noteadd = {};
var noteadd = $scope.noteadd;
$scope.noteupd = {};
var noteupd = $scope.noteupd;
// Get all notes:
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
// Get all users:
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
// Get all projects
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
// Add note to database
thisApp.addTodo = function(noteadd)
{
$http({
method : 'PUT',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteadd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
};
// Hide note by setting removed to 1
thisApp.delTodo = function(noteID)
{
var r = confirm("Are you sure?");
if (r == true) {
var noteObj = JSON.parse('{"id":' + noteID + '}'); // JSON for req
$http({
method : 'DELETE',
url : 'http://localhost:8000/notes',
data : $.param(noteObj),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't delete note. Please try again!");
});
}
};
// Show overlay with form for updating a note
thisApp.showUpd = function(noteID)
{
var overlaycover = document.getElementById("overlaycover");
var overlaybox = document.getElementById("overlaybox");
overlaycover.style.opacity = .65;
if(overlaycover.style.display == "block" || noteID == 0){ // For toggling overlay
overlaycover.style.display = "none"; // Hide div overlaycover
overlaybox.style.display = "none"; // Hide div overlaybox
} else {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
noteupd.content = response.data.content; // Update fields in form
noteupd.deadline = response.data.deadline;
noteupd.id = response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
overlaycover.style.display = "block"; // Show div overlaycover
overlaybox.style.display = "block"; // Show div overlaybox
}, function() {
alert("Error getting todo note");
});
}
}
// Update a note
thisApp.updTodo = function(noteupd)
{
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteupd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
}
// Check if deadline passed for each note in list
$scope.rowClass = function(completed, deadline)
{
var nowTime = Math.floor(Date.now()/1000);
var deadTime = new Date(deadline);
var deadUTC = Math.floor(deadTime/1000);
if (completed == 1) {
return "success"; // Note is completed
} else if (deadUTC < nowTime) {
return "danger"; // Note is not completed, deadline passed
} else {
return "active"; // Note is not completed, still time left
}
}
});
What I would like to do is to move all $http-calls to a service instead of having them in the controller like I have it now. I have searched the internet but I don't really understand the solutions i've found there.
Second, in several functions, as you can see, I use location.reload();. I would like to use ng-bind instead, but as the sam, I don't understand how this works.
Can someone please explain how I should do these two things?
Ok , let's for example create a Users factory and put all Users api related stuff inside:
'use strict';
angular
.module('todoApp')
.factory('Users', factory);
function factory($http) {
var service = {
get: get,
//edit: edit ...
};
return service;
function get() {
return $http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
return response.data;
});
}
//function edit(user) {
// return $http({method : 'PUT...
//}
}
What you have to do next is inject that factory wherever you want to call it.
So in your controller you essentially have to do this:
angular.module('todoApp', [])
.controller('MainController', function($scope, Users) {
//.....
function getUsers() {
Users.get().then(function(data){
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
}
getUsers();
//...
Repeat the same by creating the appropriate services for notes and projects.
To not bloat the main app.js move this services to seperate files, users.service.js etc..
I would also advise you to move the controllers to seperate files too.
Just be careful:
this is a module creation
angular.module('todoApp', [])
You create a module once.
to attach a service/factory/controller/anything, when you are in that separate file, to that module you use this:
angular.module('todoApp').anything
Second, I assume you use location.reload to update the view with the new data.
Let's say you edit/delete a User. Instead of reloading the page, call getUsers() in the then() of put/delete/create User.
Hope it makes sense to you!
PS: This styleguide by John Papas have been very helpful to me, I suggest you give it a read !
I've already used service factory solution for such kind of problem.
angular.module('data-service').factory('dataService', ['$http',function ($http) {
var url = 'http://localhost:8000/';
return {
getData: function(type) {
return $http({method : 'GET', url : url + type});
},
allData: function() {
return $q.all({
notes: this.getData('notes'),
users: this.getData('users'),
projects: this.getData('projects')
});
}
}
}]);
usage:
dataService.getData('notes').then(function (data) { ... });
also you can use angular promise $q.
dataService.allData().then(function(data) { /* data.notes, data.users, data.projects */ }

ReferenceError: insertRecord is not defined

I have this html code that's supposed to retrieve a local json file and have it parse and stringify to the local storage. I wanted to test the code, but when I fill out the form and run it, it says ReferenceError: insertRecord is not defined in Firefox console.
Any help would be very much appreciated.
Thank you.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Register</title>
<link href="css/navigation.css" rel="stylesheet" type="text/css">
<link href="css/body.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
<script src="store.js" type="text/javascript"></script>
<script type="text/javascript">
var i;
var user;
var txt;
$(document).ready(function () {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: getUser,
error: function() {alert("retrieval error"); }
});
});
function getUser(data) {
if (localStorage) {
if (!localStorage.getItem('user')) {
user = JSON.parse(data.User);
localStorage.setItem('user', user);
}
else {
String item = localStorage.getItem('user');
user = JSON.parse(item);
}
}
else
alert("Local Storage not supported");
}
function insertRecord() {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: insertUser,
error: function(){ alert("retrieval error"); }
});
function insertUser() {
txt = { firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
userName: document.getElementById("userName").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value
};
localStorage.setItem('user', user + JSON.stringify(txt));
}
}
</script>
</head>
<body>
<img src="images/Dance etc logo LARGE.jpg" width="263" height="150" alt="Dance Etc Logo" />
<hr />
<div data-role="header">
<h1>Dance Etc.</h1>
</div>
<div data-role="content" >
<h1>Register</h1>
<form method="post" action="" id="register" name="form">
<label>First Name: </label>
<input type="text" id="firstName" /><br />
<label>Last Name: </label>
<input type="text" id="lastName" /><br />
<label>Username: </label>
<input type="text" id="userName" /><br />
<label>Email: </label>
<input type="text" id="email" /><br />
<label>Password: </label>
<input type="password" id="password" /><br />
<input type="submit" value="Register" onClick="insertRecord()" />
</form>
</div>
<div data-role="footer">
Contact Us
Policy
History
</div>
In your code you have the following line:
String item = localStorage.getItem('user');
This isn't valid JavaScript and is therefore throwing a SyntaxError: Unexpected identifier, preventing the rest of your JavaScript code from being evaluated.
However, as you try to attach insertRecord inline in the HTML, it tries to run when triggered, but can't invoke code that didn't get evaluated.
You should consider attaching event listeners using element.addEventListener.
Additionally, indenting your code may help you debug, too.
var i, user, txt;
$(document).ready(function () {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: getUser,
error: function () {
alert("retrieval error");
}
});
});
function getUser(data) {
if (localStorage) {
if (!localStorage.getItem('user')) {
user = JSON.parse(data.User);
localStorage.setItem('user', user);
} else {
item = localStorage.getItem('user');
user = JSON.parse(item);
}
} else
alert("Local Storage not supported");
}
function insertRecord() {
$.ajax({
type: "GET",
url: "studio.json",
dataType: "json",
success: insertUser,
error: function () {
alert("retrieval error");
}
});
function insertUser() {
txt = {
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
userName: document.getElementById("userName").value,
email: document.getElementById("email").value,
password: document.getElementById("password").value
};
localStorage.setItem('user', user + JSON.stringify(txt));
}
}

Categories

Resources