PHP autoload fails to find class files after AJAX call - php

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';
}
});
?>

Related

'paypal' is not defined in PHP

I have codes in ajax which calls php file to show the paypal sdk button in that page :
function redirectPaypal() {
$('#tabs2').html('<img src="' + webroot + 'facebox/loading.gif">');
callAjax(webroot + 'TESTS.php', 'mode=paypall', function (t) {
// $.facebox(t);
$('#walletBg').removeClass('addBgColor');
$('#paypalBg').addClass('addBgColor');
$('#neverBg').removeClass('addBgColor');
$('#authBg').removeClass('addBgColor');
// $('#paymentInfo').show();
$('#tabs2').html(t);
});
}
As you see it calls TESTS.php file with the mode value paypal. The TESTS.php file is looks like below :
<?
require_once 'application-top.php';
require_once 'includes/navigation-functions.php';
require_once 'includes/site-functions-extended.php';
require_once 'includes/buy-deal-functions.php';
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
$post = getPostedData();
print_r($post);
if ($_POST['mode'] == 'paypall')
{
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Checkout Integration | Client Demo </title>
</head>
<body>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
<script>
// Render the PayPal button into #paypal-button-container
paypal_sdk.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '88.44'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
</body>
</html>
<?
}
?>
File is called successfully but as you see the code below I am getting the reference error when the page is called :
VM1597:3
Uncaught ReferenceError: paypal_sdk is not defined
at eval (eval at <anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11369), <anonymous>:3:9)
at eval (<anonymous>)
at js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11369
at Function.globalEval (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11380)
at HTMLScriptElement.<anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:2538)
at Function.each (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:11776)
at init.domManip (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:2441)
at init.append (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:3:32408)
at init.<anonymous> (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:4:1283)
at Function.access (js.php?f=js%2Fjquery-1.7.2.min.js%2Cjs%2Fmodernizr.custom.02358.js%2Cfunctions.js.php%2Cjs%2Fsite-functions.js%2Cform-validation.js.php%2Cform-validation-lang.php%2Cjs%2Fjquery-ui.min.js%2Cfacebox%2Ffacebox.js%2Cjs%2Fmbsmessage.js&min=1&sid=1631542832:2:13266)
The error is related to the script which is called in TESTS.php :
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
It seems the file is not imported or there is some errors in php file which I am not able to find it out. Can anyone help me with this please as I have spent my whole day on it. Thanks.
EDIT :
I have seperated the codes like below in order to prevent the preloading the papyal.button codes first. And now it looks like below :
<?
require_once 'application-top.php';
require_once 'includes/navigation-functions.php';
require_once 'includes/site-functions-extended.php';
require_once 'includes/buy-deal-functions.php';
?>
<script type="text/javascript" src="https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD"></script>
<?
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
$post = getPostedData();
print_r($post);
if ($_POST['mode'] == 'paypall')
{
?>
<script src="https://example.com/TESTS.js"></script>
<?
}
?>
Now I am getting the error like below :
GET https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD&_=1647908135353 net::ERR_ABORTED 400
When I checked the error code the requested src url is looking like different as it adds the timestamp at the end of the link therefore I am getting the error :
https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD&_=1647908731335
EDIT 2:
The payment page looks like below :
You don't have to inject the whole page. You can do something like this.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Checkout Integration | Client Demo </title>
<script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD" data-namespace="paypal_sdk"></script>
</head>
<body>
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
<!-- Include the PayPal JavaScript SDK -->
<?php if($_POST['mode'] == 'paypall') { ?>
<script>
// Render the PayPal button into #paypal-button-container
paypal_sdk.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '88.44'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(orderData) {
// Successful capture! For demo purposes:
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
var transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
// Replace the above to show a success message within this page, e.g.
// const element = document.getElementById('paypal-button-container');
// element.innerHTML = '';
// element.innerHTML = '<h3>Thank you for your payment!</h3>';
// Or go to another URL: actions.redirect('thank_you.html');
});
}
}).render('#paypal-button-container');
</script>
<?php } ?>
</body>
</html>
Anyone who is struggling with this case just use the code like below :
function loadAsync(url, callback) {
var s = document.createElement('script');
s.setAttribute('src', url); s.onload = callback;
document.head.insertBefore(s, document.head.firstElementChild);
}
// Usage -- callback is inlined here, but could be a named function
loadAsync('https://www.paypal.com/sdk/js?client-id=test&currency=USD', function() {
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//...
});
}
}).render('#paypal-button-container');
});
Loading a script that way is asynchronous and takes time therefore the event onload must be used as callback.

How to get data from jQuery to PHP into a MVC Pattern

I need to know if I can pass data from index.php to another page (like json.php) and then retrieve this data in PHP to modify the objects of the controller or the database.
I have attempted several options, but none work. I haven't read anything about that I want and I think it isn't available because all that I must implement is around index.php and the controller cannot receive data elsewhere. But maybe someone knows an alternative way.
I don't want to paste all my scripts I just leave above three that can be useful to show what I want.
Mainly I want to use buttons or user-inputs with some values and then I want to pass them to AJAX via json.php, but I need to do more things between reception's and response's server like update database, insert new items, etc.
I have the following files:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src='./js/main.js'></script>
</head>
<body>
<?php
require_once './php/model/warehouse.php';
require_once './php/model/cart.php';
require_once './php/model/customers.php';
//require_once './php/util/json.php';
$shop = Shop::get_instance();
$shop->load_articles();
...
$cart= Cart::getInstance();
$cart->load_cart();
...
$costumers = Custemers::get_instance();
$costumers->load_costumers();
...
<div id='btn-addtocart-index'>add to cart</div>
</body>
</html>
js/main.js
$(document).ready(
$('#btn-addtocart-index').click(function () {
var str = {prod_id: 1, quantity: 1, increment: 3, type: 'modify'}
str = JSON.stringify(str)
$.ajax({
data: str,
url: './php/util/json.php',
type: 'POST',
dataType: 'json',
ContentType: "text/json; charset=utf-8",
success: function(resp){
alert("TYPE:\t\t" + resp.type + "\nPRODID:\t" + resp.prod_id +"\nQUANT:\t\t"+resp.quantity + "\nINC:\t\t" + resp.increment);
}
})
})
)
php/util/json.php
<?php
$content = file_get_contents('php://input');
if (isset($GLOBALS['customers'])) {
echo "<br><br>CUSTOMERS<br>";
foreach($customers as $customer) {
print_r($customer->get_data());
echo '<br>';
}
}
header("Content-type: text/json; charset=utf-8");
if($content) {
global $shop;
$json = json_decode($content);
$GLOBALS['json'] = $json;
//echo 'obj json->type: ' . $json->type;
if (isset($GLOBALS['customers'])) {
echo "RIGHT NOW?";
$customers[0]->get_data();
}
} else {
//echo '#mem: \'' . file_get_contents('php://memory') . '\'';
}
echo "$content";
?>

JSON data to $scope

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?

$.post into a php class function

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?

Codeigniter Rest And Ajax not getting desired results

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);
}
}

Categories