I want to diplay data from db in my page .
This is my code in
JS :
$scope.save = function() {
var data = {
subject: $scope.composeStory.subject,
body: $scope.composeStory.body
}
$http.post(
"insert.php", {
'subject': $scope.composeStory.subject,
'body': $scope.composeStory.body
}
)
.success(function(data, status, headers, config) {
console.log("inserted Successfully");
});
};
and Php
include('config.php');
$data = json_decode(file_get_contents("php://input"));
$subject = mysql_real_escape_string($data->subject);
$body = mysql_real_escape_string($data->body);
mysql_select_db("angular") or die(mysql_error());
mysql_query("INSERT INTO story (subject,body) VALUES ('$subject', '$body')");
Print "Your information has been successfully added to the database.";
$query = "SELECT * FROM story";
$result = mysql_query($query);
$arr = array();
while ($row = mysql_fetch_array($result)) {
$subject = $row['name'];
$body = $row['description'];
$arr[] = $row;
}
echo json_encode($arr);
Json
[{"0":"","subject":"","1":"","body":""},
{"0":"","subject":"","1":"","body":""},
{"0":"Soheil","subject":"Soheil","1":"Sadeghbayan","body":"Sadeghbayan"},
{"0":"adsas","subject":"adsas","1":"asdasdasda","body":"asdasdasda"},
{"0":"Say","subject":"Say","1":"Something","body":"Something"}]
it saved to db perfectly , but i dont know how to display data from database to my page ?
For retrieval of data create a factory-service which would use $http GET method, with the url pointing to your php file which returns the $data array in the format: echo json_encode($data);
This is a recent example I posted on another question:
demoApp.factory('simpleFactory', ['$http', function($http){
return {
getCustomer: function(){
return $http.get("json/customers.php").then(
function(response){
var customers = [];
customers = response.data;
},
function(error){
console.log(error);
});
}
}
}]);
Related
I have a problem that I've been trying to solve for a long time. I have read courses about PHP sessions and I had proposals to use localstorage but to no avail
The problem:
Im working with angularJS and PHP backend, and I have 2 views, one 'login.html' and the other 'info.html', 2 controllers (one for the login function and the other for selecting the user's data) . I managed to do the authentication phase but for the second step I want that when the user authenticates, it will be redirected to other view (info.html) where all the information of this user will be displayed. How can I store the data from login function and use it in the second controller(second web service)
login.php
<?php
session_start();
$_SESSION['token'] = true;
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
if(count($data) > 0)
{
$Email=mysqli_real_escape_string($connect, $data->Email);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE (EmailClient = "'.$Email.'" AND mdp= "'.$mdp.'")';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$token = md5($Email.time()."51395+81519851");
$query = "UPDATE client SET token = '".$token."' WHERE EmailClient = '".$Email."'";
mysqli_query($connect , $query);
$_SESSION["logged_in"] = true;
$_SESSION["token"] = $token;
$_SESSION["Email"] = $Email;
$result['token'] = $token;
$resultstring=json_encode($result);
$resultstring=str_replace("null", '""', $resultstring);
echo $resultstring;
exit;
}
?>
loginCtrl
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'Email' : $scope.Email,
'password' : $scope.password
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
$state.go('info');
}
})
.error(function(data, status, headers, config, result)
{
console.log('error');
});
}
});
infoCtrl :
app.controller('infoCtrl', function($scope, $http,$state,$filter){
$scope.loadColis = function(){
$http.get("http://localhost/deb/info.php")
.success(function(data){
$scope.names = data;
});
}
info.php
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "test");
$output = array();
$query = "SELECT Name,Adresse FROM client WHERE token = '".$_SESSION['token']."'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output[] = $row;
}
echo json_encode($output);
}
?>
I don't know how get user authenticated data, how can I do please?
Thanks in advance
In Login Controller:
app.controller('loginCtrl', function($scope, $location,$state,$http,$window, $cookies){
$scope.submit = function()
{
data = {
'Email' : $scope.Email,
'password' : $scope.password
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
$cookies.putObject('AuthenticateData', data);
$state.go('info');
}
})
.error(function(data, status, headers, config, result)
{
console.log('error');
});
}
});
In Info controller:
app.controller('infoCtrl', function($scope, $http,$state,$filter, $cookies){
//use something like this
var authenticateData = cookies.getObject("AuthenticateData");
});
This is just an example to show how cookies does works. You can work around in it.
I am experimenting with making a very simple API from raw PHP (no framework).
When I type on browser http://localhost/simpleAPI/countries.php it outputs the data that I want.
But when I use and ajax call, I get an internal server error response.
<?php
require_once 'Database.php';
header("Content-Type: application/JSON");
$mysqli = Database::getInstance();
$data = [];
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM Country LIMIT 10")) {
while ($row = $result->fetch_object()){
$data[] = $row->Name;
}
/* free result set */
$result->close();
}
$res = response(200, 'ok', $data);
function response($status, $message , $data){
header("HTTP/1.1 $status $message"); <-- working Now (after adding $status)
$res['status'] = $status;
$res['message'] = $message;
$res['data'] = $data;
echo json_encode($res);
}
AJAX
var jqxhr = $.get( "countries.php", function(data) {
alert( data);
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
error
jquery.min.js:4 GET http://localhost/simpleAPI/countries.php 500 (Internal Server Error)
I am using http.get to get data from database. I am sending the parameters along with url. but the parameters are not accessible from that url.
Here is my Angularjs controller code :
app.controller('ListCtrl', ['$scope', '$http', '$location', '$window', function($scope,$http,$location,$window){
$scope.data = {};
$scope.getdata = function(){
$scope.datas = [];
$http({
url: "http://localhost/angular/data.php",
method: "GET",
params: {'place':$scope.data.place,'pincode':$scope.data.pincode}
})
.success(function(data,status,headers,config){
$scope.datas=data;
console.log($scope.datas);
$scope.navig('/show.html');
})
.error(function(){
alert("failed");
});
};
$scope.navig = function(url){
$window.location.href = url;
};
}])
And here is my data.php file
<?php
header("Access-Control-Allow-Origin: *");
$postdata = file_get_contents("php://input");
$data= json_decode($postdata);
$place = mysql_real_escape_string($data->place);
$pincode = mysql_real_escape_string($data->pincode);
//$place = $_GET[$data->place];
if ($place){
$connection = mysqli_connect("localhost","root","","building") or die("Error " . mysqli_error($connection));
$sql = "SELECT * from details ";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$detail = array();
while($row =mysqli_fetch_assoc($result))
{
$detail[] = $row;
}
echo json_encode($detail);
mysqli_close($connection);
}
else {
echo "no place entered";
}
?>
It outputs as "no place entered" even if I enter the place.
Is that the right way to retrieve the data?
I am passing either place or pincode, not both. will that cause any issue?
please help.
Solved it. Here is the solution.
I used these two line of code
$place = $_GET['place'];
$pincode= $_GET['pincode'];
instead of these 4 lines of code which is actually used to retrieve data sent with http.post
$postdata = file_get_contents("php://input");
$data= json_decode($postdata);
$place = mysql_real_escape_string($data->place);
$pincode = mysql_real_escape_string($data->pincode);
I have tried using the following code. But it is not working. I have a temporary sqllite table, I need to insert all data from temporary database to remote mysql server.
var url = "http://bmcagro.com/manoj/insertopinion.php";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this.responseText holds the raw text return of the message (used for JSON)
// this.responseXML holds any returned XML (used for SOAP web services)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == "true") {
var newtoast = Titanium.UI.createNotification({
duration: 1000,
message: "Inserted"
});
newtoast.show();
} else {
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "False"
});
toast.show();
}
},
onerror: function(e) {
Ti.API.debug(e.error);
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "Error in Connection!!"
});
toast.show();
},
timeout:5000 });
xhr.open("POST", url);
xhr.send({names: names});
});
and the php code is
<?php
$con = mysql_connect("MysqlSample.db.8189976.hostedresource.com","MysqlSample","xszZ#123ddlj");
if (!$con) {
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db("MysqlSample",$con);
if (!$db) {
echo "Failed to select db.";
exit;
}
$names = $_POST['names'];
foreach ($names as $name) {
mysql_query("INSERT INTO seekopinion(uid,gid,opiniondescription,date,postedto) VALUES (" + $name.gid + "," + $name.tempid + "," + $name.gid + ",NOW()," + $name.gid + ")");
}
if($query) {
$sql = "SELECT * FROM MysqlSample.seekopinion";
$q= mysql_query($sql);
$row = mysql_fetch_array($q);
$response = array(
'logged' => true,
'seekopinion' => $row['seekopinion']
);
echo json_encode($response);
} else {
$response = array(
'logged' => false,
'message' => 'User with same name exists!!'
);
echo json_encode($response);
}
?>
actually iam a beginer in php as well as titanium...anybody pls help me out.
Finally i found a way out ....
I changed the entire row to a string using delimiter '-' in appcelerator and then passed the parameter to the php code...from where the code is split using explode and then inserted using for loop
the appcelerator code for posting a table from an sqllite database to mysql database..
postbutton.addEventListener('click', function(e)
{
var names = [];
var datarow ="";
var db = Ti.Database.open('weather');
var rows = db.execute('SELECT tempid,gid,name,email FROM postedto');
while (rows.isValidRow())
{
datarow=datarow+"-"+rows.fieldByName('tempid')
rows.next();
}
db.close();
var params = {
"uid": Ti.App.userid,
"opiniondescription": question2.text,
"database": datarow.toString()
};
var url = "http://asdf.com/as/asd.php";
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this.responseText holds the raw text return of the message (used for JSON)
// this.responseXML holds any returned XML (used for SOAP web services)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged ==true)
{
var seekopinion11=require('seekopinion2');
var seekop11 = new seekopinion11();
var newWindow = Ti.UI.createWindow({
//fullscreen : true,
backgroundImage : 'images/background.jpg',
});
newWindow.add(seekop11);
newWindow.open({
//animated : true
});
}
else
{
var toast = Titanium.UI.createNotification({
duration: 2000,
message: response.message
});
toast.show();
}
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
var toast = Titanium.UI.createNotification({
duration: 2000,
message: "There was an error retrieving data.Please try again"
});
toast.show();
},
timeout:5000
});
xhr.open("GET", url);
xhr.send(params);
});
the php code for breaking the string using explode
<?php
$con = mysql_connect("MysqlSample.db.hostedresource.com","MysqlSample","xszZ#");
if (!$con)
{
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db("MysqlSample",$con);
if (!$db)
{
echo "Failed to select db.";
exit;
}
$uid= $_GET['uid'];
$opiniondescription= $_GET['opiniondescription'];
$database= $_GET['database'];
$insert = "INSERT INTO seekopinion(uid,opiniondescription,date) VALUES ('$uid','$opiniondescription',NOW())";
$query= mysql_query($insert);
$rows = explode("-", $database);
$arrlength=count($rows);
for($x=0;$x<$arrlength;$x++)
{
$insert = "INSERT INTO seekopinionuser(sid,postedto) VALUES ((SELECT MAX(sid) FROM seekopinion),$rows[$x])";
$query= mysql_query($insert);
}
if($query)
{
$sql = "SELECT s.sid,s.opiniondescription,s.uid,u.postedto FROM seekopinion s left join seekopinionuser u on s.sid=u.sid WHERE uid=$uid AND s.sid=(SELECT MAX(sid) FROM seekopinion) ";
$q= mysql_query($sql);
$row = mysql_fetch_array($q);
$response = array(
'logged' => true,
'opiniondescription' => $row['opiniondescription'],
'uid' => $row['uid'] ,
'sid'=>$row['sid']
);
echo json_encode($response);
}
else
{
$response = array(
'logged' => false,
'message' => 'Seek opinion insertion failed!!'
);
echo json_encode($response);
}
?>
i wish to post data to a php file using angularjs. I referred to the following link:
http://www.cleverweb.nl/javascript/a-simple-search-with-angularjs-and-php/
i tried the same example given in the link but the data is posted in JSON format. I want the data in $_POST variable. how do i do that?
here's my code:
search.js
function SearchCtrl($scope, $http) {
$scope.url = 'php/search.php'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.search = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request. i want the data in $_POST
$http.post($scope.url, { "data" : $scope.keywords}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
search.php
<?php
// The request is a JSON request.
// We must read the input.
// $_POST or $_GET will not work! **but i want it to work!**
$data = file_get_contents("php://input");
$objData = json_decode($data);
// perform query or whatever you wish, sample:
include 'connect.php';
mysql_select_db($database,$con);
$query = 'SELECT * FROM `product`';
$result = mysql_query($query) OR die(mysql_error());
$cnt = 0;
while ($row = mysql_fetch_assoc($result)) {
$nm = $row['name'];
//print_r($nm.' ');
if($objData->data == $nm) {
$cnt++;
}
}
if($cnt == 0) {
echo ' Sorry, no match!';
}
else {
echo ' I have found what you\'re looking for!';
}
how do i solve it?
Just normal PHP:
$_POST['title'] or $_POST['content'];
You can do it ;-)
This is an anwser to the comment beneath the post beneath.
Here you go, you can access the variables in the php file as you normally would.
$http.post("yourpagehandler.php", {
// Values you with to send to php page
"title": $scope.title,
"content": $scope.content
}).success(function(data, status) {
// Values returned from php handler will be in data
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});