Angular $http - function/response undefined - php

I've been unable to retrieve data from a json or php file because angular keeps yelling at me that either the function or response is undefined.
I want to pull up the navigation items from MySQL, when it failed to load php I've put the contents in a regular json file to see what was the problem it seems something in angular itself.
PHP:
<?php
header('Content-type:application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'SELECT * FROM navigation';
$result = $conn->query($sql);
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
?>
Which results in:
[{"nav_id":"0","nav_name":"Home","nav_link":""}, {"nav_id":"1","nav_name":"Contact","nav_link":"contact"}]
So far so good?
Here's my angular code that gets the file:
(function() {
var app = angular.module("headerControl", []);
app.directive("headerNavigation", function() {
return {
retrict:'E',
templateUrl:'views/partials/header-navigation.html'
};
});
app.controller("navController", function($scope, $http) {
$scope.navlist = {};
$http.get('phpservices/nav.php')
.success(function(response) {
alert('success');
})
.error(alert('error'));
});
})();
When I load the page it first gives me the error response and after that the success response... in the console angular tells me this:
Error: [ng:areq] http://errors.angularjs.org/1.4.2/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20undefined
whats wrong about this? I can't seem to figure it out...

The problem is that you are not passing error callback function properly. It should be:
.error(function() {
alert('error')
});
Otherwise you just invoke alert immediately (note ()) and since it doesn't return anything (so it "returns" undefined) error handler receives undefined in it. However, it expects a function. That's why you get this error.

Related

Migrating from xamp to raspberry pi apache server

I'm currently working on a project. It's almost done, there's only one big problem. I tested my code all the time with a xamp server on my computer, which worked perfectly fine. the goal is to run it (apache server, mysql database) on my raspberry pi. Now my project is finished, I came figured out the problem why my code doesn't work on my raspberry (at least not as I expected).
I turned on error reporting in PHP and came to this error message:
Notice: Trying to get property of non-object in /var/www/html/test.php on line 41
I use this function for all my SQL queries. Can someone provide a solution so I don't have to rewrite the whole code? Thanks in advance!
PS: this is just a piece of the code (the function where I pull the data out of the database + example of one of my queries)
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****"; // I just dont want to give my sql database password its nothing wrong ;)
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
print_r("ok connection");
function sqlquery ($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //line 41 in my code ==> do a while loop to fetch all data to an array
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
}
$stateLoop = "1";
}
else { // if there are no results
}
}
$sql1 = "SELECT stopTijd FROM gespeeldeTijd WHERE naam = 'thomas' ORDER BY ID DESC LIMIT 1"; // get data with SQL query
sqlquery($sql1,$conn,"stopTijd");
if ( $stateLoop == "1") {
print_r("ok loop");
$date1 = $myArray["0"];
print_r($date1);
$myArray = [];
$stateLoop == "0";
}
}
?>
It pretty much looks like you have some sql error in your query; check if your field names in your database match those on the raspberry.
Seeing through your code it seems like you are pretty new to programming (which is no bad thing, I was once, too). So I made a few more modifications to your code showing you the prettiness of PHP
use "return" in function sqlquery instead of globals
check for errors after executing the code
use only one variable to check if data was loaded
I commented everything I changed
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "test";
// Your function with some modifications
function sqlquery($sql, $conn, $naamtabel) {
$result = $conn->query($sql);
// Check for errors after execution
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
// If we have no data, we simply return an empty array
if($result->num_rows == 0)
return array();
// This is a variable we store the data we processed in
// We will return it at the end of our function
$myArray = null;
// Read all field data and store it $myArray
while($row = $result->fetch_assoc())
$myArray[] = $row[$naamtabel]; // if you use "$naamtabel" here, PHP first needs to interpret the string (= slower)
return $myArray;
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Because we use "die" above we don't need an "else"-clause
print_r("ok connection");
$sql = "SELECT `stopTijd` FROM `gespeeldeTijd` WHERE `naam` = 'thomas' ORDER BY `ID` DESC LIMIT 1";
$data = sqlquery($sql, $conn, "stopTijd");
// $data will contain $myArray (see "return $myArray" in function sqlquery)
// Instead checking for $stateLoop being "1" we check if $data contains any values
// If so, we fetched some data
if(sizeof($data) >= 1) {
print_r("ok loop");
$date1 = $data[0]; // No "0", because we are trying to get index 0
print_r($date1);
$data = array(); // Are you sure this is nessecary?
} else {
echo 'No data returned from query!';
}
?>
Note: code tipped on my smartphone -> untested!
If you don't want to adapt the code I wrote, the important part for this question is:
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
Your error Notice: Trying to get property of non-object means "you are trying to get num_rows from $result, but $result is not an object, so it can't contain this property".
So to figure out why $result is not an object, you need to get the error from $conn->query - my code above probably won't fix your error, but it will display you one you can work with (+ it's too long for a comment)
If you have a more detailed error message and you can't solve it on your own, feel free to comment; I will update my answer!

Why isn't the response from Ajax showing?

I'm passing values using ajax from a web page to a php file. The purpose is to pass database credentials to be able to test the database connection and get the result in return. I'm passing server name, username and password to the php file. The problem is that I'm not able to see the database connection response from the php file.
This is how I call the function within document ready:
$('#dbconn').click(db_connect)
Here is my ajax code:
function db_connect(dbserver, dbuser, dbpassword) {
var dbserver;
var dbuser;
var dbpassword;
dbserver = $('input:dbserver').val();
dbuser = $('input:dbuser').val();
dbpassword = $('input:dbpassword').val();
$.ajax({
url : "script/create_db.php",
type : "POST",
cache : false,
data : {
dbserver : dbserver,
dbuser : dbuser,
dbpassword: dbpassword,
success: function(result){alert ("response")}
}
});
};
And this is my php code:
$servername = $_GET["dbserver"];
$username = $_GET["dbuser"];
$password = $_GET["dbpassword"];
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "Connection succsess";
}
Any help is highly appreciated
success: function(result){alert ("response")}
When you get the response you alert the string "response".
You ignore the value of result entirely.
You don't see the response because you aren't looking for it.

XML Parsing Error: no root element found Location

So I'm making a simple login/registration web application but I keep getting the following error:
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:
and
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:
here is my login.php
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header('HTTP/1.1 500 Bad connection to Database');
die("The server is down, we couldn't establish the DB connection");
}
else {
$conn ->set_charset('utf8_general_ci');
$userName = $_POST['username'];
$userPassword = $_POST['userPassword'];
$sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
}
echo json_encode($response);
}
else {
header('HTTP/1.1 406 User not found');
die("Wrong credentials provided!");
}
}
$conn->close();
?>
I've done some research about xml parsing errors but I still cant manage to make my project work, ive tried with Google Chrome and Firefox
AHA! Got this today for a reason which will make me look pretty silly but which might one day help someone.
Having set up an Apache server on my machine, with PHP and so on... I got this error... and then realised why: I had clicked on the HTML file in question (i.e. the one containing the Javascript/JQuery), so the address bar in the browser showed "file:///D:/apps/Apache24/htdocs/experiments/forms/index.html".
What you have to do to actually use the Apache server (assuming it's running, etc.) is go "http://localhost/experiments/forms/index.html" in the browser's address bar.
In mitigation I have up to now been using an "index.php" file and just changed to an "index.html" file. Bit of a gotcha, since with the former you are obliged to access it "properly" using localhost.
I had same situation in Spring MVC Application as it was declared as void, changing it to return String solved the issue
#PostMapping()
public void aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
}
To
#PostMapping()
public String aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
return "justReturn something";
}
Assuming you are working with javascript, you need to put a header in front of echoing your data:
header('Content-Type: application/json');
echo json_encode($response);
Make sure you're php server is running and that the php code is in the appropriate folder. I ran into this same issue if the php was not there. I also recommend putting your html in that same folder to prevent cross-origin errors when testing.
If that is not the issue, ensure that every SQL call is correct in the php, and that you are using current php standards... Php changes quickly, unlike html, css and Javascript, so some functions may be deprecated.
Also, I noticed that you may not be collecting your variable correctly, which can also cause this error. If you are sending variables via form, they need to be in proper format and sent either by POST or GET, based on your preference. For example, if I had a login page for a maze game:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form class="modal-content animate" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" id="usernameinput" placeholder="Enter username" name="uname" required>
<label><b>Password</b></label>
<input type="password" id="passwordinput" placeholder="Enter Password" name="psw" required>
<button onclick="document.getElementById('id01').style.display='block'">Sign Up</button>
<button type="button" id="loginsubmit" onclick="myLogin(document.getElementById('usernameinput').value, document.getElementById('passwordinput').value)">Login</button>
</div>
</form>
JavaScript
function myLogin(username, password){
var datasend=("user="+username+"&pwd="+password);
$.ajax({
url: 'makeUserEntry.php',
type: 'POST',
data: datasend,
success: function(response, status) {
if(response=="Username or Password did not match"){
alert("Username or Password did not match");
}
if(response=="Connection Failure"){
alert("Connection Failure");
}
else{
localStorage.userid = response;
window.location.href = "./maze.html"
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
var response = xhr.responseText;
console.log(response);
var statusMessage = xhr.status + ' ' + xhr.statusText;
var message = 'Query failed, php script returned this status: ';
var message = message + statusMessage + ' response: ' + response;
alert(message);
}
}); // end ajax call
}
PHP
<?php
$MazeUser=$_POST['user'];
$MazePass=$_POST['pwd'];
//Connect to DB
$servername="127.0.0.1";
$username="root";
$password="password";
$dbname="infinitymaze";
//Create Connection
$conn = new MySQLi($servername, $username, $password, $dbname);
//Check connetion
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
echo json_encode("Connection Failure");
}
$verifyUPmatchSQL=("SELECT * FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$result = $conn->query($verifyUPmatchSQL);
$num_rows = $result->num_rows;
if($num_rows>0){
$userIDSQL =("SELECT mazeuserid FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$userID = $conn->query($userIDSQL);
echo json_encode($userID);
}
else{
echo json_encode("Username or Password did not match");
}
$conn->close();
?>
It would help if you included the other parts of the code such as the html and JavaScript as I wouldn't have to give my own example like this. However, I hope these pointers help!

How to fetch data from a PHP page that encodes JSON?

Please help me guys. I've been figuring how to solve this problem for several hours already but I still don't know how. ><
This is my php page that displays value in JSON Format.
jsonfile.php :
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","online_evaluation_revised") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from tblaccount";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
it display something like this:
[{"account_id":"89","username":"2012100014","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"90","username":"2012102400","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"91","username":"2012101087","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"92","username":"2011102090","password":"25d55ad283aa400af464c76d713c07ad"}]
however, I don't how to fetch/transfer these data to my services.js and controller.js.
Here is my services.js:
app.service("myService", function($http,$q)
{
var deferred = $q.defer();
$http.get('resources/json/jsonfile.php').then(function(data)
{
deferred.resolve(data);
});
this.getAccounts = function()
{
return deferred.promise;
}
})
here is my controller.js:
.controller("myCtrl",function($scope,myService)
{
var promise = myService.getAccounts();
promise.then(function (data)
{
$scope.allAccounts = data;
var accounts = data;
console.log($scope.allAccounts);
});
})
Whenever I use the data using the format above, it gives me something like this in the console log:
Object {data: "<?php
↵ //open connection to mysql db
↵ $con…db connection
↵ mysqli_close($connection);
↵?>", status: 200, config: Object, statusText: "OK"}
Weird because if I use the format above when fetching a file in JSON format (not in PHP), it gives me array objects.
For This To Access Data in Js File YOu Have to use ajax.
call ajax when ever you want data.
for More Details you refer below link.
http://www.w3schools.com/php/php_ajax_database.asp
Try :
$http.get('resources/json/jsonfile.php',{ responseType : 'json' })

Angular $http post not working with a https url

In my ionic app I have the following code:
$http({ url: "http://someurl/script.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({param1:$localStorage.test.paramtest})
}).success(function(data) {
//console.log(data);
$scope.data = data;
}).error(function(data) {
//console.log("error:" + data);
alert("error:" + data);
})
.finally(function (data) {
//console.log("ok:" + data);
alert("ok:" + data);
});
The code above is working fine and I'm able to post en retrieve data from my database.
When I change the http:// url to a https:// url all of a sudden it is not working anymore. The error function gives me the error "error: null"
When I manually define the id in the php script and run de script with the https url in my browser it is also working.
This is mij script.php code:
<?php
//variables
$id = $_POST["param1"];
//$id = "12047";
// databse connection variables
$hostname = "...";
$username = "...";
$password = "...";
$database = "...";
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully<br>";
// show all database entries
$sql = "SELECT * FROM table1 WHERE field1_id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
// Add all rows to an array
$rows[] = $row;
}
// Json encode the full array
echo json_encode($rows);
} else {
//echo "0results";
}
$conn->close();
?>
I have setup my hosting to work with https and installed a SSL certificate on my server.
I found out that my hosting provider doesn't support SSL database connections in there hosting packages. It appears that this is only possible with dedicated servers.

Categories