Angular js-Web page freezes after form submitted - html

This is a project I'm doing to learn Angular JS. It's a single page web application that allows to log contacts and edit them. For some reason that I can't figure out, my web page freezes any time I post data to Firebase. Can anyone help with this?
This my javascript file
'use strict';
angular.module('myContacts.contacts', ['ngRoute','firebase'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contacts', {
templateUrl: 'contacts/contacts.html',
controller: 'contactsCtrl'
});
}])
.controller('contactsCtrl', ['$scope','$firebaseArray', function($scope, $firebaseArray) {
var ref = firebase.database().ref();
$scope.contacts = $firebaseArray(ref);
//console.log($scope.contacts);
$scope.showAddForm = function(){
$scope.addFormShow = true;
}
$scope.hide = function(){
$scope.addFormShow = false;
}
$scope.addFormSubmit = function(){
console.log('adding contact');
//Assign values
if($scope.name){var name = $scope.name}else {name=null;}
if($scope.email){var email = $scope.email}else {email=null;}
if($scope.company){var company = $scope.company}else {company=null;}
if($scope.mobile_phone){var mobile_phone = $scope.mobile_phone}else { mobile_phone=null;}
if($scope.home_phone){var home_phone = $scope.home_phone}else {home_phone=null;}
if($scope.work_phone){var work_phone = $scope.work_phone}else {work_phone=null;}
if($scope.street_address){var street_address = $scope.street_address}else {street_address=null;}
if($scope.city){var city = $scope.city}else {city=null;}
if($scope.province){var province = $scope.province}else {province=null;}
if($scope.postal_code){var postal_code = $scope.postal_code}else {postal_code=null;}
//Build Object
$scope.contacts.$add({
name:name,
email:email,
company:company,
phone:[
{
mobile:mobile_phone,
home:home_phone,
work:work_phone
}
],
address:[
{
street_address:street_address,
city: city,
province: province,
postal_code: postal_code
}
]
}).then(function(ref){
var id = ref.key();
console.log('added contact with id: '+ id);
//clear form
clearFields();
hide form
$scope.addFormShow = false;
//send message
$scope.msg ="contact Added";
});
}
//Clear $scope Fields
function clearFields(){
console.log('Clearing All Fields');
$scope.name = '';
$scope.email = '';
$scope.company = '';
$scope.mobile_phone = '';
$scope.home_phone = '';
$scope.work_phone = '';
$scope.street_address = '';
$scope.city = '';
$scope.province = '';
$scope.postal_code = '';
}
}]);
and here is the HTML file
<div class="row" ng-controller="contactsCtrl">
<div class="large-10 columns">
<!--<div data-alert ng-show="msg" class="alert-box">{{msg}}</div>-->
<form ng-submit="addFormSubmit()" ng-show="addFormShow">
<h3>Add Contact</h3>
<!--Add Form-->
<div class="row">
<div class="large-6 columns">
<label>Name:
<input type="text" ng-model="name" placeholder="Contact Name" required/>
</label>
</div>
<div class="large-6 columns">
<label>Email:
<input type="text" ng-model="email" placeholder="Contact Email" required/>
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Company:
<input type="text" ng-model="company" placeholder="Company Name"/>
</label>
</div>
<div class="large-6 columns">
<label>Work Phone:
<input type="text" ng-model="work_phone" placeholder="Work Phone"/>
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Mobile Phone:
<input type="text" ng-model="mobile_phone" placeholder="Mobile Phone" />
</label>
</div>
<div class="large-6 columns">
<label>Home Phone:
<input type="text" ng-model="home_phone" placeholder="Mobile Phone"/>
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Street Address:
<input type="text" ng-model="street_address" placeholder="Street Name"/>
</label>
</div>
<div class="large-6 columns">
<label>City:
<input type="text" ng-model="city" placeholder="City"/>
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Province:
<input type="text" ng-model="state" placeholder="Province"/>
</label>
</div>
<div class="large-6 columns">
<label>Postal Code:
<input type="text" ng-model="postal_code" placeholder="Postal Code"/>
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" value="Add Contact" class="button"/>
</div>
</div>
</form>
<h3>Your Contacts (3)</h3>
<table>
<thead>
<tr>
<th width="200px">Name</th>
<th width="200px">Company</th>
<th width="25%">Email</th>
<th width="25%">Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{contact.name}}</td>
<td>{{contact.company}}</td>
<td>{{contact.email}}</td>
<td><a class="button tiny" ng-click="showEditForm(contact)">Edit</a><a class="button tiny alert" ng-click="removeContact(contact)">Delete</a></td>
</tr>
</tbody>
</table>
</div>
<div class="small-12 large-2 columns">
<a class="button large" ng-click="showAddForm()" ng-hide="addFormShow">+</a>
<a class="button large" ng-click="hide()" ng-show="addFormShow">-</a>
</div>
</div>

While checking your code I have the feeling that you are probably not initializing the firebase module.
So you should do it first
Config firebase.initializeApp() or it will not work
.config(function () {
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
});
Check this example, please use your own firebase initialization info to make it work I made your code work on muy test.
Example: https://jsfiddle.net/moplin/zLozccap/

Related

Can't get value from form in AngularJS

I tried this student manager in HTML+ java last time. So now I want to try in angularJS. When I finished my code, it doesn't seem to work.
There are no error in console so I don't know where I went wrong. Can someone help me to figure out what the error is here?
HTML
<div ng-controll="MyController">
<form role="form" ng-submit="saveStudent()">
<div class="form-group mt-2">
<label for="" class="form-label">Student Name: </label>
<input type="text" required placeholder="Enter student name" class="form-control" ng-model="name">
</div>
<div class="form-group mt-2">
<label for="" class="form-label">Student DOB: </label>
<input type="date" placeholder="mm/dd/yyyy" class="form-control" ng-model="birth">
</div>
<div class="form-group mt-2">
<label for="" class="form-label">Student Gender: </label>
<input type="radio" name="sex" value="male" ng-model="sex" id="male">
<label for="male">Male</label>
<input type="radio" name="sex" value="female" ng-model="sex" id="female">
<label for="female">Female</label>
</div>
<div class="form-group mt-2">
<label for="" class="form-label">Student Language: </label>
<label for="" ng-repeat="language in languagesList">
<input type="checkbox" value="{{language.name}}" ng-checked="checkboxModel.indexOf(language) > -1" ng-click="addLanguage(language)">{{language}}
</label>
</div>
<div class="form-group mt-2">
<label for="">Student Class: </label>
<select name="student_class" class="form-control" ng-model="studentclass">
<option value="">---Select---</option>
<option value="{{ item }}" ng-repeat="item in classList">{{ item }}</option>
</select>
</div>
<div class="form-group mt-2 pb-3">
<button class="btn btn-danger" type="submit">Add</button>
</div>
</form>
<br><br><br>
<div class="card-table " style="margin-top: 20px;">
<h2 style="text-align: center;">Student List</h2>
<div class="content">
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>DOB</th>
<th>Gender</th>
<th>Language</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in studentList track by $index">
<td>{{ item.name }}</td>
<td>{{ item.studentclass }}</td>
<td>{{ item.birth | date}}</td>
<td>{{ item.sex }}</td>
<td>
<div ng-repeat="checkbox in item.checkboxModel">
{{ checkbox }}
</div>
</td>
<td>
<a href="#" class="btn btn-danger" ng-click="removeStudent($index)" style="color: blue;">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Angular JS
var app = angular.module('MyApp', []);
app.controller('MyController', ['$scope', function ($scope) {
$scope.studentList = [];
$scope.classList = ['C2108G1',
'C2108G2',
'C2108G3',
'C2108G4',
'C2108G5',
'C2108L'
];
$scope.languagesList = [
'English',
'Vietnamese',
'Japanese',
'Chinese',
'French'
];
$scope.checkboxModel = [];
$scope.addLanguage = function (language) {
var index = $scope.checkboxModel.indexOf(language);
if (index > -1) {
$scope.checkboxModel.splice(index, 1);
} else {
$scope.checkboxModel.push(language);
}
}
$scope.saveStudent = function () {
var item = {
'name': $scope.name,
'birth': $scope.birth,
'sex': $scope.sex,
'studentclass': $scope.studentclass,
'checkboxModel': $scope.checkboxModel,
}
if ($scope.currentIndex >= 0) {
$scope.studentList[$scope.currentIndex] = item;
$scope.currentIndex = -1;
} else {
$scope.studentList.push(item);
}
}
$scope.currentIndex = -1;
$scope.removeStudent = function (index) {
var option = confirm('Are you sure you want to remove this student?');
if (!option) return;
$scope.studentList.splice(index, 1);
}
}]);

How to get data from two tables using Angular and displaying them in HTML?

I want to display two columns from two different tables.
I have table "offices" and "cash_desks"
Table "offices" have the column "name" which I want to display.
Table "cash_desks" have the columns "name" and "office_id"(which refers to offices id).
I want to display offices name and cash_desks name in HTML table.
Here is my HTML code:
<table class="table">
<tr ng-repeat="cash_desks in items" ng-click="editItem(cash_desks)">
<td>{{cash_desks.name}}</td>
<td>{{offices.name}}</td>
</tr>
</table>
<label><input type="checkbox" ng-model="myVar">Редактирай офис</label>
<div ng-show="myVar">
<div class="form">
<form ng-submit="saveItem(cash_desksForm.$valid)" name="cash_desksForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="offices_name">Код на валута</label>
<input type="text" class="form-control" required ng-model="activeItem.name" placeholder="Офис.." />
</div>
<div class="form-group">
<label for="value_name">Локация на офис</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.location" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="cash_desksForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
</div>
</div>
And Angular Code:
app.controller("CashDesksCtrl", function($rootScope, $scope){
$scope.items = [];
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh = function () {
$scope.items = [];
window.defaultAdapter.query("SELECT offices.name,cash_desks.name FROM offices LEFT JOIN cash_desks ON offices.id = cash_desks.office_id LIMIT 8", { type: Sequelize.QueryTypes.SELECT})
.then(cash_desks => {
$scope.items = cash_desks;
$scope.$apply();
})
};
You have same key (name) from your select , try to use alias to make them differents.
<table class="table">
<tr ng-repeat="itemin items" ng-click="editItem(cash_desks)">
<td>{{item.cash_desk_name}}</td>
<td>{{item.office_name}}</td>
</tr>
</table>
<label><input type="checkbox" ng-model="myVar">Редактирай офис</label>
<div ng-show="myVar">
<div class="form">
<form ng-submit="saveItem(cash_desksForm.$valid)" name="cash_desksForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="offices_name">Код на валута</label>
<input type="text" class="form-control" required ng-model="activeItem.name" placeholder="Офис.." />
</div>
<div class="form-group">
<label for="value_name">Локация на офис</label>
<input type="text" class="form-control" id="password" ng-model="activeItem.location" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="cash_desksForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
</div>
</div>
app.controller("CashDesksCtrl", function($rootScope, $scope){
$scope.items = [];
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh = function () {
$scope.items = [];
window.defaultAdapter.query("SELECT offices.name as office_name,cash_desks.name as cash_desk_name FROM offices LEFT JOIN cash_desks ON offices.id = cash_desks.office_id LIMIT 8", { type: Sequelize.QueryTypes.SELECT})
.then(cash_desks => {
$scope.items = cash_desks;
$scope.$apply();
})
};

property 'name' does not exist on type 'FormComponent'

Here is the error Message:
WARNING in Invalid background value at 160:282. Ignoring.
WARNING in Invalid background value at 184:60084. Ignoring.
ERROR in src/app/form/form.component.html(14,48): : Property 'name' does not exist on type 'FormComponent'.
src/app/form/form.component.html(27,69): : Property 'homePhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(32,67): : Property 'cellPhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(37,71): : Property 'officePhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(168,21): : Property 'homePhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(169,21): : Property 'cellPhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(170,21): : Property 'officePhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(189,11): : Property 'NaN' does not exist on type 'FormComponent'.
src/app/form/form.component.html(14,48): : Property 'name' does not exist on type 'FormComponent'.
src/app/form/form.component.html(27,69): : Property 'homePhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(32,67): : Property 'cellPhone' does not exist on type 'FormComponent'.
src/app/form/form.component.html(37,71): : Property 'officePhone' does not exist on type 'FormComponent'.
Here is my form.component.html
<div [hidden]="submitted" >
<form #calculatingForm="ngForm" (ngSubmit)="onSubmit(calculatingForm)" class="ui big form">
<h2 class="ui dividing header">ProShine Quote Calculator</h2>
<div class="spacer30"></div>
<div class="ui grid">
<div class="row">
<div class="eight wide column">
<div class="required field">
<label for="name">Client Name</label>
<input type="text" name="name" [(ngModel)]="name" #client="ngModel" required autofocus>
<div [hidden]="client.valid || client.pristine" class="ui negative message">
<div class="header">
No Client Name Entered
</div>
<p>Please Enter A Name
</p>
</div>
</div>
<div class="field">
<label for="homePhone">Home Phone</label>
<input type="tel" name="homePhone" id="homePhone" [(ngModel)]="homePhone" placeholder="(123) 456-7890"
[textMask]="{mask: mask}">
</div>
<div class="field">
<label for="cellPhone">Cell Phone</label>
<input type="tel" name="cellPhone" id="cellPhone" [(ngModel)]="cellPhone" placeholder="(123) 456-7890"
[textMask]="{mask: mask}">
</div>
<div class="field">
<label for="officePhone">Office Phone</label>
<input type="tel" name="officePhone" id="officePhone" [(ngModel)]="officePhone" placeholder="(123) 456-7890"
[textMask]="{mask: mask}">
</div>
</div>
<div class="eight wide column">
<div class="required field">
<label for="totalPanes">Total Number of Panes</label>
<input type="number" name="totalPanes" id="totalPanes" [(ngModel)]="totalPanes" #panes="ngModel" required>
<div [hidden]="panes.valid || panes.pristine" class="ui negative message">
<div class="header">
You Didn't Enter A Number
</div>
<p>Please Enter the Number of Panes
</p>
</div>
</div>
<div class="field">
<label for="floorPanes">Number of Floor Panes</label>
<input type="number" name="floorPanes" id="floorPanes" [(ngModel)]="floorPanes">
</div>
<div class="field">
<label for="outsideLadderPanes">Number of Outside Ladder Panes</label>
<input type="number" name="outsideLadderPanes" id="outsideLadderPanes" [(ngModel)]="outsideLadderPanes">
</div>
<div class="field">
<label for="ladderPanesInAndOut">Number of Indoor AND Outdoor Ladder Panes</label>
<input type="number" name="ladderPanesInAndOut" id="ladderPanesInAndOut" [(ngModel)]="ladderPanesInAndOut">
</div>
</div>
</div> <!--End of row-->
<div class="spacer30"></div>
<div class="three column row">
<div class="four wide column"></div>
<div class="eight wide column">
<div class="required field">
<label for="currentUser">Created By</label>
<select name="currentUser" id="currentUser" class="ui fluid dropdown " [(ngModel)]="currentUser" required>
<option value="">-- Select --</option>
<option value="Jason Walle">Jason Walle</option>
<option value="Aubree Walle">Aubree Walle</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="column">
<h2 class="ui dividing header">Additional Options</h2>
<!-- <div class="spacer30"></div> -->
</div>
</div>
<div class="row">
<div class="eight wide column">
<div class="field">
<label for="referral">Referral By</label>
<input type="text" name="referral" id="referral" [(ngModel)]="referral" >
</div>
</div>
<div class="three wide column">
<div class="field">
<label for="clientDiscount">Discount</label>
<input type="text" name="clientDiscount" id="clientDiscount" [(ngModel)]="clientDiscount" >
</div>
</div>
</div>
<div class="row">
<div class="eight wide column"></div>
<div class="three wide column">
<div class="field">
<label for="discountType">Discount Type</label>
<select name="discountType" id="discountType" class="ui fluid dropdown " [(ngModel)]="discountType" required>
<option value="">-- Select --</option>
<option value="Percentage">Percentage(%)</option>
<option value="Dollars">Dollars($)</option>
</select>
</div>
</div>
</div>
</div>
<div class="spacer50"></div>
<button type="submit" class="ui blue button">Calculate</button>
<button type="button" class="ui olive button" (click)="calculatingForm.reset()">New Client</button>
<div class="spacer75"></div>
</form>
</div>
<div [hidden]="!submitted" class="results-div">
<button (click)="goBack()" class="ui blue button"> <i class="arrow alternate circle left outline icon"></i> Go Back</button>
<!-- ============ PDF Generating Section ============= -->
<div id="content">
<div class="ui grid">
<div class="three column row">
<div class="column"></div>
<div class="column">
<img src="./../../assets/proshine-card.jpg" alt="" class="proshine-logo">
</div>
<div class="column"></div>
</div>
</div>
<div class="spacer50"></div>
<div class="ui grid">
<div class="row">
<div class="twelve wide column">
<br>
<h2 class="">Client Name: <span style="margin-left: 50px;font-size: larger">{{ clientName }}</span></h2>
<div class="spacer30"></div>
</div>
<div class="eight wide column">
<h3>Home Phone #: {{homePhone}} </h3>
<h3>Cell Phone #: {{cellPhone}} </h3>
<h3>Office Phone #: {{officePhone}} </h3>
</div>
</div>
</div>
<hr>
<div class="spacer30"></div>
<div class="ui grid">
<div class="row">
<div class="eight wide column">
<h3># of Floor Panes: <h2>{{floorPanes}}</h2> </h3>
<h3># of OUTSIDE Ladder Panes: <h2>{{outsideLadderPanes}}</h2> </h3>
<h3># of Inside AND Outside Ladder Panes: <h2>{{ladderPanesInAndOut}}</h2> </h3>
</div>
</div>
</div>
<hr>
<!-- <h3>Original Quote: ${{clientDiscount - }} </h3> -->
<h3 *ngIf="clientDiscount!= NaN">Client Discount: <span style="color:firebrick">- ${{discountPrice}} </span> </h3>
<h1>Total Quote: <span class="quotePrice" >${{estimatedQuote}}</span> </h1>
<div class="spacer50"></div>
<h3>Created By {{currentUser}} on {{currentDate | date:'fullDate'}} </h3>
</div>
<div class="spacer50"></div>
<button class="ui orange button" (click)="downloadPDF()">Export As PDF</button>
<div class="spacer75"></div>
</div>
Here is my form.component.ts file
import { NavigationComponent } from './../navigation/navigation.component';
import { Estimate } from './../estimate';
import { NgForm, FormsModule } from "#angular/forms";
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
constructor(
) { }
// =========== Text Mask ==============
mask: any[] = ['+','1',' ', '(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
// =========== Variables ===========
submitted = false;
// isOn = false;
costPerPane = 0.00;
costForLadder = 0.00;
costForFloorPanes = 0.00;
estimatedQuote = 0.00;
// quoteDemo = new Estimate("Phil",12,12,0,0,0);
clientName:string = "";
clientHomePhone:string;
clientCellPhone:string;
clientOfficePhone:string;
currentUser:string;
currentDate:string;
referral:string;
totalPanes:number;
floorPanes:number;
outsideLadderPanes:number;
ladderPanesInAndOut:number;
clientDiscount:number;
discountType:string;
discountPrice:any;
onSubmit(calculatingForm :NgForm){
this.submitted = true;
//Getting Form Input Values
this.clientName = calculatingForm.form.get('name').value;
this.clientHomePhone = calculatingForm.form.get('homePhone').value;
this.clientCellPhone = calculatingForm.form.get('cellPhone').value;
this.clientOfficePhone = calculatingForm.form.get('officePhone').value;
this.totalPanes = calculatingForm.form.get('totalPanes').value;
this.floorPanes = calculatingForm.form.get('floorPanes').value;
this.outsideLadderPanes = calculatingForm.form.get('outsideLadderPanes').value;
this.ladderPanesInAndOut = calculatingForm.form.get('ladderPanesInAndOut').value;
this.clientDiscount = calculatingForm.form.get('clientDiscount').value;
this.discountType = calculatingForm.form.get('discountType').value;
this.currentUser = calculatingForm.form.get('currentUser').value;
this.currentDate = Date.now().toString();
// ============ TOTAL QUOTE ==========
this.estimatedQuote = (this.costForFloorPanes + this.costForLadder);
//------ Discount Amount ----------
if (this.discountType == "Percentage") {
this.clientDiscount /= 100;
this.discountPrice = (this.estimatedQuote * this.clientDiscount);
this.estimatedQuote -= (Math.round(this.discountPrice));
this.discountPrice = (Math.round(this.discountPrice)).toString();
// this.estimatedQuote = (Math.ceil(this.estimatedQuote));
}else if(this.discountType == "Dollars"){
this.discountPrice = this.clientDiscount.toString();
this.estimatedQuote -= this.clientDiscount;
}else{
this.estimatedQuote = this.estimatedQuote;
}
}//End of onSubmit
public goBack(){
this.estimatedQuote = 0.00;
this.submitted = false;
}
public downloadPDF(){
return xepOnline.Formatter.Format('content', {render: 'download'});
}
ngOnInit() {
}
}
The error seems to be in the HTML:
[(ngModel)]="stufffffffs"
You have taken the wrong ngModel binding, the variables you have taken in component are not taken in form
In component you have taken,
clientName:string = "";clientHomePhone:string;clientCellPhone:string;
but in form you took,
Name:string = "";HomePhone:string;CellPhone:string;
You forgot to prepend client
Eg;
<input type="text" name="name" [(ngModel)]="name" #client="ngModel" required autofocus>
Should be,
<input type="text" name="name" [(ngModel)]="clientName" #client="ngModel" required autofocus>
so, replace all the occurrences with the same.
Use the same variables with ngModel that are defined in the component. It basically means there is a property in the component, that it is referring to. But as there is no such variable as "homePhone" in component, hence it is giving an error.
[(ngModel)]="clientHomePhone" instead of [(ngModel)]="homePhone"
<input type="tel" name="homePhone" id="homePhone" [(ngModel)]="clientHomePhone" placeholder="(123) 456-7890" [textMask]="{mask: mask}">
Similarly, for all other inputs for which the error is coming.
Read this for how ngModel works.

Web application using the Slim API. I'm trying to get data from my SQL database to populate a modal when the edit link is clicked in the table

Whilst debugging; the id for each row is found when the edit button is clicked but it seems to get stuck at that point. The data for the said row will not populate the modal. I would appreciate any help at all! Here is a picture in chrome. I have exhausted all of my ideas. I do have an error for localhost failed to load resource for an image folder, could this be causing conflict? I don't see how.
HTML
<div class="tab-pane" id="admin">
<br>
<div class="container">
<table id="admin_table" class="display">
<thead>
<tr>
<th>Title</th>
<th>Genre</th>
<th>Platform</th>
<th>Score Phrase</th>
<th>Score</th>
<th>Release Year</th>
<th>Release Month</th>
<th>Release Day</th>
<th>Editors Choice</th>
<th>Edit</th>
<th>x</th>
</tr>
<tbody id="admin_table_body">
</tbody>
</table>
</div> <br><br><br><br>
</div>
</div>
>Modal
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Edit</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" method="post">
<div class="form-group">
<label class="col-sm-4 control-label"><strong>ID:</strong></label>
<input type="text" style="height:32px;" name="id" id="id" disabled/>
<label for="id" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Title:</strong></label>
<input type="text" style="height:32px;" id="title" name="title"/>
<label for="title" class="error" ></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Genre:</strong></label>
<input type="text" style="height:32px;" id="genre" name="genre"/>
<label for="genre" class="error" ></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Platform:</strong></label>
<input type="text" style="height:32px;" id="platform" name="platform"/>
<label for="platform" class="error" ></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Score:</strong></label>
<input type="text" id="score" name="score" style="height:32px;"/>
<label for="score" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Score Phrase:</strong></label>
<input type="text" id="score_phrase" name="score_phrase" style="height:32px;"/>
<label for="score_phrase" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Release Year:</strong></label>
<input type="text" id="release_year" name="release_year" style="height:32px;"/>
<label for="release_year" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Release Month:</strong></label>
<textarea id="release_month" name="release_month" style="height:32px;"></textarea>
<label for="release_month" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Release Day:</strong></label>
<textarea id="release_day" name="release_day" style="height:32px;"></textarea>
<label for="release_day" class="error"></label>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><strong>Editors Choice:</strong></label>
<textarea id="editors_choice" name="editors_choice" style="height:32px;"></textarea>
<label for="editors_choice" class="error"></label>
</div>
</form>
</div>
Main.js
var rootURL ="http://localhost:4006/GamesAPI/api/games";
var currentGame;
//when the DOM is ready
$(document).ready(function(){
findAll();
//findById();
$(document).on("click","#admin_table_body a",function(){findById(this.id);});
// $(document).on("click","#addButton",function(){addGame();});
// $(document).on("click","#deleteButton",function(){deleteGame();});
});
var findAll=function(){
console.log('findAll');
$.ajax({
type: 'GET',
url: rootURL,
dataType: "json", // data type of response
success: renderList
});
};
var findById = function(id)
{
console.log('findById: '+id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: "json",
//Gets stuck here
success: function(data){
//$('#btnDelete').show();
console.log('findById success: ' +data.title);
currentGame = data;
renderDetails(currentGame);
}
});
};
function renderList(data){
list = data.games;
console.log("renderList");
$('#admin_table_body tr').remove();
$.each(list, function(index, games){
$('#admin_table_body').append('<tr><td>' +games.title+'</td><td>'+games.genre+'</td><td>'
+games.platform+'</td><td>' +games.score_phrase+'</td><td>'
+games.score+'</td><td>'+games.release_year+'</td><td>'+games.release_month+'</td><td>'
+games.release_day+'</td><td>'+games.editors_choice+'</td><td>\n\
Edit</td>\n\
<td id="'+games.id+'"><button type="button" id="deleteButton" class="btn btn-success">Delete</button></td></tr>');
});
$('#admin_table').DataTable();
// $('gameList').append('<div class="row">');
//The rest of this function is to populate a different client page
output='<div class="row">';
$.each(list, function(index,games){
var img="pics/"+games.picture;
output+=('<div class="col-sm-6 col-md-4 col-lg-3"><div class="card"><img src='+'"'+img+'"'+
'height="150"><p>Title: '+games.title+'</p><p>Genre: '+games.genre+'</p><p>Platform: '+games.platform+
'</p><p>Score: '+games.score+' '+games.score_phrase+'</p></div></div>');
// $('#gameList').append('<div class="col-sm-6 col-md-4 col-lg-3"><div class="card">'+game.title+'</div></div>');
});
// $('#gameList').append('</div>');
output+='</div>';
$('#productList').append(output);
};
var renderDetails = function(games)
{
$('#id').val(games.id);
$('#title').val(games.title);
$('#url').val(games.url);
$('#platform').val(games.platform);
$('#score').val(games.score);
$('#score_phrase').val(games.score_phrase);
$('#genre').val(games.genre);
$('#pic').attr('src', 'pics/' + games.picture);
$('#editors_choice').val(games.editors_choice);
$('#release_year').val(games.release_year);
$('#release_month').val(games.release_month);
$('#release_day').val(games.release_day);
};
DatabaseMethod.php
function getGame($id) {
$query = "SELECT * FROM games WHERE id = '$id'";
try {
global $db;
$games = $db->query($query);
$game = $games->fetch(PDO::FETCH_ASSOC);
header("Content-Type: application/json", true);
echo $query;
echo json_encode($game);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Your server-side PHP method is outputting data which is not valid JSON.
Remove
echo $query;
from your code, since it's just left over from debugging. This is preventing jQuery from seeing the whole response as JSON and parsing it accordingly.

Record data: SyntaxError: Unexpected end of JSON input

I can record data in my db but ajax loading doesn't inter in success method. What's the problem?
error: "SyntaxError: Unexpected end of JSON input
at Object.parse (native)
at n.parseJSON "
record_data.php
<?php
$type=getPar_empty("type",$_GET,"");
$new_nome=$_GET['new_nome'];
$new_cognome=$_GET['new_cognome'];
$new_email=$_GET['new_email'];
$new_lingua=$_GET['new_lingua'];
if ($type=="add_user"){
$stmt=null;
$stmt=$db->prepare("INSERT INTO newsletter_utenti(email,abilitato,nome,cognome,lingua,lista,data_creazione,unsubscribe) VALUES('$new_email',1,'$new_nome','$new_cognome','$new_lingua','manual',now(),0)");
if (!$stmt) {
log_msg($db->error);
die();
}
$stmt->execute();
$stmt->close();
$db->close();
}
?>
script
$("#salvaBtn").click(function(){
var nome = $('#nome').val();
var cognome = $('#cognome').val();
var email = $('#email').val();
var lingua = $('#lingua').val();
var dataString = 'nome='+nome+'&cognome='+cognome+'&email='+email+'&lingua='+lingua+'&type=add_user';
$.ajax({
type:'GET',
data:dataString,
url:"record_data.php",
success:function(result) {
$("#status_text").html(result);
$('#nome').val('');
$('#cognome').val('');
$('#email').val('');
},
error:function(xhr,status,error) {
console.log(error);
}
});
});
$('#adduser').submit(function (){
return false;
});
form
<form name="adduser" id="adduser" method="GET" action="#">
<div class="col-md-3">
<div class="form-group m-b-30">
<p>E-mail</p>
<input class="form-control" type="email" id="email" name="email" placeholder="indirizzo e-mail" email required>
</div>
</div>
<div class="col-md-3">
<div class="form-group m-b-30">
<p>Nome</p>
<input class="form-control" type="text" id="nome" name="nome" placeholder="nome">
</div>
</div>
<div class="col-md-3">
<div class="form-group m-b-30">
<p>Cognome</p>
<input class="form-control" type="text" id="cognome" name="cognome" placeholder="cognome">
</div>
</div>
<div class="col-md-3">
<div class="form-group m-b-30">
<p>Lingua</p>
<select class="form-control" id="lingua" name="lingua">
<option value="it">IT</option>
<option value="en">EN</option>
</select>
</div>
<input type="submit" class="btn btn-embossed btn-primary m-r-20" id="salvaBtn" value="Aggiungi utente"></input>
<div id="status_text" /></div>
</div>
</form>
Your ajax method is POST, but you try to recive values from GET, could be this.
Another way is to use json_decode, from PHP.
$vars = json_decode($_POST['data']);
tell us, these changes will clear your code input.
thanks