I'm using angularjs for my app and php to fetch data from server...
The php file gets all the needed variables but when i'm trying to see the answer using angular I only get [object Object], [object Object] and so on...
Any ideas?
Thanks!
Angular code:
app.controller('FormController', ['$scope', '$http', function($scope, $http){
$scope.submit = function() {
var data = {
'days': $scope.days,
'age_18': $scope.age_18,
'age_13_17': $scope.age_13_17,
'age_8_12': $scope.age_8_12,
'age_3_7': $scope.age_3_7,
'water': true,
'outside': true
}
$http.post('php/get_data.php', data)
.success(function(data, status, headers, config) {
alert(data);
})
}
}])
Php Code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "nathan", "nathan", "nathan");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$age_18 = $request->age_18;
$age_13_17 = $request->age_13_17;
$age_8_12 = $request->age_8_12;
$age_3_7 = $request->age_3_7;
$days = $request->days;
$water = $request->water;
$outside = $request->outside;
$result = $conn->query("SELECT id, modal_name, name,('$age_18'*18_rating + '$age_13_17'*13_17_rating
+ '$age_8_12'*8_12_rating + '$age_3_7'*3_7_rating) as total
FROM parks
WHERE (water_park LIKE '$water' OR water_park LIKE 0)
and (outside_orlando LIKE '$outside' OR outside_orlando LIKE 0)
ORDER BY total DESC");
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {$outp .= ",";}
$outp .= '{"name":"' . $rs["name"] . '",';
$outp .= '"modal_name":"' . $rs["modal_name"] . '",';
$outp .= '"id":"' . $rs["id"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
?>
The output you get is an array of objects.
Try the following :
$http.post('php/get_data.php', data)
.success(function(data, status, headers, config) {
for (var j = 0; j < data.length; j++) {
alert(data[j].name);
}
})
Please check this and tell me if it is working for you:
$http.post('php/get_data.php', JSON.stringify(data))
.success(function(data, status, headers, config) {
alert(data);
})
Related
I get an error which doesn't say anything to me. I'm kinda new to Angular so it might be a really stupid error but I can't figure out.
It says there's a Syntax Error:
SyntaxError: Unexpected token /
at Object.parse (native)
at fromJson (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:1252:14)
at defaultHttpResponseTransform (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9414:16)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9505:12
at forEach (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:336:20)
at transformData (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9504:3)
at transformResponse (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:10276:23)
at processQueue (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:14745:28)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:14761:27
at Scope.$eval (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:15989:28)
My html Code where I'm calling the controller:
<div ng-controller="dbTestCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
My Angular controller:
module.controller('dbTestCtrl', function($scope, $http) {
$http.get(PHP_API + "datahandler/dbTest.php")
.then(function (response){
$scope.names = response.data.records;});
});
And my php file which is working as far as i can see:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "cmweb");
$result = $conn->query("SELECT loginName, userID, createDate FROM users");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {
$outp .= ",";
}
$outp .= '{"Name":"' . $rs["loginName"] . '",';
$outp .= '"ID":"' . $rs["userID"] . '",';
$outp .= '"Created":"'. $rs["createDate"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
As I said I'm really new to angular and I just couldn't figure out by myself so it would be great if someone could help me out :)
Thx
May be your json format is wrong. Try using json_encode to avoid writing all those quotes and brackets by yourself.
$outp = array();
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = array('Name' => $rs["loginName"],
'ID' => $rs["userID"],
'Created' => $rs["createDate"]);
}
echo json_encode(array('records' => $outp));
On my website, I'm using ajax to send data to an external php script, which queries a database and returns the result to the website. I ran into the problem, that I can only return strings with php, but I want to return an array of objects (which is valid json). My code looks like this at the moment:
php
$connection = mysqli_connect($adrs, $usr, $pw, $db);
if(mysqli_connect_errno()) {
die(mysqli_connect_error());
}
if($_GET["feed"] == "hausaufgaben") {
$query = "SELECT fach, aufgabe, datum FROM hausaufgaben WHERE fachgruppe != '";
if($_GET["fremdsprache"] == "latein") {
$query .= "französisch";
}
else {
$query .= "latein";
}
$query .= "' AND fachgruppe != '";
if($_GET["englisch"] == "koch") {
$query .= "schopper";
}
else {
$query .= "koch";
}
$query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";
$result = mysqli_query($connection, $query);
$data = [];
while($row = mysqli_fetch_row($result)) {
$object = '{"fach": "' . $row[0] . '", "datum": "' . $row[2] . '", "aufgabe": "' . $row[1] . '"}';
array_push($data, json_decode($object));
}
echo $data;
}
ajax
$.ajax({
type: "GET",
url: "php/getFeed.php",
cache: false,
dataType: "json",
data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data, textStatus, jqXHR) {
alert(typeof(data));
this.hausaufgaben = data;
})
.fail(function(jqXHR, textStatus, error) {
alert("error: " + error);
});
It always throws the error "Unexpected token A". I got it to return each single line in the array as string, but I can't use a string in my website. My problem is, that I can't echo an array of objects with php and get the array with ajax.
Instead of trying to build a json string yourself you can do it all much easier by building the $data array using PHP data structures and then using json_encode() to convert it all to a JSON string for sending to your javascript.
Reference json_encode and json_decode
Like this :-
$data = [];
while($row = mysqli_fetch_object($result)) {
$data[] = $row;
}
echo json_encode($data);
You will also have to change you javascript to process an array of objects rather than a string, but that should be easy
So basically i have json file made from SLQ database by PHP script
Geting angular to read json and binds to scope
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://kserwach.nazwa.pl/extremerun/data.php")
.success(function (response) {$scope.names = response.records;});
});
You can look at json file by simply enterning this link
[http://kserwach.nazwa.pl/extremerun/data.php][1]
My problem is that, while i put any "new line" in SQL angular crashes. How can i make angular to not crash while someone press "enter button" while writing new desc? Or else how to make json file to replace this "enter" with some html tag, and then how to make angular to read this html tag?
This is how i read mySQL data
<?php
$user='user_name';
$password='password';
$dbname='db_name';
$host='host';
try
{
$db = new PDO('mysql:host='.$host.';dbname='.$dbname.';',$user,$password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>"; die();
}
$stmt = $db-> query('SELECT name,description,surname,photo FROM mates');
$temp = 0;
$outp = "";
foreach($stmt as $row)
{
if($temp == 0) {
$outp .= '{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
$temp = 1;
} else {
$outp .= ',{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
}
}
$outp ='{"records":['.$outp.']}';
echo($outp);
?>
And then, sorry for my bad english. Just not primary, or even secondary language.
i've encountered a problem changing php variable that is respobsible for showing content
here's my JS code:
$(document).ready(function(){
var ajax = 1;
var button;
$('.tagbtn').click(function(){
button = $(this);
$(this).siblings("ul").slideToggle('slow', function(){
$('.selection').click(function(){
var number = $(this).children('h1').html();
button.html(number);
$(this).parent('ul').slideUp('slow');
var data = 'number=' + number;
$.ajax({
type:'POST',
//url: 'ajax-realizacje.html',
url: 'aktualnosci.class.php',
async: true,
data: data,
success: function(){
limit_page = number;
}
});
});
});
});
});
limit_page is the variable from the external file, which i am trying to change
and here's my php function that loads the content:
function LoadArticles($pages = 0, $page = 0) {
$start = ($pages - $page) * $this->limit_page;
$q = "SELECT p.*, d.title, d.title_url, d.content, d.content_short, d.tagi FROM " . $this->table . " p ";
$q .= "LEFT JOIN " . $this->tableDescription . " d ON p.id=d.parent_id ";
$q .= "WHERE d.language_id=? AND p.active=1 AND d.active=1 ";
$q .= "ORDER BY p.date_add DESC, p.id DESC ";
$q .= "LIMIT ?,? ";
$params = array(
array(dbStatement::INTEGER, _ID),
array(dbStatement::INTEGER, $start),
array(dbStatement::INTEGER, $this->limit_page)
);
$statement = $this->db->query($q, $params);
$articles = array();
while ($row = $statement->fetch_assoc()) {
$row['content'] = strip_tags($row['content']);
$row['url'] = BASE_URL . '/' . $this->modul . '/' . $row['title_url'] . '.html';
$row['photo'] = $this->getPhotoUrl($row['photo']);
$row['date_add_org'] = $row['date_add'];
if (!empty($row['tagi'])) {
$row['tagi_url'] = explode('|', str_replace(' ', '-', $row['tagi']));
$row['tagi'] = explode('|', $row['tagi']);
}
$row['date_add'] = date("j", strtotime($row['date_add_org'])) . " " . miesiac2(date("n", strtotime($row['date_add_org']))) . " " . date("Y", strtotime($row['date_add_org'])) . "r";
$articles[] = $row;
}
return $articles;
}
the problem is that ajax doesn't seem to change that php variable
would appreciate your help
if it's just a text on a file you can read it by using:
$this->limit_page = file_get_contents('path/to/file');
I have searched stackoverflow for similar questions but nothing helped. This is my ajax call to adding.php file. I called this on jquery keyup event. When I inspect in browser I see php file returning response. However, the data in response never reaches success function of ajax.
$.ajax({
url: "anding.php",
type: "POST",
dataType: 'json',
data: JSON.stringify({mycol:mycol,mycolval:mycolval,string:string}),
contentType: 'application/json',
success: function(data){
alert(data);
var output = data.substring(0, data.indexOf('arventures'));
last = data.substring(data.indexOf('arventures') + 10);
last--;
$('.remove').remove();
$('.main_tr').after(output);
if (output == '' || output == null) {
$('.message').html('No results found.');
}
else {
$('#row1').addClass('highlight');
}//highlight row1 by default
}
});
This is my php file which returns the response. I have pasted the entire code because I dont know which part is causing the issue.
adding.php
<?php
include 'connection.php';
$postdata = json_decode(file_get_contents("php://input"), true);
//var_dump($postdata);exit;
//var_dump($postdata);
$query = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '".$table_name."'
AND table_schema = '".$mysql_database."'";
$result = mysqli_query($con,$query);
$results = array();
while ($line = mysqli_fetch_assoc($result)) {
$results[] = $line;
}
$query = null;
foreach ($results as $r) {//search in order.1st search in column 1 then column 2...so on
$append = " SELECT * from " . $table_name . " WHERE " . $r['COLUMN_NAME'] . " like '" . $postdata['string'] . "%'";
$query = $query . $append;
for($i=1;$i<=(count($postdata['mycol']))-1;$i++)
{
$append1=" AND " .$postdata['mycol'][$i]. " like '" . $postdata['mycolval'][$i] . "%'";
$query = $query . $append1;
}
$query=$query." UNION";
}
$query = substr($query, 0, -6);
$result2 = mysqli_query($con, $query);
$pos = strrpos($postdata['string'], '%');
$str_count = substr_count($postdata['string'], '%');
$results2 = array();
$results3 =array();
while ($line = mysqli_fetch_assoc($result2)) {
if (strpos($postdata['string'], '%') !== false || strpos($postdata['string'], '_') !== false) {// highlight in star search
$str = preg_replace('/[^a-zA-Z0-9-]/', '', $postdata['string']);
$line = preg_replace("|^($str)|Ui", "<span class='highlights'>$1</span>", $line);
} else {
$string=$postdata['string'];
$line = preg_replace("|^($string)|Ui", "<span class='highlights'>$1</span>", $line); //highlight in normal search
}
$results2[] = $line;
}
$result2 -> data_seek(0);
while ($line1 = mysqli_fetch_assoc($result2)) {
$results3[] = $line1;
}
for ($i=1;$i<=count($results2);$i++) {
echo "<tr id='row".$i."' class='remove table_row'>";
$j=0;
foreach($results as $r1){
if($j==0){
echo "<td class='index_field' dB_id='".$results3[$i-1][$r1['COLUMN_NAME']]."'>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
} else {
echo "<td>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
}
$j++;
}
echo "</tr>";
}
echo 'arventures' . $i;
mysqli_close($con);
Your ajax call never reaches the success function because you have specified dataType as JSON. Either remove dataType or return JSON instead of normal HTML.