I am trying to get the data from mysql in my Angularjs page and I am using PHP as my server side language. I am not able to get the data in my page, however I got the data from my PHP file. And if you have some alternative of it please tell me.
Here is my code:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
<h2>here is the info</h2>
<table>
<tr ng-repeat="country in countries">
<td>{{country.Empno}}</td>
<td>{{country.Ename}}</td>
<td>{{country.Job}}</td>
<td>{{country.Hiredate}}</td>
<td>{{country.Salary}}</td>
</tr>
</table>
</body>
<script>
var app = angular.module('myapp', []);
app.controller('myCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'one.php'
}).then(function successCallback(response) {
// Store response data
$scope.country = response.data;
});
}]);
</script>
</html>
here is the one.php file
<?php
$link=mysqli_connect("localhost","root","vikash","jarvis");
if($link==false){
die("you are not connected to database ".mysqli_connect_error());
}
$query="SELECT * FROM emp";
$data=array();
if($result=mysqli_query($link,$query))
{
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_assoc($result))
{
$data[]=array("Empno"=>$row['empno'],"Ename"=>$row['ename'],"Job"=>$row['job'],"Hiredate"=>['hiredate'],"Salary"=>['sal']);
}
}
else
{
echo "no records are matching";
}
}
else
{
die("could not able to execue the command ".mysqli_error($link));
}
echo json_encode($data);
mysqli_close($link);
?>
You are getting confused between absolute file paths and internet addresses. one.php is not a URL, it is a system file path.
You need to serve your one.php file via a webserver which will give is an address like http://localhost/one.php and then use that as your URL in your angularJS code.
This is because you are using angular's $http module, which is designed for IP (Internet Protocol). It is not designed for system file access.
Related
I am working with phonegap for the first time to build hybrid mobile app with back-end(php, mysql). So i am doing a test on how phonegap can connect to php on localhost to send and retrieve data. But no data was retrieved, I have reduced my codes to the this and i see no errors in both ajax call and php code. So i guess it should be the way phonegap connects to backend that i am getting wrong, please help.
html form and ajax call:
<form id="form1">
<input type="text" id="email" />
<input type="password" id="password" />
<input type="submit" name="login" id="login" value="Login">
</form>
<script type="text/javascript">
$("form").submit(function(){
var data= ("#form1").serialize();
$.post("http://localhost/securityapp/login.php",data,function(response){
alert(response);
});
});
</script>
php file:
<?php
include 'db.php';
session_start();
if ($_POST ) {
echo $_POST;
}
?>
Basically it is meant to alert to values sent to php script as the response but it is not doing so, network tab says 200 for status. what am i doing wrong? I feel phonegap isn't connecting to the url defined
This is how I solved this issue:
created a table on a database that holds the current URL/IP of the server
Created a check-url.php file, this file runs a query on the database to see IP/URL of
the server
I created a connection.js file, this file basically makes a request to a check-url.php
to get current IP of the server to use in Cordova app
check-url.php
header("Access-Control-Allow-Origin: *"); //to allow phonegap access it because of cross origin and domain restrictions
require 'db.php';
$query= "SELECT url FROM settings";
$query= mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($query);
$row= $row['url'];
echo $row; //current IP exmaple:http://127.0.0.1:80/
connection.js
//check current server ip from database
export function check_url(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "http://127.0.0.1:80/projectname/check-url.php");
httpRequest.send();
}
So any time I want to connect to backend by Cordova I import the function check-url() from connection.js into my front-end ajax request url like this:
<script type="module">
import {check-url} from './connection.js';
check-url(function(result) {
var currentIP= result;
$.ajax({
type:"POST",
url: currentIP + "projectapp/login.php",
data:data,
success: function(data){
//do something
}
});
});
</script>
Note: The URL/IP in connection.js, database, and server IP should be the same, as this helps you not to repeat IP always and also to test when using PhoneGap mobile and also when you switch to live, change it to the current IP address of your project.
I'm receiving data from an API (asana) when an event was made in my workspace via a POST method in a file called asanatarget.php
The data is correct and i can store it in file when received.
Looks like that:
{"events":"resource":xxx,"user":xxx,"type":"story","action":"added","created_at":"2019-02-20T14:48:09.142Z","parent":xxx}]}
In the same file I send the data to a new file with AJAX with GET method:
asanatarget.php
<?php
if(isset($_SERVER['HTTP_X_HOOK_SECRET'])) {
$h = $_SERVER['HTTP_X_HOOK_SECRET'];
header('X-Hook-Secret:' . $h);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$input = file_get_contents('php://input');
if ($input) {
$entries = json_decode(file_get_contents('php://input'), true);
file_put_contents('targetasanaDATA' . time() . '.txt', json_encode($entries));
?>
<script>
$( document ).ready(function() {
$.ajax({
type: "GET",
url: "/asanawebhook", // Working with laravel, the route is well defined
data: <?php echo json_encode($entries); ?>,
dataType: "json",
success: function(response){
console.log("success " + response);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
}
});
});
</script>
<?php
}
?>
</body>
</html>
When i'm directly loading asanatarget.php with test data, it's working fine and the data is passed to /asanawebhook but when the data is passed directly from the api, it's not working.
I checked and the data is always correct
Your PHP script generates only a HTML page (basically, a text).
The javascript can be interpreted and executed by a browser. But if no browser reads this page and execute it, nothing happens. PHP generates a webpage, nobody reads it, and things ends here.
You can use PHP too to send data via POST. You can build your query with http_build_query() and use file_get_contents().
I've literally checked out every single ng-repeat question out there but a lot of them don't deal with databases and people just use arrays in JS and a simple $scope.array.push("stuff") works for them.
I've tried $scope.apply, $rootScope and even calling the GET request right after a successful POST request.
I have a form with 2 text inputs, date and content.
When the submit button is pressed, date and content are added into a MySQL database using PHP.
The data is added just fine to the MySQL database and retrieving also works properly.
Even the GET request inside the successful POST request is executed.
So I don't understand why it forces me to refresh the page to see the updated ng-repeat results.
Am I missing something?
Any help or suggestions is greatly appreciated, thanks!
Relevant HTML code
<div ng-controller="insertController">
<h2> What I learned today </h2>
<form>
Date <br>
<input type="text" ng-model="date"><br><br>
Content <br>
<textarea rows="10" cols="50" ng-model="content"></textarea><br><br>
<input type="button" value="Submit" ng-click="insertdata()">
</form>
</div>
<div ng-controller="fetchController">
<span ng-repeat="item in results">
{{item.date}}<br>
{{item.content}}<br><br>
</span>
</div>
insertController.js
var app = angular.module('myApp', []);
app.controller('insertController', function($scope, $http) {
$scope.insertdata = function() {
$http({
method: 'POST',
url: 'http://localhost/storestuff/insert.php',
data: {'date':$scope.date, 'content':$scope.content, 'in':'json-format'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(res) {
console.log("Successful response", res)
$scope.date = "";
$scope.content = "";
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
alert("GOT NEW DATA");
$scope.results = response.data; // Allow angular to access the PHP output data
});
$scope.apply;
})
.catch(function(err) {
console.error("Error with POST", err);
});
}
});
insert.php
<?php
header('Access-Control-Allow-Origin: *');
$theConnection = mysqli_connect("localhost", "root", "", "storestuff");
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL.";
}
$theData = json_decode(file_get_contents('php://input'));
$date = mysqli_real_escape_string($theConnection, $theData->date);
$content = mysqli_real_escape_string($theConnection, $theData->content);
mysqli_query($theConnection, "INSERT INTO thestuff(date, content) VALUES('$date', '$content')");
mysqli_close($theConnection);
?>
fetchController.js
app.controller('fetchController', function ($scope, $http) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
$scope.results = response.data; // Allow angular to access the PHP output data
});
});
fetch.php
<?php
header('Access-Control-Allow-Origin: *'); // clientside(Node) <-> serverside(PHP)
$mysqli = new mysqli("localhost", "root", "", "storestuff");
if($mysqli->connect_error) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM thestuff";
$theData = array();
if($result = $mysqli->query($query)) {
while($row = mysqli_fetch_array($result)) {
$theData[] = array(
'date'=>$row['date'],
'content'=>$row['content']);
}
echo json_encode($theData); // Echo the output for the controller to access
$result->free(); // Free the result set
}
else {
echo "0 results.";
}
$mysqli->close(); // Close the connection
?>
The problem with this code is that you have two different controllers, both with separate scopes. Inserting/updating the $scope.results object/array in one controller, will not update the other $scope; they are separate distinct scopes, both with a copy of the data.
Using two controllers looks correct in your use case. However you should be using a service to access your remote data. Check out this answer for some advice on this https://stackoverflow.com/a/20181543/2603735.
Using a service like in that answer, will allow you to store the array/object of remote data in one place, and reference the SAME object from both controllers. Therefore updating from one controller, will also update the other.
For anyone who will ever stumble on my question, I don't want to just leave my broken code there with no answer but neither can I edit the question and put in my answer cause that would defy the purpose of StackOverflow.
So here is my answer to my own question.
I had to make quite a few changes to what I had before. The biggest change by far, is how I handled the data that was returned by fetch.php.
Instead of just taking the output into $scope.results = response.data;, which would work fine if I wasn't dynamically adding to the database, but for this case, I ended up using a service. (Thanks #jayden-meyer for suggesting Angular services.)
The service allowed me to access the same array from my insertController and from my fetchController instead of having a copy of the same array in both controllers which was my problem.
No changes in the HTML code.
No changes to insert.php.
No changes to fetch.php.
insertController.js
I removed the extraneous GET request I had inside the .then method which was completely unneeded since I can just push to the existing array.
(Thanks #charlietfl for the tip)
Instead I added resultsService.addItem($scope.date, $scope.content); inside of the .then method.
I also added my service as an argument.
app.controller('insertController', function($scope, $http, resultsService) {
result.js
app.service('resultsService', function() {
var results = new Array();
var addItem = function(date, content) {
var obj = new Object();
obj["date"] = date;
obj["content"] = content;
results.push(obj);
}
var getItems = function() {
return results;
}
return {
addItem: addItem,
getItems: getItems
};
});
fetchController.js
var size = 0;
var count = 0;
app.controller('fetchController', function ($scope, $http, resultsService) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
size = (response.data).length;
while(count < size) {
var date = response.data[count].date;
var content = response.data[count].content;
resultsService.addItem(date, content);
count++;
}
size = 0;
count = 0;
$scope.results = resultsService.getItems();
});
});
In my AngularJS app, the data entered into the form are not stored in the MySQL database after hitting the submit button. An alert after successful form data submit however indicates that it is working.
Also, after hitting the submit button, I want the app to proceed to the next view (#/setup-step2) - however it remains at step1.
html partial (#/setup-step1):
<form ng-submit="submitForm1()">
Job title: <input type="text" name="jobtitle" ng-model="formData1.jobtitle">
Vacancy ID: <input type="text" name="vacancyid" ng-model="formData1.vacancyid">
<button type="submit" class="animatedbutton"> Proceed </button>
</form>
controller.js:
var ctr = angular.module('myApp.controller', []);
ctr.controller
('Step1Controller', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$scope.formData1 = {};
$scope.submitForm1 = function() {
$http({
method: 'POST',
url: 'php/setup-step1.php',
data: $.param($scope.formData1),
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log(data);
alert("It worked");
})
.error(function(data) {
console.log(data);
alert("It didn't work");
})
}
}]);
setup-step1.php in folder /php:
<?php
include_once('db.php');
// Check connection
if(mysqli_connect_errno())
{echo '<p>Connection to MySQL server failed: '.mysqli_connect_error().'</p>';}
else
{echo '<p>Connection to MySQL server successful.</p>';}
$_POST = json_decode(file_get_contents("php://input"), true);
if (empty($_POST['jobtitle']))
{$errors['jobtitle'] = 'Job title is required.';}
else {
// Escape user inputs for security
$jobtitle = $_POST['jobtitle'];
$vacancyid = $_POST['vacancyid'];
$data = "INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle','$vacancyid')";mysql_query("INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle', '$vacancyid')");}
if ($connect->query($data) === TRUE)
{$conn->close();}
else
{echo "Error: " . $sql . "<br>" . $conn->error;}
exit();
?>
First,
Be sure that you enable the cors before performing any request to the server.When you are working with angularjs this usually means that you are making cors requests to the server.If you didn't enable cors option you cannot call any method from the server since it is not allowed.
Second,
just keep php code inside your setup-step1.php.You don't need any html code there since it will return result of your requet only.
Third,
As I know you cannot change location of the webpage from erver because server domin and website domains are different.You need to redirect the user to another page in angularjs. You can find the ways of redirecting in angularjs by using $location or $state.
I found the answer myself. The problem was incorrect php and mysql syntax. Updated the code the way it works now.
I am developing a social network web site using Symfony2. In fact, I would like to know how I can get an array field value from a PHP file using jquery/Ajax in Symfony2. Among the files that I have in my project folder there are two files: test.html.twig and moslem1.php. The code of each of that two files is below:
The code of test.html.twig:
<html>
<head>
</head>
<body>
<script src="{{asset('bundles/moslemtest/src/jquery.min.js')}}" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: '{{asset('bundles/moslemtest/phptest/moslem1.php')}}',
type: 'POST',
dataType: 'JSON',
success: function(data1) {
var id=data1.id;
document.write(id);
}
});
});
</script>
</body>
</html>
The code of moslem1.php:
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)) {
$notification = array('id'=>$row['Id'],'subject'=>$row['Subject'],'location'=>$row['Location'],'description'=>$row['Description'],'starttime'=>$row['StartTime'],'endtime'=>$row['EndTime']);
}
echo json_encode($notification);
mysqli_close($con);
?>
The issue is whenever I run the file test.html.twig it displays the out below:
undefined
What is strange is that it works when I put the code of the file test.html.twig in a html file. in fact I created two other files (not in Symfony2) which are t1.html and moslem1.php. their codes are as below:
The code of t1.html:
<html>
<head>
</head>
<body>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'moslem1.php',
type: 'POST',
dataType: 'JSON',
success: function(data1) {
var id=data1.id;
document.write(id);
}
});
});
</script>
</body>
</html>
The code of moslem1.php:
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)) {
$notification = array('id'=>$row['Id'],'subject'=>$row['Subject'],'location'=>$row['Location'],'description'=>$row['Description'],'starttime'=>$row['StartTime'],'endtime'=>$row['EndTime']);
}
echo json_encode($notification);
mysqli_close($con);
?>
As I said above, it works when I deal with a HTML file, but as I work on Symfony2 I have to use files with "html.twig" extension for view(output). So my question is what shall I do to make it works correctly with my twig file?
Thanks in advance.
It's a very bad idea to put the php file into the bundles folder, it's a huge security issue. If you want an AJAX response then put it into the Controller.
Create a new action in the Controller as you normally do. Write the AJAX action and give back a JSONResponse as a response.
/**
* Return an ajax response
*/
public function ajaxAction(){
// do the controller logic
// $response is an array()
return new JSONResponse($response);
}
Then in jQuery ajax set the url like this:
$.ajax({
url: 'url/to/your/controller', // If you use the FOSJsRoutingBundle then it will be Routing.generate('route_name')
type: 'POST',
dataType: 'JSON',
success: function(data1) {
var id=data1.id;
document.write(id);
}
});
In the new action you can use the EntityManager to access your database.
Here is a good article about this issue: http://symfony2forum.org/threads/5-Using-Symfony2-jQuery-and-Ajax
You should also consider to use the FOSJsRoutingBundle for javascript routing.
It's a very great bundle that allows you to generate routes in javascript files as you can do it in twig with the path('path_name') command.
Here is the GitHub project for this bundle: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle
Try to understand the Symfony Request -> Response process, because if you don't follow it, it will cause serious problems for you.
http://symfony.com/doc/current/book/http_fundamentals.html
http://symfony.com/doc/current/book/page_creation.html