how to send and retrieve data in a php file from angularjs - javascript

I have a project made in angularjs. i need click the botton prueba and send one parameter to the phpfile to validate if its a number xxxx, return some information, if its other number, return other information.
I have to receive the number in the file php and code a if structure but I couldn't receive the parameter en the php file.
Here is my code
HTML
<!DOCTYPE html>
<html ng-app="AppUts">
<head>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<meta charset='utf-8'>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body ng-controller="EstudiantesController as estCtrl">
<input ng-model="info" class="form-control" id="identificacion" type="text" placeholder="Nro Identificación" />
<button ng-click="estCtrl.traer()" class="btn btn-success" id="boton">seguir</button>
<button ng-click="estCtrl.traer2()" class="btn btn-success" id="boton">prueba</button>
<div class="list-group">
<div id="destino_datos_estudiante">
</div>
<div class="list-group-item" id="jsones" ng-show="estCtrl.datos[0].isError">
nombre de estudiante
<h3>{{estCtrl.datos[0].nombreEstudiante}}</h3>
programa
<h3>{{estCtrl.datos[0].nombrePrograma}}</h3>
</div>
</div>
</body>
</html>
JS
(function() {
var app = angular.module('AppUts', []);
app.controller('EstudiantesController', ['$http', function($http){
var estudiante = this;
estudiante.datos = [];
estudiante.traer = function(){
$http.get("datos_estudiante.php").success(function(data){
estudiante.datos = data;
});
}
estudiante.traer2 = function(){
estudiante.jsonData = {num: 1, num: "manzana"}
$envio = $http({
url: "datos_estudiante.php",
method: "POST",
data: {val: 3}
}).success(function(){
console.log($envio);
});
}
}]);
})();
PHP
<?php
$data = file_get_contents("php://input");
$objData = json_decode($data);
$datosEstudiante[] = ["nombreEstudiante" => "Andres Mogollon",
"nombrePrograma" => "Tecnologia Desarrollo Sistemas Informaticos",
"progId" => 1,
"estudianteId" => 1,
"msg" => "vacio",
"isError" => true
];
echo json_encode($datosEstudiante);
?>
Thank you

Related

How to connect HTML page to MySQL Workbench Server using JavaScript,Ajax and PHP?

I have an HTML page where we enter the name of a movie and if that movie is present in the database,then the name is displayed. I am trying to connect to the database using JavaScript, Ajax and PHP. The database is in the MySQL Workbench Server.
This is what I have done:
pc.html
<html>
<head>
<script type="text/javascript">
function Search_Data()
{
var httpr = new XMLHttpRequest();
var movie_name=document.getElementById("moviename").value;
console.log(movie_name);
httpr.open("GET","get_data.php",true);
httpr.send();
httpr.onreadystatechange = function()
{
if(this.readyState==4 && this.status==200)
{
alert(this.responseText);
}
}
}
</script>
<body>
<input type="text" name="moviename" id="moviename" placeholder="Enter a movie...">
<br/>
<input type="button" name="search" value="Search" onclick="Search_Data()">
<br/>
<span id="response"></span>
</body>
</head>
</html>
get_data.php
(Below code is a trial code to see if its working)
<?php
echo "Hello World"
?>
In the browser,the result I am getting is:
The files are in the following location:
C:\Users\Admin\AppData\Roaming\MySQL\Workbench\scripts
The entire code is getting displayed instead of just "Hello World".I am new to web development and PHP and I am not sure what seems to be the problem.
what are you using is ajax with normal java-script i suggest to use jquery ajax and this is a full example how to connect it to php and how to get the value or list
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<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>
</head>
<body>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
<td width="90%"><span id="employee_name"></span></td>
second
<input type="input" id="inputs" value="submit">
<p id="email"></p>
<p id="pass"></p>
<p id="permission"></p>
<script>
$(document).ready(function(){
$('#search').click(function(){
var val = document.getElementById("inputs").value;
var id= $('#employee_list').val();
setInterval(function(){
$.ajax({
url:"db.php",
method:"POST",
data: {val : val},
dataType:"JSON",
success:function(data)
{
$('#email').text(data[val].email);
$('#pass').text(data[val].pass);
$('#permission').text(data[val].perm);
}
})
}, 1000);
});
});
</script>
</body>
</html>
the php file
<?php
$items = array();
$url="localhost";
$user= "root";
$pass="";
$dbname="test";
$value= 0;
if(isset( $_POST['val'])){
$value= $_POST['val'];
}
$num=0;
$connect=mysqli_connect($url,$user,$pass,$dbname);
$result="SELECT email,pass,permission FROM test where id=$value";
$sql=mysqli_query($connect,$result);
while($row=mysqli_fetch_assoc($sql) ){
/* add a new item */
$num++;
$items[$value] = array(
'email' => $row['email'],
'pass' => $row['pass'],
'perm' => $row['permission']
);
}
$json_response = json_encode($items);
echo $json_response;
?>

Suggestion box app won't display suggestions

I'm trying to create a suggestion box app in JavaScript using AngularJS 1.X that people can post suggestions on and upvote those suggestions. I'm having trouble getting the suggestions to show up on the page. Help? Here's my code:
index.html:
<!DOCTYPE html>
<html>
<Head>
<title>Suggestion Box</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
</Head>
<body ng-app="SuggestionBox" ng-controller="HomeController">
<h1> Suggestion Box </h1>
<form ng-submit="addSuggestion()" style="margin-top: 50px">
<h3> Submit Your Suggestion </h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Great ideas here" ng-model="title"></input>
</div>
<button type="submit" class="btn btn-primary">Suggest</button>
</form>
<div class="main" ng-repeat="post in posts"></div>
<p>
<span class="glyphicon glyphicon-plus-sign" ng-click="upVote(post)"></span> Upvotes: <span id="$scope.posts.upvotes"></span>
</p>
<!-- Modules -->
<script type="text/javascript" src="C:\Users\Olivia\Documents\JS\app.js"></script>
<!-- Controllers -->
<script type="text/javascript" src="C:\Users\Olivia\Documents\JS\controllers\HomeController.js"></script>
<!-- Services -->
<script type="text/javascript" src="C:\Users\Olivia\Documents\JS\Services\Suggestions.js"></script>
</body>
</html>
Controller:
app.controller('HomeController', ['$scope', 'suggestions', function($scope, suggestions) {
$scope.helloWorld = "Hello, AngularJS!",
$scope.posts = Suggestions.posts,
$scope.addSuggestion = function($scope.title) {
if(!$scope.title || $scope.title === "") {
return;
};
$scope.posts.push({
title: $scope.title,
upvotes: 0,
});
$scope.title = '';
}
$scope.upVote = function(post) {
$scope.posts[post].upvotes += 1;
};
}]);
app.js:
var app = angular.module('SuggestionBox', ['ngRoute']);
I haven't added any routing yet so the route is just sitting there
Suggestions.js:
app.factory('Suggestions', [function(){
var demoSuggestions = {
posts: [
{
title: 'Insert suggestion here',
upvotes: 10,
comments: [],
},
{
title: 'See above',
upvotes: 2,
comments: [],
},
]
};
return demoSuggestions;
}]);
Any help would be greatly appreciated. Thanks!
This is a working version. It looks like you're pretty new to AngularJS. Feel free to ask any questions.
"use strict";
var app = angular.module('SuggestionBox', ['ngRoute']);
app.factory('SuggestionsFactory', [function () {
var posts = [
{
title: 'Insert suggestion here',
upvotes: 10,
comments: [],
id: 1
},
{
title: 'See above',
upvotes: 2,
comments: [],
id: 2
}
];
function postFactory(title) {
return {
title: title,
upvotes: 0,
comments: []
}
}
var getPosts = function(){
return angular.copy(posts);
}
var addPost = function (title) {
posts.push(postFactory(title));
}
var removePost = function(id){
// remove from posts by id
}
return {
getPosts: getPosts,
removePost: removePost,
addPost: addPost
}
}]);
app.controller('HomeController', ['$scope', 'SuggestionsFactory', function ($scope, SuggestionsFactory) {
var vm = this;
vm.posts = SuggestionsFactory.getPosts();
vm.title = '';
vm.addSuggestion = function () {
if (vm.title && vm.title !== '') {
SuggestionsFactory.addPost(vm.title);
vm.posts = SuggestionsFactory.getPosts();
vm.title = '';
}
}
vm.upVote = function (post) {
post.upvotes += 1;
};
}]);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body ng-app="SuggestionBox" ng-controller="HomeController as vm" class="container">
<div class="row">
<div class="col-sm-12">
<h1> Suggestion Box </h1>
<ng-form style="margin-top: 50px">
<h3> Submit Your Suggestion </h3>
<div class="form-group">
<input type="text" class="form-control" placeholder="Great ideas here" ng-model="vm.title" />
</div>
<button type="button" class="btn btn-primary" ng-click="vm.addSuggestion(vm.title)">Suggest</button>
</ng-form>
<div class="main" ng-repeat="post in vm.posts">
<p style="font-weight:bold;">{{post.title}}</p>
<div>
<button ng-click="vm.upVote(post)">upvote</button> Upvotes:
<span id="upvotes">{{post.upvotes}}</span>
</div>
</div>
</div>
</div>
</body>
</html>

AngularJS $location directory

Main page URL: http://localhost:3000/
Current second page URL: http://localhost:3000/#/titleDetails.html
Expected second page URL: http://localhost:3000/titleDetails.html
Currently when I click on the title in my main page, the URL contains an extra /# which causes the page to be redirected to titleDetails.html.
The directory of titleDetails.html and index.html is in the same directory.
May I know how can I fix this?
Original Post: AngularJS Display 1 Post in New Page
app.js
(function () {
angular
.module("BlogApp", [])
.config(function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
})
.controller("BlogController", BlogController);
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function init() {
getAllPosts();
}
init();
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('/titleDetails.html');
}
function updatePost(post){
console.log(post);
$http
.put("/api/blogpost/"+post._id, post)
.success(getAllPosts);
}
function editPost(postId){
$http
.get("/api/blogpost/"+postId)
.success(function(post){
$scope.post = post;
});
}
function deletePost(postId){
$http
.delete("/api/blogpost/"+postId)
.success(getAllPosts);
}
function getAllPosts(){
$http
.get("/api/blogpost")
.success(function(posts) {
$scope.posts = posts;
});
}
function createPost(post) {
console.log(post);
$http
.post("/api/blogpost",post)
.success(getAllPosts);
}
}
})();
index.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>
<div ng-repeat="post in posts">
<h2>
<a ng-click="titleDetails(post)">{{ post.title }} </a>
<a ng-click="editPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-pencil"></span></a>
<a ng-click="deletePost(post._id)" class="pull-right"><span class = "glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
</div>
</body>
</html>
titleDetails.html:
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
</html>
Console Error in index.html:
angular.js:13708 Error: [$location:nobase] http://errors.angularjs.org/1.5.7/$location/nobase
at angular.js:38
at sf.$get (angular.js:13384)
at Object.invoke (angular.js:4709)
at angular.js:4508
at d (angular.js:4655)
at e (angular.js:4679)
at Object.invoke (angular.js:4701)
at R.instance (angular.js:10234)
at m (angular.js:9147)
at g (angular.js:8510)
Angular has 3 routing operates:
Hashbang Mode
HTML5 Mode
Hashbang in HTML5 Mode
You can configure: $locationProvider.html5Mode(true).hashPrefix('!');
Check documentation

Multiple get requests when loading page

When I visit my page, a get-request is fired 4 times, when It's just supposed to be fired 2 times. Take a look at the picture below:
Here is my code:
index.html:
<!DOCTYPE html>
<html ng-app="cryptlib">
<head>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
</head>
<body ng-controller="firstPageController">
<div ng-view>
</div>
</body>
<script src="js/angular-file-upload-shim.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.2.20" src="https://code.angularjs.org/1.2.20/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular-sanitize.js"></script>
<script src="js/angular-file-upload.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script>
</html>
firstpage.html
<link href='http://fonts.googleapis.com/css?family=Fjord+One' rel='stylesheet' type='text/css'>
<div id="layout">
<div id="top">
<h2>CryptLib</h2>
</div>
<div id="main">
<div class="leftcontent">
<ul>
<li>>> Webbutveckling</li>
<li>>> Programmering</li>
<li>>> Elektronik</li>
<li>>> Vetenskap</li>
<li>>> Övrigt</li>
<li>>> Ladda upp</li>
</ul>
</div>
<div class="maincontent">
<li ng-repeat="book in books track by $index">
{{book}}
</li>
</div>
<div id="bottom">
<h3>Ladda upp {{selectedItem}}</h3>
<input type="text" ng-model="myModelObj">
Välj mapp:
<select ng-model="selectedItem" ng-options="item for item in items" ng-change="change()">
</select>
<input type="file" ng-file-select="onFileSelect($files)">
<!--Bild<input type="file" ng-file-select="onFileSelect($files)" multiple accept="image/*">-->
</div>
</div>
controller.js
angular.module('cryptlib_controllers')
.controller('firstPageController', ['$scope','$http','$location','$sce','$rootScope','$upload', function($scope, $http, $location, $sce, $rootScope, $upload) {
$http({
url: 'lib/actions.php',
method: 'GET',
params: {get_books: 1}
}).success(function(data) {
$scope.books = data;
});
$http({
url: 'lib/actions.php',
method: 'GET',
params: {get_dirs: 1}
});
console.log($scope.books);
$scope.onFileSelect = function($files) {
//Vi har valt en eller flea filer
//$files är en array innehållande de valda filerna att ladda upp. Dess namn, storlek och typ
for(var i = 0; i < $files.length; i++)
{
var file = $files[i];
$scope.upload = $upload.upload({
url: 'lib/actions.php',
data: {myObj: $scope.myModelObj},
file: file
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
console.log(data);
});
}
};
$scope.items = ['Programmering', 'Elektronik'];
$scope.change = function() {
alert($scope.selectedItem);
}
}]).controller('bookController', ['$scope','$http','$location','$sce','$rootScope','$upload', function($scope, $http, $location, $sce, $rootScope, $upload) {
}]);
Why is a get request fired 4times when I visit the page? It should only be fired 2times? Anyone who can explain?
Because you are defining firstPageController twice. First in the body tag, and then in the route.

Updating a variable inside Service

Right I've got a really dumb one for you, and I've been looking at this code all day with no result.
I have a simple textbox which goes through a controller and updates a variable inside a service (The service will eventually fetch/update data from somewhere else).
At the moment, I am able to retrieve the variable value all the way to the view and it works, but the textbox is unable to update the variable inside the service in order to then display the new variable value in the view again....
I really appreciate any help and hope I have made sense!!!
// APP/APP.JS
(function(){
var app = angular.module('appMod', ['ngRoute', 'ngAnimate']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'introController',
templateUrl: 'app/partials/intro.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('nameController', function($scope, dataService) {
var nameValue;
this.name = dataService.getName();
this.submitName = function(nameVal) {
nameValue = this.nameCtrl.nameVal;
dataService.setName(nameValue);
};
});
app.controller('introController', function($scope, dataService) {
this.name = dataService.getName();
});
app.service('dataService', function () {
var name = "f";
this.getName = function() {
return name;
};
this.setName = function(nameVal) {
name = nameVal;
};
});
})();
<!-- INDEX.HTML -->
<!DOCTYPE html>
<html ng-app="appMod">
<head>
<link rel="stylesheet" type="text/css" href="content/css/normalize.css">
<link rel="stylesheet" type="text/css" href="content/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="content/css/style.css">
<link rel="stylesheet" type="text/css" href="content/css/animation.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/angular.min.js"></script>
<script type="text/javascript" src="scripts/angular-route.min.js"></script>
<script type="text/javascript" src="scripts/angular-timer.min.js"></script>
<script type="text/javascript" src="scripts/angular-animate.min.js"></script>
<script type="text/javascript" src="app/app.js"></script>
</head>
<body>
<div class="container">
<div class="row" ng-controller="nameController as nameCtrl">
<img src="content/images/sitelogo.png" class="logo">
<h2 class="welcomeMessage fade">Welcome <span class="fade" ng-show="!nameCtrl.name == ''">{{nameCtrl.name}}</span><span class="inline fade" ng-hide="nameCtrl.name !== ''">Friend</span> <small>(We like to get personal!)</small></h2>
<div class="namebox fade">
<h2>Welcome <small class="fade">Please type your name</small></h2>
<form class="fade">
<div class="form-group">
<input type="text" class="form-control" ng-model="nameCtrl.nameVal" autofocus>
</div>
<button type="submit" style="width:100%;" class="btn btn-default fade" ng-click="nameCtrl.submitName()" >Submit</button>
</form>
</div>
</div>
</div>
<div ng-view></div>
</body>
</html>
You need to be binding to name and not nameVal on your input
Then just pass that in your setName call, i don't think the rest of the code is needed in there, you can get rid of the nameValue var too.
this.submitName = function() {
dataService.setName(this.name);
};
The nameValue var is local to the controller and not available on the $scope to bind to your view, so even though you were changing it, the view didn't know about it as it couldn't see that var.

Categories

Resources