How to retrieve parameters sent with http.get - php

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);

Related

PHP/MySQL/AJAX - Refresh query values with AJAX

I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.

How to select data from db using angular variable in php

I want to write select query in php to get data from database using variable from front-end. In other words I need to do something like this:
SELECT email FROM users WHERE token = '$token'
What I currently have, I have code which posts my variables to back end:
app.controller('customersCtrl', function($scope, $http,$templateCache) {
$scope.subscribe = function (gameId){
$scope.codeStatus = "";
$http({
url: "php/test.php",
method: "POST",
data: {
userId: JSON.parse(localStorage.getItem('loggedUserInfo')),
gameId: gameId,
token:JSON.parse(localStorage.getItem('token'))
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).success(function(response) {
$scope.codeStatus = response.data;
console.log(response);
});
};
});
And here is my php code:
<?php
$lnk = mysql_connect('localhost', 'root', '')
or die ('Not connected : ' . mysql_error());
mysql_select_db('pitch', $lnk) or die ('Can\'t use db : ' . mysql_error());
$data = json_decode(file_get_contents("php://input"));
$token=$data->token;
$dump1 = mysql_query("SELECT email FROM users where token = '$token' ");
if(!$dump1) exit("Error - ".mysql_error());
$getList = array();
$outp = "";
while ($row = mysql_fetch_assoc($dump1)) {
$relations = array();
$getList[] = $row;
}
$output = json_encode(array('users' => $getList));
echo $output;
?>
The weirdest thing for me is that when I try to go to url localhost/php/test.php I get an Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/test.php on line 8, which means I guess that $token is empty, but when I console.log(response) in angular it shows me my token in console which I think means that data from front-end was passed to back-end. Or my understanding is wrong?
Will be really thankful for help!
first thing is try to var_dump($_POST), or try to var_dump($data) on your test.php

Showing data from database with AngularJS

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);
});
}
}
}]);

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

fetch data in $_POST variable in angularjs

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;
});

Categories