I want to make a live username check and I want to use a PHP function.
-->
<?php
require '../../core/init.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>KöppCMS - Registrieren</title>
<link rel="stylesheet" href="../../../css/style.css">
<script type="text/javascript" src="../../../js/jquery.js"></script>
<script type="text/javascript" src="../../../js/footer.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#username").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
var username = $(this).val(); //get the string typed by user
$.post('users.php', {'username':username}, function(data) { //make ajax call to users.php
$("#user-result").html(data); //dump the data received from PHP page
});
});
});
</script>
</head>
Init.php:
<?php
session_start();
require 'database/connect.php';
require 'classes/users.php';
require 'classes/general.php';
$users = new Users($db);
$general = new General();
$errors = array();
?>
So how can I call the check_username function and send the values to it?
Hope you understand my question, because my English isn't that good.
i'd tried this in the users.php:
<?php
$users = new Users($db);
echo $users->check_username($_POST['username']);
class Users{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function check_username($data) {
return $data+1;
}
function func1($data){
return $data+1;
}
}
Get this Error:
Notice: Undefined variable: db in C:\xampp\htdocs\kcms\system\cms\user\users.php on line 2
Your PHP script should do something like:
<?php
require('init.php'); // This contains $users = new Users($db);
echo $users->check_username($_POST['username']);
For using the return value in your Javascript, see
How do I return the response from an asynchronous call?
Related
I'm building a very simple shop app using PHP and some JQuery.
On the first load, the app loads fine, but if do GET request call to the same script, it gives me an error:
Warning: require(app\controllers\Wallet.php): failed to open stream: No such file or directory in C:\xampp\htdocs\abc\app\core\autoload.php on line 5
Here's my index.php file (Bootstrap and Jquery links omitted):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>MyShop</title>
</head>
<body>
<div id="app">
<?php
require_once 'app/core/App.php';
?>
</div>
</body>
</html>
Here's my app/core/App.php:
<?php
namespace app\controllers;
require_once 'autoload.php';
//Instantiate
$wallet = new Wallet();
$header = new Header();
$products = new Products();
$products_list = $products->getProducts();
$cart = new Cart($products_list);
//Do logic
$cart->addToCart(2);
if(isset($_GET['addtocart']))
{
$added_id = $_GET['addtocart'];
$cart->addToCart($added_id);
}
if(isset($_GET['removefromcart']))
{
$added_id = $_GET['removefromcart'];
$cart->removeFromCart($added_id);
}
if(isset($_GET['checkout']))
{
$cart->checkout();
}
//
//Show everything
$header->showHeader($wallet);
$products->showProducts();
$cart->showCart();
Autoload in autoload.php is very simple
<?php
spl_autoload_register(function($className)
{
require $className.'.php';
});
And here's example of a jquery script tied to Add to cart button:
$(function() {
$('#app').on("click","#addtocart", function (e) {
e.preventDefault();
productId = $(e.target).data("product-id")
$.ajax({
type: 'get',
url: './app/core/App.php',
data: {
'addtocart': productId,
},
success: results => {
$('#app').html(results);
},
error: () => {
alert('Load error');
}
});
console.log(productId);
});
})
Seems like nothing changes, but the code breaks.
Had to refactor autoload.php adding absolute path to make it work:
<?php
spl_autoload_register(function($className)
{
$file = $_SERVER['DOCUMENT_ROOT'].PROJECT_SUBFOLDER.$className.'.php';
if(file_exists($file))
{
require_once $file;
}
else {
echo 'File:'.$file.' not found';
}
});
?>
I'm trying to display a simple chart but it's not showing on localhost. I'm using codeigniter framework+google charts.
I want to display this simple chart: Chart
Data_model.php:
defined('BASEPATH') OR exit('No direct script access allowed');
class Data_model extends CI_Model {
private $performance = 'sportoviska_zakaznici';
function __construct() {
}
function get_chart_data() {
return $this->db->query('SELECT pohlavie, count(*) as counts FROM sportoviska_zakaznici GROUP BY rok')->result_array();
}
}
Charts.php (controller):
class Charts extends CI_Controller {
function __Construct() {
parent::__Construct();
$this->load->helper(array('form', 'url'));
$this->load->model('data_model', 'chart');
}
public function index()
{
$data['chart_data'] = $this->chart->get_chart_data();
$this->load->view('uvodna_stranka', $data);
}
}
uvodna_stranka.php (view):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title></title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the line package.
// google.charts.load('current', {'packages':['bar', 'timeline']});
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'}],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
?>
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<b>Bla bla<b>
<div id="piechart" style="width: 900px;"></div>
</body>
</html>
I'm trying to display data from this MySQL table:
Mysql table
When I try to access it from my localhost chart is not being displayed. This is how it looks: Image
So what is the problem?
you can check the browser's console for errors (press F12 on most)
there are a couple issues here...
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'}],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
?>
first, there is a ending curly brace out of place after --> 'counts'}
remove it...
next, the array for the data doesn't have ending braces --> ]);
change above to...
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
?>
]);
First you have syntax problems, you have a closing bracket in ['pohlavie', 'counts'}], which doesn't even open or has any porpouse I think.
Then when you have the data, in which you never close the tags from the function:
var data = google.visualization.arrayToDataTable([
['pohlavie', 'counts'}],
<?php
foreach ($chart_data as $data) {
echo "['".$data["pohlavie"]."', ".$data["counts"]."],";
}
I went on https://developers.google.com/chart/interactive/docs/drawing_charts and found out you should probably be using the following first example. In your case it should go along the lines of the following instead of your var data:
data = new google.visualization.DataTable();
data.addColumn('string', 'pohlavie');
data.addColumn('number', 'counts');
data.addRows([
<?php
foreach ($chart_data as $data) {
echo '["'.$data["pohlavie"].'","'.$data["counts"].'"]';
}
?>
]);
Just to be sure you should check the examples of the google charts documentation.
I'm writing a little, simple script which load JSON file and print into HTML by AngularJS. This is my JS code:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
var APP = angular.module('APP', []);
var restaruantId;
APP.ApplicationCtrl = function ($scope) {
if ($_GET['id'] !== undefined && $_GET['id'] !== null) {
restaruantId = $_GET['id'];
jQuery.get( "inc/getData.php", { id: restaruantId} )
.done(function( data ) {
// $scope.restaurant = data;
$scope.restaurant = angular.fromJson(data);
console.log($scope);
});
} else {
alert("ERROR");
}
$scope.name = 'World';
};
getData.php load JSON file from Graph API and it works. $scope.restaurant is an object and it contains all data. This is my HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS Test</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="APP" ng-controller="APP.ApplicationCtrl">
<h1>{{ restaurant.name }}</h1>
</div>
</body>
</html>
Unfortunatelly restaurant.name doesn't work and it's empty. Can you tell me why?
My codeigniter controller is set up as follows:
<?php
include('./application/libraries/REST_Controller.php');
class Restful extends REST_Controller{
public function user_get()
{
//URL as such:
// http://localhost/rest/restful/user/id/1
//notice array('returned'$this->get(id)) ->>>> get the id thats being sent
$data = array('returned: '.$this->get('id'));
$this->response($data);
//returns :
// xml <item> returned: 1</item> /xml
}
}
trying to access it from a view that is set up as such:
<!DOCTYPE html>
<html>
<header>
<title style="font-family:Logo">Ajax</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--this is jQuery with only the ajax part-->
<script src="../ajax.js"></script>
</header>
<body>
<div id="e">
</div>
<script>
function getrest(){
var output;
res=$.ajax({
url: 'http://localhost/rest/restful/user?id=1',
type: 'GET',
success: function(output){
document.getElementById('e').innerHTML = output;
}
});
}
$(document).ready(function(){
getrest();
});
</script>
</body>
</html>
My Problem is that the result i keep getting from the view is:
[object Document]
What am i doing wrong here?
EDIT:
If i type this into the URL
rest/restful/user?id=1
i get this result from the rest controller:
returned: 1
Thanks
Jason
I think you need to define function name as "user", not "user_get". So controller code will be
public function user()
{
$data = array('returned: '.$this->get('id'));
$this->response($data);
}
}
I want to view the data on mysql using ajax, im having a problem with my code. This code doesn't alert anything.
index.php
<script>
function forusedata(id) {
$.post('insert_home.php', {BOOKDATA: id}).done(function(data) {
alert(data);
});
}
</script>
});
insert_home.php
else if (isset($_POST['BOOKDATA'])) {
$ENUM = ($_POST['BOOKDATA']);
$result = mysqli_query($con, "SELECT *FROM book WHERE BOOKID='$ENUM'");
while ($row = mysqli_fetch_array($result)) {
echo $row['BOOKCAPTION'];
}
mysqli_close($con);
}
Try that:
script
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Test POST</title>
</head>
<body>
<script type='text/javascript'>
$(document).ready(function() {
$.post(
'insert_home.php',
{
BOOKDATA: 1
}
).done(function(data) {
alert(data);
});
});
</script>
</body>
</html>
insert_home.php
<?php
if (isset($_POST['BOOKDATA'])) {
// search user
echo 'BOOKDATA = ' . $_POST['BOOKDATA'];
}
In you case, you need to transform your mysql result in a text or json format, like echo json_encode($your_var);
Your problem maybe is in your SELECT/mysqli connection.
Try see the return in you Developers Tools (Chrome):
Press F12
Clique in Network tab
Search for your insert_home.php request
Click in Response
Hope this helps