fetch data in $_POST variable in angularjs - php

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

Related

I am not able to get response in angular js $http.post

I want to check whether the email id already exists in the db. If the email id exists, it should return false, else true. I'm not able to get the response. I've attached the controller code and the php code. [the variable validUser is undefined]
Controller.js
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
});
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
}
}
});
checkUser.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "user_details");
//$data = json_decode(file_get_contents("php://input"));
//$email = mysql_real_escape_string($data->email);
$email = $_POST['email'];
$result = $conn->query("SELECT count(*) as count from user where email='$email'");
$outp = "";
$rs = $result->fetch_array(MYSQLI_ASSOC)
if ($rs['count']==0)
{
$outp ="true";
}
else
{
$outp ="false";
}
$conn->close();
echo($outp);
?>
You're not checking the response in the correct place, or rather - at the correct time.
$http.post returns immediately. Your .then callback is called when the response is returned from the server. The code after the call to post (your if statements) is executed right after $http.post returns, and before the response is received from the server.
You should place your validation code inside your callback:
$http.post(...).then(function(response) {
validUser = response;
if(validUser==="true") {
...
} else if (validUser==="false") {
...
}
}
You're if statement needs to be inside the .then callback, otherwise you'll end up checking it before youre ajax request gets responded to
signUpApp.controller("signUpCtrl",function($scope,$http){
$scope.register = function(form,user){
if (form.$valid)
{
$http.post("http://localhost/checkUser.php?email="+user.email)
.then(function(response){
validUser=response;
if(validUser=="true")
{
alert("valid user");
}
else
{
alert("already exists");
}
});
}
}
});

How to retrieve parameters sent with http.get

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

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

Post to PHP with Ajax and read Results

I have read through dozens of similar questions on this website, and am having a lot of trouble trying to understand what is wrong with my code. I am trying to dynamically update select boxes based on the value of another one, but for some reason cannot seem to get any type of response data back once I post to PHP with Ajax.
JAVASCRIPT:
function toggleHiddenDIV()
{
var dc = document.getElementById("datacenter");
var dcVal = dc.options[dc.selectedIndex].value;
// Check if Datacenter selection has no Value selected
if(dcVal != '')
{
document.getElementById("hidden-options").style.display="block";
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action_type': 'update_inventory_fields', id: dcVal },
success: function(response)
{
alert(response);
}
});
}
else
{
document.getElementById("hidden-options").style.display="none";
}
};
</script>
PHP:
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
return json_encode($data);
}
Don't call return (since you're not returning a function); just echo then content onto the page:
echo json_encode($data);
Change to this...no need to return, just echo, since youre outside of a function call
if ($_POST['action_type'] == "update_inventory_fields")
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["id"])) { return; }
}
$result = mysql_query("SELECT id, ip, block FROM ipv4 WHERE datacenter = " . $_POST["id"]);
$data = array();
while($row = mysql_fetch_array($result, true))
{
$data[] = $row;
};
echo json_encode($data);
}
If the php code you posted is inside a function than you need to use echo functionname();
If the php code is not in a function, then just use echo json_encode($data);

Trouoble with Ajax submitting to database

I have this form:
<form method = \"get\" action = \"\" onsubmit = \"return addBeer('$user','$id','$name','$abv','$ibu','$icon','$style','$brewery','$breweryID','$icon')\" >
<p> <input type = \"submit\" value = \"Go Fishing\" /> </p>
</form>
which calls this JavaScript function:
function addBeer(user,id,bname,abv,ibu,icon,bstyle,brewery,breweryID,icon)
{
//get elements
alert('userID' + user);
alert('beerid'+id);
alert('beername'+bname);
alert('style'+bstyle);
alert('brewery'+brewery);
alert('abv'+abv);
alert('ibu'+ibu);
alert('brewery id'+ breweryID);
alert('icon'+icon);
//run ajax
var ajaxSettings2 =
{
type: "POST",
url: "addBeer.php",
data: "uID="+user+"&bID="+id+"&bName="+bname+"&bStyle="+bstyle+"&bBrewery="+brewery+"&abv="+abv+"&ibu="+ibu+"&breweryID="+breweryID,
success: function()
{
$('#sbutton').remove();
alert('Load was performed.');
},
error: function(xhr, status, error) { alert("error: " + error); } };
$.ajax(ajaxSettings2);
}
All the alerts work so I know for a fact that the information is getting passed fom the form to the function, but it fails on the ajax call to addBeer.php because it runs the error function and pop up the error alert. Unfortunetley nothing is reported in the pop up.
This is the addBeer.php file that is called to add to the database:
<?php
require_once('myConnectDB.inc.php');
require_once('page.inc.php');
session_start();
//add beer to database code
$userID = $_POST['uID'];
$beerName = $_POST['bName'];
$beerID = $_POST['bid'];
$brewery = $_POST['bBrewery'];
$style = $_POST['bStyle'];
$abv = $_POST['abv'];
$ibu = $_POST['ibu'];
$breweryID = $_POST['breweryID'];
//$icon = $_POST['icon'];
//get brewery icon
$uri3 = "http://api.brewerydb.com/v2/brewery/$breweryID?key=myKey&format=json";
$response3 = file_get_contents($uri3);
//parse xml
$myBrew = json_decode($response3);
$iconBrew = $myBrew->data->images->medium;
//add above data to database
$db = new myConnectDB();
$beerName = $db->real_escape_string($beerName);
$beerID = $db->real_escape_string($beerID);
$brewery = $db->real_escape_string($brewery);
$style = $db->real_escape_string($style);
$userID = $db->real_escape_string($userID);
$abv = $db->real_escape_string($abv);
$ibu = $db->real_escape_string($ibu);
$breweryID = $db->real_escape_string($breweryID);
$icon = $db->real_escape_string($icon);
$query3 = "INSERT INTO tableName (userID,beerID,beerName,beerStyle,beerBrewery,abv,ibu,breweryID,icon, brewIcon) VALUES ($userID, '$beerID', '$beerName', '$style' , '$brewery', '$abv','$ibu','$breweryID', '$icon', '$iconBrew')";
$db->query($query3);
?>
I took out my api key and table name for security.
I have checked the network tab in chrome under inspect element and when I click on addBeer.php call and look under headers it shows in form data that the information is being passed.
Update:
I am escaping my quotes because its being printed from php
After lots and lots of frustration, I figured out my problem. The information I was sending, I was querying from another database and all that info was not always complete.
If I clicked submit and it and one of the variables in the function call was an empty string it did not like it.
You have your method as GET in the form but POST in your Ajax.

Categories