I am new to Angular2. I have one PHP file and would like to fetch content from PHP file in Angular component. Following is my code I have written by taking references. I am not able to figure out what is the issue as I am not getting any error in console nor desired output.
PHP code - 'getArea.php'
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db("mydb", $link);
$data=array();
$result = mysql_query("SELECT * FROM dam_color", $link);
$num_rows = mysql_num_rows($result);
for ($i=0; $i<mysql_num_rows($result); $i++)
{
$row = mysql_fetch_assoc($result);
$data['success'] = true;
$data['areaname'] = $row['area_name'];
}
echo json_encode($data);
?>
Angular Component - php-form.component.ts content
export class PhpFormComponent {
msg = "Welcome";
public data;
constructor(private http:Http){ }
ngOnInit(){
this.getData();
}
getData(){
this.http.get('http://localhost/myapi/getArea.php')
.map(res => res.json())
.map(res => {
if(res.success)
{
this.msg="Fetched data";
}
else
{
this.msg="Error in fetching data";
}
})
.subscribe(
data =>this.getdata = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
}
}
Related
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 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);
});
}
}
}]);
My app makes a call from Flash to get back list of countries but in my PHP the result is returning empty, i have created the table using phpMyAdmin and i have two rows in there.
Here is the code Action script 3:
package {
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.events.EventDispatcher;
public class SQL extends EventDispatcher{
var url:String = "";
var urlRequest:URLRequest;
public function SQL() {
// constructor code
}
public function Post(url:String, urlVaribles:URLVariables = null):void{
this.url = url;
this.urlRequest = this.urlRequestObj();
var loader:URLLoader = new URLLoader();
if(urlVaribles){
this.urlRequest.data = urlVaribles;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
}
loader.addEventListener(Event.COMPLETE, dataPostOnLoad);
loader.load(this.urlRequest);
}
public function Get(url:String, urlVaribles:URLVariables = null):void{
this.url = url;
this.urlRequest = this.urlRequestObj();
var loader:URLLoader = new URLLoader();
if(urlVaribles){
this.urlRequest.data = urlVaribles;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
}
loader.addEventListener(Event.COMPLETE, dataGetOnLoad);
loader.load(this.urlRequest);
}
private function urlRequestObj():URLRequest{
return new URLRequest(this.url);
}
private function dataPostOnLoad(evt:Event):void{
var evt2:SQLEvent=new SQLEvent(SQLEvent.POST_COMPLETE, evt.target.data);
dispatchEvent(evt2);
}
private function dataGetOnLoad(evt:Event):void{
trace("IN GET " + evt.target.data);
var evt2:SQLEvent=new SQLEvent(SQLEvent.GET_COMPLETE, evt.target.data);
dispatchEvent(evt2);
}
}
}
Code for the call from Flash:
import fl.motion.MotionEvent;
var sql:SQL = new SQL();
sql.addEventListener(SQLEvent.GET_COMPLETE, dataGetResponse);
sql.Get("http://localhost:8888/MAMP/HUGT/getCountriesDP.php");
mc_ddScroll.visible = false;
mc_ddScrollButton.addEventListener(MouseEvent.CLICK, clickScrollButton);
function dataGetResponse(e:SQLEvent):void {
trace("Countries " + e.params);
}
function clickScrollButton(e:MouseEvent):void{
if(mc_ddScroll.visible){
mc_ddScroll.visible = false;
}
else{
mc_ddScroll.visible = true;
}
}
And finally the PHP script:
getCountriesDP.php
<?php
include "connect.php";
$result = mysql_query($conn,"SELECT * FROM C_Countries");
if(mysql_num_rows($result)){
echo '{"countries":[';
$first = true;
$row=mysql_fetch_assoc($result);
while($row=mysql_fetch_row($result)){
// cast results to specific data types
if($first) {
$first = false;
} else {
echo ',';
}
echo json_encode($row);
}
echo ']}';
} else {
echo "[]";
}
mysqli_close($conn);
?>
Connect.php
<?php
$conn = mysql_connect("localhost","root","root");
mysql_select_db("HUGT", $conn);
// disable reporting errors for security reason
error_reporting(0);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
?>
I just changed my php script to this:
<?php
$conn = mysqli_connect("localhost","root","root", "HUGT");
//mysql_select_db("HUGT", $conn);
// disable reporting errors for security reason
error_reporting(0);
// Error checking
if(mysqli_connect_errno()) {
die('Could not connect ' . mysqli_connect_error());
}
?>
and:
<?php
include "connect.php";
$result = mysqli_query($conn,"SELECT * FROM C_Countries");
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($conn);
?>
I'm trying to develop an application which gets the the response from the MySQL database using ajax post and update in list selector, but the list is displaying empty, can some one help me out from this please.....
code for .js:
SecondAssistant.prototype.setup = function() {
this.selectorChanged = this.selectorChanged.bindEventListener(this);
Mojo.Event.listen(this.controller.get('firstselector'), Mojo.Event.propertyChange, this.selectorChanged);
this.names = [];
try {
new Ajax.Request('http://localhost/projects/testingasdf.php', {
method: 'post',
parameters: {
'recs': getallrecords,
'q': q
},
evalJSON: 'true',
onSuccess: function(response){
var json = response.responseJSON;
var count = json.count - 1;
for(i=0; i<count; i++){
this.names.push({
label: json[i].name,
value: '0'
});
}
this.controller.modelChanged(this.model);
}.bind(this),
onFailure: function(){
Mojo.Controller.errorDialog('Failed to get ajax response');
}
});
}
catch (e){
Mojo.Controller.errorDialog(e);
}
this.controller.setupWidget("firstselector",
this.attributes = {
label: $L('Name'),
modelProperty: 'currentName'
},
this.model = {
choices: this.names
}
);
};
code for php:
<?php
header('Content-type: application/json'); // this is the magic that sets responseJSON
$conn = mysql_connect('localhost', 'root', '')// creating a connection
mysql_select_db("test", $conn) or die('could not select the database');//selecting database from connected database connection
switch($_POST['recs'])
{
case'getallRecords':{
$q = $_POST['q'];
//performing sql operations
$query = sprintf("SELECT * FROM user WHERE name= $q");
$result = mysql_query($query) or die('Query failed:' .mysql_error());
$all_recs = array();
while ($line = mysql_fetch_array($result,MYSQL_ASSOC)) {
$all_recs[] = $line;
}
break;
}
}
echo json_encode($all_recs);
// Free resultset
mysql_free_result($result);
// closing connection
mysql_close($conn);
?>
I would move the model updating code out of the SecondAssistant.prototype.setup method and have it fire somewhere in SecondAssistant.prototoype.activate.
Also call modelChanged
this.controller.modelChanged(this.model);
There is a typo on bindEventListener - should be bindAsEventListener and the return of the bind should be a different object:
this.selectorChangedBind = this.selectorChanged.bindAsEventListener(this);
I run a mysql query and get the results successfully. However, I cannot read the elements of the array from javascript side. Can anyone help??
//JAVASCRIPT makes a request
function profiles(){
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "text");
}
function fillProfileCombo(res) {
alert(res);
}
//dbConn.php takes the request , gets the result and passes via echo as it is shown as follows:
//RETURN PROFILE LIST
else if (!strcmp($opType, "getProfileList")){ //no param is coming
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
mysql_select_db( $db_name ) or die( mysql_error() );
$profiles = mysql_query(" SELECT DISTINCT profileName FROM `map_locations` ");
$row = mysql_fetch_array($profiles);
/*while() {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
*/
//$data = array();
//$row = mysql_fetch_assoc($profiles)
/*while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}*/
if ($row){
echo $row;
} else {
echo "ERROR occured";
}
}
//PROBLEM:
//when I change echo $row; into echo $row[0]; , I see the first element in an alert box...query is definitely working..
//however when I change res to res[0], it does not show anything - which is normal because I do not know how to cast php array into js array..
function fillProfileCombo(res) {
alert(res[0]); // does not work..
}
I do not want to use json by the way... I am not very good at. I do not want to mess it up. Any suggestion and help is appreciated.
// PHP
$res = array();
while ($row = mysql_fetch_array($profiles)) {
$res[] = $row['profileName'];
}
header('Content-type: application/json');
echo json_encode($res);
// JavaScript
$.post('dbConn.php', { opType:"getProfileList" }, function(data) {
alert(data.length + " profiles returned");
}, "json");
Thanks Phil..This works now.. I followed your way by changing sth.. Maybe it was working but I couldnt run it. Very similar except a couple of changes. I changed it as like this:
//PHP
$data = array();
while($row = mysql_fetch_assoc($profiles))
{
$data[] = $row;
}
if ($data){
echo json_encode($data);
} else {
echo $data;
}
//JS
function profiles(){
//$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
}
function fillProfileCombo(data) {
alert(data[1].profileName);
}