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);
}
}
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 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";
?>
When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.
I'm tryin to get a value in URL from php file via $.get(), here is the code:
PHP folder called 'jquery_con4.php':
echo (isset($_GET['req'])) ? 'found':'notfound';
JQuery called 'pass.js':
$.get('connection/jquery_con4.php', function(data){
alert(data);
});
the main folder called 'password_c.php' which include the javascript called 'pass.js' which has $.get but it shows me in note 'notfound', & if remove if echo, it shows be 'undefined index:req'
--- URL is: 'http://localhost/series/skyface/password_c.php?req=65yDq0zI39UcRSF'
Thanks!
http://localhost:8888/series/skyface/password_c.php?req=65yDq0zI39UcRSF
In order to pass the 'req' value from the URL querystring to the jquery_con4.php script, you need a JS function that will grab it for you and pass it into an ajax request.
Below is an example of how that might work.
/series/skyface/password_c.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="../../main.js"></script>
</body>
</html>
/main.js:
jQuery(document).ready(function($) {
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function success(data) {
console.log(data);
}
$.ajax({
url: '/connection/jquery_con4.php',
data: {req : getParameterByName('req')},
success: success
});
});
/connection/jquery_con4.php:
<?php echo(isset($_GET['req'])) ? 'found' : 'notfound'; ?>
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?