AngularJS, issue with GET (PHP/Json/SQL) - javascript

I am very new to AngularJS and started to rebuild a restaurant finder app i have previously written in pure PHP. However i would now like to achieve faster database access and asynchronous sorting, hence the desire to learn AngularJS.
I have not used JSON for a while and i am literally stuck with getting basic queries back to AngularJS. Otherwise the syntax is correct but i am unable to get additional data from another table.
So first the basic controller to fetch the data from a PHP file:
var app = angular.module('Dinneri', []);
app.controller('showContent', function($scope, $http) {
$http.get("server/showcontent.php")
.success(function (response) {$scope.restaurants = response.records;});
});
And then we have the showcontent.php file to perform the queries and return the data in JSON.
To clarify: The SQL table populated with restaurants is restaurants and the entries are populated with hashjoins that include a reference to the restaurant and the hashtag associated. The hashtag table includes the actual hashtags. Any tips on shortening the SQL in this conjunction would also be welcomed.
<?php
// Set JSON for Angular
header("Content-Type: application/json; charset=UTF-8");
// Include DB credentials
include('db_con.php');
// Get Restaurants
$result = $mysqli->query("SELECT * FROM `restaurant`");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
// Add restaurant to array
$outp .= '{"ID":"' . $rs["restaurant_id"] . '",';
$outp .= '"Name":"' . $rs["restaurant_title"] . '",';
$outp .= '"Description":"' . $rs["restaurant_description"] . '",';
$outp .= '"Address":"' . $rs["restaurant_address"] . '",';
$outp .= '"LocLat":"' . $rs["restaurant_loc_lat"] . '",';
$outp .= '"LocLong":"' . $rs["restaurant_loc_long"] . '",';
$outp .= '"Added":"' . $rs["restaurant_added"] . '",';
// Get current while loop restaurant
$restaurant = $rs["restaurant_id"];
// Get joined hashtags
$result_hash = $mysqli->query("SELECT * FROM `hash_join` WHERE `restaurant_hash` = $restaurant");
while($hashjoin = $result_hash->fetch_row())
{
$hashtag_id = $hashjoin[1];
// Get hashtag information
$hashtags = $mysqli->query("SELECT * FROM `hashtags` WHERE `hashtag_id` = $hashtag_id ORDER BY `restaurant_type` DESC");
while($hash = $hashtags->fetch_row())
{
// Add hashtags to array
$outp .= '"HashtagID":"' . $hash[0] . '",';
$outp .= '"HashtagName":"' . $hash[1] . '",';
$outp .= '"HashtagType":"' . $hash[2] . '"}';
}
}
}
// Finalize output array
$outp ='{"records":['.$outp.']}';
// Deliver output array
echo($outp);
// Close mysqli
$mysqli->close();
?>
The first set of results are returned to Angular like expected and all code works until i try to output the "Hashtags". The PHP page "showcontent.php" outputs the JSON code as expected but for some reason the Angular controller is being picky about the hashtags.
Deleting this section of the code where the hashtags are outputted makes everything work like a charm, but without the desired output.
Thank you in advance <3

Related

Error Fetching Data From a PHP Server Running MySQL with Angular JS

I am getting a [$http:baddata] error when my Angular app calls my php file.
I'm not sure where the error is triggering exactly, but I believe it's a problem constructing the json object! I've attached all relevant code. Any help would be amazing. Thanks in advance :)
Angular documentation shows this
This is the PHP file which connects to my database and attempts to return a JSON formatting string back to the calling file
<?php
echo '<script>console.log("Inside php file!")</script>';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once('mysqli_connect.php');
$query = "SELECT rideid, destination, price, capacity, userid, origin, departDate, vehicle FROM rides";
$result = #mysqli_query($dbc, $query);
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"Origin":"' . $rs["origin"] . '",';
$outp .= '"Destination":"' . $rs["destination"] . '",';
$outp .= '"Price":"'. $rs["price"] . '"}';
$outp .= '"Capacity":"'. $rs["capacity"] . '"}';
}
$outp ='{"records":['.$outp.']}';
//echo '<script>console.log(JSON.stringify('.$outp.'))</script>';
$conn->close();
echo($outp);
This is the Angular app making the request to the PHP file
<html>
<head>
<!-- Include Angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
</head>
<body>
<!-- Ride Table -->
<div ng-app = "rideAppTest" ng-controller= "rideCtrlTest">
<table>
<tr ng-repeat = "x in names">
<td>{{x.Origin}}</td>
<td>{{x.Destination}}</td>
<td>{{x.Price}}</td>
<td>{{x.Capacity}}</td>
</tr>
</table>
</div>
<!-- End Ride Table -->
<!--Ride Table Script-->
<script>
var app = angular.module('rideAppTest', []);
app.controller('rideCtrlTest', function($scope, $http) {
$http.get("angularFilter.php")
.then(
function (response) {
$scope.names = response.data.records;
},
function(data){
console.log("Error!" + data);
}
);
});
</script>
</body>
</html>
Don't construct the JSON the way you are doing, first collect everything inside an array or an object then do echo json_encode($result);
Something like this:
$outp = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $rs;
}
echo json_encode(["records" => $outp]);
Thank to #Madhav for the help. This is what ended up working for me :)
while($rs = mysqli_fetch_array($result)) {
$myArray[] = array(
'Origin' => $rs["origin"],
'Destination' => $rs["origin"],
'Price' => $rs["price"],
'Capacity' => $rs["capacity"]
);
}
echo json_encode(["records" => $myArray]);

send google tag manager results to php page via ajax method GET

i got a few variables on my site that i push on GTM they work perfect, now i need to get variables results from gtm and send it via ajax to a php page where afterwards i'll use it to an email with the results.
<script>
$(document).ready( function() {
var msg = google_tag_manager["GTM-xxxxx"].dataLayer.get('pageName');
var msg1 = google_tag_manager["GTM-xx"].dataLayer.get('MembershipLvl');
var msg2 = google_tag_manager["GTM-xx"].dataLayer.get('CountryRes');
var msg3 = google_tag_manager["GTM-xxxx"].dataLayer.get('pageLanguage');
var getall = [msg, msg1, msg2, msg3,];
// var me = 'just seend'; this do work
console.log(getall);
$.ajax({
type: "GET",
url: "url.cart.php", // some php
data:{info: getall},
datatype: 'html',
success: function(data) {}
});
});
and here is my php
<?php
/*
*
*/
send_mail();
function send_mail(){
if( $_GET["info"] ) {
$mail = $_GET["info"];
$header ="From: no-reply#test.com" . "\r\n";
$for = 'end#emailadaress.com';
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$title = 'Mailing list Newsletter';
$message = '<html><body>';
$message .= '<br/> <p>tou got email from</p><br/>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="2">';
$message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($mail)."</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
if(mail($for, $title, $message, $header)){
die();
}else{
//echo "false";
}
}else{
echo "false";
}
}
?>
the issue is that im not getting GTM variables sent, i do see them in console log, if i change variable like var = test, i do get it, but i just cant get the GTM variable sent
So the problem is that $_GET["info"] contains an array which strip_tags cannot handle. If you look at the response from your call it should have a PHP error. Somewhere along the lines of : Warning: strip_tags() expects parameter 1 to be string, array given. If you want to get the values out of the array you can either build a loop or reference the particular index.
LOOP
foreach ($mail as $gtm) {
$message .= $gtm;
}
INDEX
$message .= $mail[0] // google_tag_manager["GTM-xxxxx"].dataLayer.get('pageName');
$message .= $mail[1] // google_tag_manager["GTM-xx"].dataLayer.get('MembershipLvl');
etc...
PHP strip tags
Foreach loop
How to view a ajax call in chrome

How to change js code to php

Currently I am learning Php. For an Ebay shop I try to get my page free of JS and to switch to pure CSS via PHP.
For this I have so far a backend, into which I enter my links and texts. These are stored in my menu.js.
$remote_directory = UPLOAD_PATH;
$renaming_file = $remote_directory . '/js/menu.js';
$renaming_file_to = $remote_directory . '/js/menu.old';
$_remc = new Admin_Remote_Copy(ADMIN_UPLOAD_SERVER_HOST, ADMIN_UPLOAD_USER_NAME, ADMIN_UPLOAD_PASSWORD, ADMIN_UPLOAD_SSH_PORT);
$_remc->remote_copy($renaming_file, $renaming_file_to);
if ($_remc->remote_is_writeable($renaming_file)) {
$menu_string = "document.getElementById('categories_menu').innerHTML='";
for ($z = 0; $z < count($_POST['menu_lvl1_text']); $z++) {
$menu_string .= '<li>' . htmlentities($_POST['menu_lvl1_text'][$z], ENT_QUOTES, "UTF-8") . '';
if (isset($_POST['menu' . $z . '_lvl2_text']) && !empty($_POST['menu' . $z . '_lvl2_text'])) {
$menu_string .= '<ul>';
for ($zs = 0; $zs < count($_POST['menu' . $z . '_lvl2_text']); $zs++) {
$menu_string .= '<li>' . htmlentities($_POST['menu' . $z . '_lvl2_text'][$zs], ENT_QUOTES, "UTF-8") . '';
}
$menu_string .= '</ul>';
}
$menu_string .= '</li>';
}
$menu_string .= "';";
$_remc->remote_content_copy($renaming_file, $menu_string);
$local_renaming_file = ADMIN_LOCAL_PATH . '/js/menu.js';
$_remc->local_content_copy($local_renaming_file, $menu_string);
} else {
$file_error = true;
}
Now I had thought to pass these values ​​into an array and save it via JSON PrittyPrint. However, I have no idea at all how to build this array.
My idea is to build a navigation with fixed IDs and fill it with the JSON file.
In the latter I see no problems, but the array is not clear to me.
Let's assume that array would look something like this:
$m =array(
"10100" => array('menu_lvl1_text' => 'menu_lvl1_link'),
"10101" => array('menu_lvl2_text' => 'menu_lvl2_link'),
"10102" => array('menu_lvl2_text' => 'menu_lvl2_link'),
"10103" => array('menu_lvl2_text' => 'menu_lvl2_link')
);
Am I on the wrong path?
And how does my array know that it is to assign value 1 to ID 10000?
Thanks,
Patrick
I think that you forgot to open a folder first! You can use some php functions like opendir at first then get or create a new file there.

generate unique link that runs an images slider with different images

i searched all over the web and i couldn't find an answer, please help me!.
I have an HTML form, like this one:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="text" name="folder_name" placeholder="Folder name">
<input type="submit" value="Submit">
</form>
Now, upload.php takes number of images and store a link to the folder in MySQL.
Then i call query.php through angularJS $http to retrieve the link to the folder + the images.
Here is query.php:
session_start();
include 'connection.php';
header("Content-Type: application/json; charset=UTF-8");
$folder = $_SESSION["target_folder"];
$query = "SELECT * FROM links WHERE link LIKE '%$folder%'";
$stmt = $db->prepare($query);
$stmt->execute();
$imagesArray = [];
$images = [];
$response = "";
$imageArray = "";
$first_response = "";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$images = unserialize($row["images"]);
$imagesArray = explode(",", $images);
foreach($imagesArray as $image) {
if ($response != "") {$response .= ",";}
$response .= '{"target_folder":"' . $row["link"] . '",';
//$response .= '"ext":"' . $row["ext"] . '",';
$response .= '"billboardNumber":"' . $image . '"}';
}
}
$response ='{"records":['.$response.']}';
echo $response;
Last is the slider in slider.html that retrieves the JSON data from query.php:
$http.get("php/query.php")
.success(function (response) {
$scope.slides = response.records;
});
Most important part, my question :-)
every time i run slider.html it overwrites the old slider.html link and outputs the images from the last JSON call.
how can i run slider.html for a month and still get to the same folder even if i generate another 1000 links to different folder.
i hope that someone will understand me :-)
thank you !!!

Elements not included in div when added using Javascript

I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;

Categories