I'm wanting to load list of names from SQL DB. I then want to click the name and have corresponding image load. The first image should load when page loads. Names are loading. Image is not loading and ng-click does not load image. Made similar code work using JSON, but not able to make work using DB. Cats is the name of table. ImagePath and CatName are the fields in DB. New to PHP. Thank you.
<!doctype html>
<html>
<head>
<title>Load Images from DB</title>
<script src="angular.min.js"></script>
</head>
<body ng-app='myapp'>
<div ng-controller="userCtrl">
<div ng-repeat="user in Cats">
<h3 ng-click = "$scope.selectCat(cat)">{{user.CatName}}</h3>
</div>
<img ng-src="{{$scope.selectedCat.ImagePath}}"/>
<!-- Script -->
<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'getData.php'
}).then(function successCallback(response) {
$scope.Cats = response.data;
$scope.selectCat=selectCat;
$scope.selectedCat=$scope.Cats[0];
function selectCat(pos) {
$scope.selectedCat = pos;
};
});
}]);
</script>
</div>
</body>
</html>
Here is PHP code
include 'config.php';
$sel = mysqli_query($con,"select * from Cats");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$data[] = array("CatName"=>$row['CatName'],"ImagePath"=>$row['ImagePath']);
}
echo json_encode($data);
Change you controller script by moving the selectCat outside of promise. Also assign it scope.
fetch.controller('userCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.selectCat = selectCat;
function selectCat(pos) { $scope.selectedCat = pos; }; });
}
$http({ method: 'get', url: 'getData.php' }).then(function successCallback(response) { $scope.Cats = response.data; $scope.selectedCat=$scope.Cats[0]; }]);
The php will be executed server side and render the data as json array.
Anyways i will update my answer.
I finally got it to work by changing the HTML to:
<div ng-controller = "MainController as **vm**">
<div ng-repeat = "cat in Cats">
<h3 ng-click = "vm.selectCat(cat)">{{cat.CatName}}</h3>
</div>
<hr>
<h3>{{vm.selectedCat.CatName}}</h3>
<img ng-src="{{vm.selectedCat.ImagePath}}"</img>
I then changed the controller to :
angular.module('myApp').controller('MainController', ['$scope','$http',function($scope,$http) {
**var vm = this;**
vm.selectCat=selectCat;
function selectCat(pos) {
vm.selectedCat = pos;
};
$http({
method: 'get',
url: 'getData.php'
}).then(function successCallback(response) {
**$scope.Cats = response.data;
vm.selectedCat=$scope.Cats[0];**
});
Related
I have a PHP script which Edit and Delete cars on my website. Now I want to make Edit and Delete buttons inside a dropdown, and I did but its adding dropdown just to the first car from the row, since the ID is the same for every dropdown. Now I know how to get the unique ID from every car from PHP but how can I achieve it in JavaScript. I will show you my code.
PHP:
$id = $row["id"];
<div class='dropdown'>
<button onclick='myFunction()' class='dropbtn'>Settings</button>
<div id='myDropdown".$id."'class='dropdown-content'>
".($featured!=1 ? "<a title='Make ".$title." Featured'href='forms/addfeatured.php?id=".$id."'>Make Featured</a>" : "<a title='Remove ".$title."' href='forms/removefeatured.php?id=".$id."'>Remove Featured</a>")."
<a title='Delete ".$title."' href='forms/deletecars.php?id=".$id."'>Delete</a>
</div>
JavaScript:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
So how can I have different ID in javascript so I can open dropdowns for each entry?
Only use , No need to technically learn AJAX or JSON !
You Just need to use the simple functions which has been prepared for use and has been put in the libraries. And set a few parameters that they need.
The important thing is that, You should know PHP runs on the server machine, not your browser or your PC.
So the PHP variables too.. They are not in your machine to easily put them in a JS variable.
At his point we need to communicate with the server to send them(using AJAX function) in a proper format(using JSON function) for us to use.
So, Your question :
How to add ID from PHP script to JavaScript code?
has the easiest solution just with these functions:
(At your browser page):
$.ajax({ .. some parameters .. });
$(document).ready(function() {
$.ajax({
type: 'post', //Transfer Protocol
url: 'serving.php', //Address of Server Page
dataType: 'json', //Data Structure
data: {action: 'demo'},
success: function(output) {
$variables = output;
}
});
});
and
(At your PHP page on the server)
json_encode(.. some data ..);
$variables = array("Chevy", "BMW", "Ford");
echo json_encode($variables ); // Encoded variable array
Unfortunately your codes and description are not clear for me to help directly in your project.
But I attach a simple practical Example :(in Jquery)
// carSelection.html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs
/jquery/2.1.1/jquery.min.js"> //jquery CDN
</script>
</head>
<body>
<div style="margin:2em">
<form id="myForm">
<select id="selectNumber">
<option>Choose a car</option>
</select>
</form>
</div>
<script>
var $cars = '';
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'carServs.php',
dataType: 'json',
data: {action: 'demo'},
success: function(output) {
$cars = output;
var option = '';
for (var i=0;i<$cars.length;i++){
option += '<option value="'+ $cars[i] +
'">' +
$cars[i] + '</option>';
}
$('#selectNumber').append(option);
}
});
});
</script>
</body>
</html>
And
// carServs.php page
<?php
// ...
$cars = array("Chevy", "BMW", "Ford");
echo json_encode($cars);
//...
?>
just remeber to attach the jquery CDN at your code, In the head section or just before ending the body tag </body>
And if you insist to have it in JavaScript, It's possible just with a few changes in syntax.
im trying to find a way to only show las signature created in canvas, but the problem is that senes the img don't save in the DB i cant limit 1; like in mysqli_query or can you??
This is where the signature is created.
<div id="signArea" >
<h2 class="tag-ingo">Put signature below,</h2>
<div class="sig sigWrapper" style="height:auto;">
<div class="typed"></div>
<canvas class="sign-pad" id="sign-pad" width="300" height="100"></canvas>
</div>
</div>
<button id="btnSaveSign">Save Signature</button>
when the signature is created it call this function which saves the signature to a file :
$(document).ready(function() {
$('#signArea').signaturePad({drawOnly:true,
drawBezierCurves:true, lineTop:90});
});
$("#btnSaveSign").click(function(e) {
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data =canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: { img_data:img_data },
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
save_sign.php
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = md5(date("dmYhisA"));
//Location to where you want to created sign image
$file_name = 'doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
The output loads like this:
<?php
$image_list = glob("doc_signs/*.png");
foreach($image_list as $image){
?>
my problem is that it loads all images saved in the file , is there any whay to ony load last image and reset on load page??? .
When request is ajax, i am rendering content section and inserting it to DOM. It is working as expected.
However.. i can't find out the way, how to render multiple sections, like content and title and more in the same time.
Controller:
public function awesome(Request $request) {
if($request->ajax()){
return view('awesome')->renderSections()['content'];
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data);
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});
layouts.app
<title>#yield('title')</title>
<meta name="description" content="#yield('desc')"/>
<a data-request="push" title="AWESOME" href="<?= url('/'); ?>/awesome">Awesome</a>
<a data-request="push" title="RANDOM" href="<?= url('/'); ?>/random">Random</a>
<div id="content">
#yield('content')
</div>
Blade:
#extends('layouts.app')
#section('title', 'Awesome')
#section('desc', 'About awesome')
#section('content')
some text from awesome page
#endsection
Question:
How to render both or more of them in same time? Should i use an array or something else? Please give example or full explanation.
Thanks for any answers.
You can just send a json object of title and content, and then use JS to parse the array and extract both sections. Like so:
Controller
public function awesome(Request $request) {
if($request->ajax()){
$view = view('awesome')->renderSections();
return response()->json([
'content' => $view['content'],
'title' => $view['title'],
]);
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data.content);
document.title = data.title;
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});
I'm developing a small project where I have a web page (index.html) loading in Express.js and it sends some data to a PHP script running on a MAMP server. The PHP script processes the data and returns a JSON encoded array back to the web page and finally the Node.js server sends data to connected clients using socket.io.
I have problems with the communication with PHP using jQuery Ajax. I send the data to PHP using POST and I know PHP receives that data but I don't know how to catch the response from PHP to know how the processing went.
I have no experience with Node.js. What can I do to make this thing work?
So far this is the code I have
Node.js - Express.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, db = require('./routes/db')
, http = require('http')
, socketio = require('socket.io')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); //Middleware
app.use('/', express.static(__dirname + '/public'));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
HTML Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Site</title>
<script src="js/jquery-2.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<div id="formContainer">
<form enctype="multipart/form-data">
<input type="text" name="texto">
<button type="button" id="buttonSend">Enviar</button>
</form><br/><br/>
</div>
<script type="text/javascript">
$('#buttonSend').click(function(e){
e.preventDefault();
$.ajax({
url: 'http://localhost:8080/NodePHP/test.php',
type: 'POST',
dataType: "json",
data: {value: 1},
success: function(data){
if(data.success == true){
alert("Perfect!");
}
else{
alert("Error!");
}
},
error: function(xhr,status,error){
//alert("Error de llamada al servidor");
alert(xhr.responseText);
//$('#botonUsarFoto').css('display','block');
}
});
});
</script>
</body>
</html>
PHP Script
<?php
$number = $_POST['value'];
echo $number;
// move the image into the specified directory //
if ($number == 1) {
$data = array("success"=>"true");
echo json_encode($data);
} else {
$data = array("success"=>"false");
echo json_encode($data);
}
?>
Thanks in advance for any help
In order to make a request with Node, we'll use the http and querystring modules. Here's an example lovingly adopted from the Nodejitsu folks:
var http = require('http');
var querystring = require('querystring');
var data = querystring.stringify({
value: 1
});
var options = {
host: 'localhost',
path: '/myPHPScript',
method: 'POST'
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write(data);
req.end();
Alternatively, you could use the request module, but first things first.
<!doctype html>
<html>
<head>
<title>jQuery Tagit Demo Page (HTML)</title>
<script src="demo/js/jquery.1.7.2.min.js"></script>
<script src="demo/js/jquery-ui.1.8.20.min.js"></script>
<script src="js/tagit.js"></script>
<link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">
<script>
$(document).ready(function () {
var list = new Array();
var availableTags = [];
$('#demo2').tagit({tagSource:availableTags});
$('#demo2GetTags').click(function () {
showTags($('#demo2').tagit('tags'))
});
/*
$('li[data-value]').each(function(){
alert($(this).data("value"));
});*/
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
function showTags(tags) {
console.log(tags);
var string = "";
for (var i in tags){
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
}
});
</script>
</head>
<body>
<div id="wrap">
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
<div class="box">
<div class="note">
You can manually specify tags in your markup by adding <em>list items</em> to the unordered list!
</div>
<ul id="demo2" data-name="demo2">
<li data-value="here">here</li>
<li data-value="are">are</li>
<li data-value="some...">some</li>
<!-- notice that this tag is setting a different value :) -->
<li data-value="initial">initial</li>
<li data-value="tags">tags</li>
</ul>
<div class="buttons">
<button id="demo2GetTags" value="Get Tags">Get Tags</button>
<button id="demo2ResetTags" value="Reset Tags">Reset Tags</button>
<button id="view-tags">View Tags on the console </button>
</div>
</div>
</div>
<script>
</script>
</body>
</html>
This code will just transfer the list of items in the dostuff.php but when I try to print_r it on PHP nothing won't come out. why is that?
I am doing an ajax request on this line
$('#demo2').click(function(){
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: alert("OK")
});
});
and the code in PHP
<?php
$lis = $_POST['items'];
$liarray = explode("::", $lis);
print_r($liarray);
?>
This is just a shot in the dark, given the limited information, but it would appear that you're expecting something to happen with the data sent back from the server.. but you literally do nothing with it. On success, you have it display an alert... and nothing else.
Try changing your success entry to the following:
success: function(data) {
$("#wrap").html(data);
}
This will fill the div with the data from the POST request. The reason it shows up as nothing as it is..., you aren't loading the currently executing page with the data needed for the print_r to actually echo anything.
Edit: How to insert values into database;
Database interaction now-a-days is done with either custom wrappers, or the php Data Object, also referred to as PDO, as opposed to the deprecated mysql_* functions.
First, you prepare your database object, similar to how a connection is done in the aforementioned deprecated functions:
$dbh = new PDO("mysql:host=hostname;dbname=database", $username, $password);
Then, you can begin interaction, preparing a query statement..
$stmt = $dbh->prepare("UPDATE table_name SET column1 = :column1 WHERE id = :id");
Binding a parameter in said statement..
$stmt->bindParam(':column1', $column1);
$stmt->bindParam(':id', $id);
$id = $_POST['id'];
And finally executing the query:
try {
$stmt->execute();
}
catch (Exception $e) {
echo $e;
}
PDO auto-escapes any strings bound in the prior statements, making it save from SQL-injection attacks, and it speeds up the process of multiple executions. Take the following example:
foreach ($_POST as $id) {
$stmt->execute();
}
Since the id parameter is already bound to $id, all you have to do is change $id and execute the query.
Where where you expecting the PHP result of print_r to "come out"?
Try changing your AJAX call to this (only the value of success is different):
$.ajax({
url: "demo3.php",
type: "POST",
data: { items:list.join("::") },
success: function(data, textStatus, jqXHR){
alert(data);
}
});
With this, the output of your PHP template, which you would normally see if you posted to it the old fashioned way (ie. with a form and a full page reload), will display in an alert.
Hope that helps.
Try to add encodeURI for the jQuery part,
$.ajax({
url: "demo3.php",
type: "POST",
data: { items: encodeURIComponent (list.join("::")) },
success: function(response) {
console.log(response);
}
});
And urldecode for the PHP part:
$lis = $_POST['items'];
$liarray = explode("::", urldecode($lis));
print_r($liarray);
3 things:
Set your AJAX's success to show the echos/prints given in your PHP script
success: function(result)
{
$("#somecontainer").html(result);
}
That way ANYTHING that gets printed in a PHP script otherwise, will be put in i.e.
<div id="somecontainer">
Result of PHPcode here
</div>
Second, instead of
var string = "";
for (var i in tags)
{
string += tags[i].value+" ";
}
var list = string.split(" ");
//The last element of the array contains " "
list.pop();
use push(). This adds the value at the next unoccupied index in the array:
var string = "";
for (var i in tags)
{
list.push(tags[i].value);
}
That way you don't have to pop the last element off.
Third point: put your PHP code in a separate file (and your JavaScript/jQuery as well). Have like:
/root/index.html
/root/script/dostuff.php
/root/script/myscript.js
then let your AJAX call to url: "/script/dostuff.php"