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";
?>
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 populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});
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'; ?>
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 am trying to build a CSV file in PHP, then call the PHP file from an AJAX call, which will then initiate a download of the CSV file upon success of the AJAX call. This works fine if I save a physical copy of the .csv on the server, but I would like to use php://ouput so I do not have to worry about physical files clogging up the server. Is it possible to initiate a download from returning php://output to AJAX? Here is my code:
HTML/jquery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
alert('Finished');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
PHP:
<?php
header('Content-type: application/vnd.ms-excel');
header('Content-disposition: attachment; filename="test.csv"');
$f = fopen('php://output', 'w');
fwrite($f,'this,is,a,test');
fclose($f);
readfile('php://output');
return;
?>
I am not sure how to get this to return a File Save dialog from my AJAX call.
This has to be simple, but I can't seem to find any examples that combines these two issues.
You can do this by creating and sending form via jquery (page not reloaded):
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'GET');
form.appendTo(document.body);
form.submit();
form.remove();
});
Also you can pass post parameters if need:
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'POST');
var input = $('<input>').attr('type', 'hidden').attr('name', 'x').val('x value');
form.append(input);
form.appendTo(document.body);
form.submit();
form.remove();
});
The following works, but is highly inneficient as it calls the php.php file twice. Does anybody have any better ideas?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
window.open('php.php');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
Is there anyway to cache 'php.php' for just this instance so that it loads instantly under window.open('php.php'), but will reload contents when I click download next?
Why does window.open(response) not work the same?
look this:
if (!headers_sent()) {
// seconds, minutes, hours, days
$expires = 60*60*24*14;
header('Pragma: public');
header('Cache-Control: maxage=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
}
Note: this will not work with POST requests, just GET.
To allow for a file download, you can simply call the below code (say on a button's onclick):
window.open(<file-url>);
Hope this helps.