AngularJS - Multiple StateParems - json

We are still picking up and learning AngularJS but can't seem to figure this issue out, we want to be able to select a product type and use the formData value ("productType":"1") image1 to display the correct JSON product data related to this ID image2.
These are our controllers below within app.js, we have tried using multiple $stateParems but cant get seem to get the producttype id working with the stateParems.
Each productType ID is related to its own JSONstub, this is what we are using currently but this only grabs the jobID and not the producttype id below.
$scope.productid = $stateParams.jobID[0];
url: 'http://jsonstub.com/producttype/' + $scope.productid,
Here is our Plnkr, to find the Product Type section Click 'Login' > 'CHD24 - 26384108' 'View' > Next.
If anyone could advice and point us in the right direction this would help massively, also as we are new to AngularJS if you see anything else that we are doing wrongly please point it out.
Thank you.
// Product Type
.controller('warrantyCtrl', function($scope, $http, $stateParams) {
$scope.params = $stateParams.jobID[0];
$scope.dataLoaded = false;
$http({
url: 'http://jsonstub.com/warranty/' + $scope.params,
method: 'GET',
dataType: 'json',
data: '',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://run.plnkr.co',
'JsonStub-User-Key': '1357f082-ea56-46f0-adc5-3e5c273f6f87',
'JsonStub-Project-Key': 'e4f971a2-db30-45a0-80f9-bfa41b922c64'
}
}).success(function(data, status, headers, config) {
$scope.warrantydata = data;
$scope.dataLoaded = true;
}).error(function(data, status, error, config) {
$scope.warrantydata = [{
heading: "Error",
description: "Could not load json data"
}];
$scope.dataLoaded = false;
});
$scope.formData = {
'jobID': $scope.params
};
// Product Type Select
$scope.products = [{
id: '1',
name: 'Petrol Lawnmower'
}, {
id: '2',
name: 'Electric Lawnmower'
}, {
id: '3',
name: 'Petrol Chainsaw'
}, {
id: '4',
name: 'Electric Chainsaw'
}, {
id: '5',
name: 'Petrol Timmer'
}, {
id: '6',
name: 'Electric Timmer'
}, {
id: '7',
name: 'Etc'
}];
})
// Product Data
.controller('warrantyFormProductType', function($scope, $http, $stateParams) {
$scope.productid = $stateParams.jobID[0];
$http({
url: 'http://jsonstub.com/producttype/' + $scope.productid, // This needs to be productType id
method: 'GET',
dataType: 'json',
data: '',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://run.plnkr.co',
'JsonStub-User-Key': '1357f082-ea56-46f0-adc5-3e5c273f6f87',
'JsonStub-Project-Key': 'e4f971a2-db30-45a0-80f9-bfa41b922c64'
}
}).success(function(data, status, headers, config) {
$scope.productdata = data;
}).error(function(data, status, error, config) {
$scope.productdata = [{
heading: "Error",
description: "Could not load json data"
}];
})
// Add / Remove Columns (Still working on)
$scope.removeRow = function(index) {
$scope.productdata.splice(index, 1);
if ($scope.productdata.length() === 0) {
$scope.productdata = [];
}
};
$scope.addRow = function() {
var newrow = [];
if ($scope.productdata.length === 0) {
newrow = [{
'en': ''
}];
} else {
$scope.productdata[0].forEach(function(row) {
newrow.push({
'en': ''
});
});
}
$scope.productdata.push(newrow);
};
});

Is your API request supposed to be like this http://jsonstub.com/2/1 ?
Assuming yes, I've updated the code here
But I am getting Error 400 for this request.
Take a look and comment if this is what you needed.

Related

no display fail message from controller

I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});

How to fetch particular data in column from JSON with keys

I am not sure how to fetch particular data in column from JSON with the help of keys. From ajax request i am getting data from the server but i want to store it in sqlite as the columns in server
$("#xxx").click(function()
{
var e = $("#mob").val();
var p = $("#key").val();
myDB.transaction(function(transaction)
{
transaction.executeSql('CREATE TABLE IF NOT EXISTS User_data (data)', [],
function(tx, result)
{
navigator.notification.alert("table created");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
$.ajax
({
url: "http://192.168.1.4/sms/android.php",
type: "GET",
datatype: "json",
data: { type:'login', phone: e, name: p },
ContentType: "application/json",
success: function(response)
{
var valuesInArray = JSON.stringify(response);
var user_data = JSON.parse(valuesInArray);
for(var item in user_data.Users)
{
myDB.transaction(function(transaction)
{
transaction.executeSql('INSERT INTO User_data (id,date_closed) VALUES (item.id,item.date_closed)', [],
function(tx, result)
{
navigator.notification.alert("data inserted");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
}
},
error: function(e)
{
alert('Got ERROR: ' + JSON.stringify(e));
}
});
});
here is the image of the data i am getting from the server
DATA IN ALERT BOX
here, i want to fetch each column in the database.
Thankx in advance.
<?php
header('Access-Control-Allow-Origin:*');
pg_connect("host=localhost port=5432 dbname=** user=** password=***");
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$mobile = $_GET['phone'];
$key = $_GET['name'];
$query = "select * from crm_lead where phone='$mobile' and id='$key'";
$result = pg_query($query);
while($myrow = pg_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('Users' => $recipes));
echo "'".$output."';";
}
}
else
{
echo "invalid";
}
pg_close();
?>
Why can't you use the response object directly since it's already a Json object?
var users = response.Users;
for(var i=0; i < users.length;i++)
{
var id = users[i].id;
//do something with id
}
$.ajax
({
url: "http://182.70.240.81:82/sms/android.php",
type: "GET",
datatype: "json",
data: { type: 'login', phone: 9770869868, name: 14 },
ContentType: "application/json",
success: function (response) {
var simpleJson = JSON.parse(response);
var shortName = 'db_test';
var version = '1.0';
var displayName = 'Test Information';
var maxSize = 65536; // in bytes
var db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(function (txe) {
txe.executeSql('DROP TABLE User_data');
txe.executeSql('CREATE TABLE User_data(id INTEGER,date_closed TEXT)');
db.transaction(function (txe1) {
for (var i = 0; i < simpleJson.Users.length; i++) {
txe1.executeSql('INSERT INTO User_data (id,date_closed) VALUES (' + simpleJson.Users[i].id + ',"' + simpleJson.Users[i].date_closed + '")', [],
function (tx, result) {
alert("data inserted");
},
function (error) {
alert("error, table exists");
});
}
});
});
}
});
Remove Single Qoutaion from your json:

why it's appending #/... in location.hash

I am using angular js for my app.
Here , My Angular code as :
var app = angular.module('TaskManager', ['ngCookies']);
app.controller('LoginController', function($scope, $http, $location, $cookieStore) {
$scope.login = function(str) {
console.log(".......... login called......");
$http({
method: 'POST',
url: '../TaskManager/public/user/login',
data: $.param({
email: email.value,
password: password.value
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
var result = data.response;
console.log(result);
if (result == "success") {
//storing value at cookieStore
$cookieStore.put("loggedin", "true");
$cookieStore.put("loggedUserId", data.user_id);
$cookieStore.put("password", data.password);
$cookieStore.put("type", data.type);
$cookieStore.put("email", data.email);
location.href='Dashboard.html';
} else alert(data.message);
});
});
app.controller('DashboardController', function($scope, $http, $location, $cookieStore) {
$scope.users = [];
$http({
method: 'POST',
url: '../TaskManager/public/task/tasklist',
data: $.param({
logged_userid: userId,
password: password,
status: 'All',
user_id: useridToFetch
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
$scope.users = data.users;
});
//location.hash="";
console.log(window.location);
});
It works fine but when it redirects to the dashboard page after logged in, the location.hash is being assigned with the #/PAGE_NAME. it becomes location.hash=#/PAGE_NAMEwhich results the URL value repetition.
Like:
http://localhost:8085/NovaTaskManager/Dashboard.html#/Dashboard.html
I tried to clear hash at DashboardController, Which clears for a while but as soon as the page is refreshed the earlier URL appears again.
Don't know:
1. why location.hash is getting assigned by default ?
2. How it can be resolved ?
Any suggestion would be appreciated.

How do you mock MySQL (with node-orm2) in Node.js/Express?

I am using node.js/express with https://github.com/dresende/node-orm2 to use my MySQL database.
I am new to the node.js world and I am quite stuck so far, I don't know how to unit test (not integration test) a simple function.
Here is my server.js, loading my user model (ORM)
var express = require('express'),
orm = require('orm'),
config = require('./config/config.js'),
auth = require('./services/authentication'),
helper = require('./middlewares/helper.js'),
friends = require('./modules/friends.js');
var app = express();
app.use(orm.express('mysql://' + config.mysql.username + ':' + config.mysql.pwd + '#' + config.mysql.host + ':' + config.mysql.port + '/' + config.mysql.db, {
define: function(db, models, next) {
db.load("./models/models.js", function(err) { // loaded!
models.user = db.models.user;
});
}
}));
var middlewares = [auth.authenticate, helper.retrieveUser];
app.get('/friends', middlewares, friends.findActiveFriends);
app.listen(3000);
console.log('Listening on port 3000...');
here is the user model :
module.exports = function (db, cb) {
var User = db.define('user', {
uid : { type: 'number', rational: false, unique: true, required: true },
first_name : { type: 'text', size: 100, required: true },
last_name : { type: 'text', size: 100, required: true },
picture : { type: 'text', size: 255, required: false },
email : { type: 'text', size: 255, required: true },
creation_date : { type: 'date', time: true },
modification_date : { type: 'date', time: true }
}, {
methods: {
fullName: function () {
return this.first_name + ' ' + this.last_name;
}
},
hooks: {
beforeCreate: function (next) {
if (this.creation_date == undefined) {
this.creation_date = new Date();
}
if (this.modification_date == undefined) {
this.modification_date = new Date();
}
return next();
}
}
});
// CUSTOM FUNCTIONS
User.getByUid = function(uid, callback) {
this.find({ uid: uid }, function(err, users) {
if(err) callback(err);
if (users.length == 1) {
callback(null, users[0]);
} else {
callback('No user found with uid=' + uid);
}
});
};
User.hasMany("friends", User, {
status: { type: 'enum', values: ['pending', 'refused', 'active'] }
}, {
reverse: 'friendsrev', mergeId: 'user_id', mergeAssocId: 'friend_id'
});
return cb();
};
and here is my methods to find active friends in friends.js:
var _findActiveFriends = function(req, res) {
req.currentUser.getFriends({
status: 'active'
}, function(err, friends) {
if (err) throw err;
res.send(JSON.stringify(friends));
});
};
I would like to know how can I write a simple test (with mocha and sinon.js ?) by mocking the database connection and the request also. I need to mock the value of req.currentUser which is a user returned by the ORM in a middleware.
I just want to run unit tests and do not use a real DB or make some HTTP calls.
thanks for your help.
If you want to mock the req using sinon.js, you can do something like the following.
var sinon = require('sinon');
var friend = require('./friend');
it('some test', function(done) {
var req = {
currentUser: {
// Add all the properties/functions that you are concerned with here.
// and you can/should wrap them around sinon.spy().
// If you are not concerned with that function (i.e. you are not using it)
// then you can simply use sinon.stub() to return a stub function.
}
};
var res = {
send: sinon.spy(function(obj) {
assert.ok(obj); // yes object exists
done(); // end of test
};
};
var next = function() {};
friend.findActiveFriend(req, res, next);
});
This way you shouldn't be connecting to the model, which tests friend.js only.
Also, since I just noticed you are using orm.express, you may also want to simply mock req.models with the stubbed function you desire as above.

How do get jquery fullcalendar to pass additional parameters to my json feed script

My code is as follows
jQuery('#calendar').fullCalendar({
weekMode: 'liquid',
events: themeforce.events,
eventRender: function (event, element) {
element.find('span.fc-event-title').html(element.find('span.fc-event-title').text());
}
});
where themeforce.events is a variable containing an encoded url of the json feed a php file - all works well.
I tried replacing events: themeforce.events, with
events: {
url: themeforce.events,
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
However now the calendar fails to load.
What can I do?
I wanted the start and end times for a post ajax request and it took me a bit of time to work it out.
This might help you:
events: function(start, end, timezone, callback) {
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: {
start: start.format(),
end: end.format(),
custom_param1: 'value 1',
custom_param2: 'value 2',
},
error: function () {
alert('there was an error while fetching events!');
},
success: function(doc) {
var events = [];
$.each(doc,function (index, e) {
events.push(e);
});
callback(events);
}
});
}
You should use extraParams as explained in doc : https://fullcalendar.io/docs/events-json-feed
var calendar = new Calendar(calendarEl, {
eventSources: [
// your event source
{
url: '/myfeed.php',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
Also be sure your feed's url return raw json data array !
Just put "data" instead of "extraParams" in "events"
events: {
url: 'service.php',
method: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
}