Sending array from php to javascript, parsing PHP variables to JS - javascript

I want to be able to pickup variables from php example: public var $PHPVariable = "Hello World"; or something in that way. But how will I possible send this to javascript without XML HTTP(S) requests?
PHP File example
<?php
public var $secure_connection = $secure['ssl']['type']['connection']['valid_id'] // This is equal to (int)25
public var $userRank = $_SESSION['user']['active']['secure']['rank']; // Returns Admin or Default
public var $userFullName = $_SESSION['user']['unactive']['secure']['require']['name']['first'.'middle'.'last']
?>
JavaScript file / document
function get(variable, type){
if(!empty(variable) && !empty(type)){
if(!exist(variable)){ // the exist function will check if the public variable exist in the php setting file.
return 'The variable does not exist!';
}
if(type=='output'){
return recieve(variable, 'As String'); // the recieve function will collect the data from the public variable.
}
if(type=='setting'){
return recieve(variable, 'As Setting') // returning the recieve function as a setting will basicly mean it can return anything such as string/array/integer/boolean
}
}else{
return 'ERROR: Please fill in required fields!';
}
}
if(get('secure_connection', 'setting')==25){/* Returns true */}
if(get('userRank', 'setting')=='Admin'){/* Returns true */}
if(get('userFullName', 'output')){/* Returns the variable as a string no matter what the php variable was in ex int/boolean*/}
Take in mind I want to do this without XML http(s) requests!
Thanks for taking your time help! Richard.
EDIT
I know it is possible sending JSON Requests to a PHP Object class, which could solve this solution but it is not secure enough for my website, though it allows the user to even edit their own rank into other ranks or change SQL Connection properties of databases and change the row values, etc. Just with enough knowledge of using the (example) Chrome Console to use the function to change the php files content. Which will result resolving no ones problems.

Related

How to receive HTTP POST parameters on vue.js? [duplicate]

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

Capture instance of PHP class and call an instance function from JS

I have a page that asks for a country code in a ComboBox, and I want it to load some other ComboBox with certain values that depend on the first one.
The secondary data should be loaded using a function inside a PHP class, whose instance I need to capture. I'm still not very familiar with AJAX and jQuery, so that's my problem.
My code is like this (I omitted the most obvious parts, of course):
new.html
<script src="findIDTypes.js"></script>
<form>
<select id="country_id" onchange="findIDTypes(this.id)">
<option value="AR">Argentina</option>
<option value="BR">Brazil</option>
</select>
</form>
dbfunctions.php
class DBConn {
public function GetInstance($host = FALSE, $user = FALSE, $pass = FALSE) {
static $_instance = FALSE;
if ($_instance === FALSE) {
if ($host == FALSE || $user == FALSE || $pass == FALSE) {
// Error! Can't instantiate
}
$_instance = new DBConn($host, $user, $pass);
}
// OK!
return $_instance;
}
public function findIDTypes($country_id) {
// Returns array of value pairs (Code, Description)
}
}
findIDTypes.js
function findIDTypes(value_to_search) {
// ???
}
What I need my AJAX/jQuery (not sure which) function to do is:
Capture the instance of DBConn
Call the instance function "findIDTypes()" in the PHP class
Retrieve the array of (C,D) pairs and load them, one by one, on the secondary combobox
What exactly do I need to do to complete steps 1 and 2, if it's possible at all?
Thanks! :)
php and javascript are entirely different, and while you can use php to generate javascript code before the page is rendered, you cannot call php functions from javascript.
This is because php runs on the server, and javascript (which the exception of Node.js!) runs in the browser.
To solve this, you need to expose your php as an API using HTTP GET or POST methods.
Steps
Build your php page to accept $_GET url query parameters or $_POST parameters, in one form or another.
Decide upon a method of communicating your data on the server end back to your browser's javascript/ajax. For this, I highly recommend json for an innumerable number of reasons. It easily integrates with php via json_encode() and json_decode(), and javascript via JSON.parse() and JSON.stringify().
Once you've established your "API" as it were in php, you can easily use jQuery's $.ajax to send and retrieve data to your php. Since your example is relatively simple, it may be as easy as something like http://yoursite.com/?init=DBConn_GetInstance and handling the $_GET['init'] function, then outputting the results of your function.

How to check if table is empty using cakephp and AJAX?

how do we check if table is empty with cakephp and ajax? In my index.ctp I have an image that when clicked, it will inform the user if the table is empty or not. If it's empty, an alert box will appear, and if it's not, it will be redirected to another page.
<?php
echo $this->Html->image('movie.png', array('onclick'=>'check()'));
?>
JAVASCRIPT:
function check(){
//check browser comp, create an object
object.GET("GET", url, false);
//rest of the code here
}
MoviesController.php
function index(){
//something here
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
I know how to do it using the normal PHP coding, but with cakephp, and since I am new, I dont know yet. For regular PHP coding, I used the GET method for AJAX, and I can specify the URL for the PHP query inside the GET function. I don't know how to do it using cake.
You need to set the layout to AJAX then render your view. I strongly recommend not to use the index() method for this. Instead you can define a whatever() method in the MoviesController:
function whatever(){
//It is not a bad idea to do this only for GET - use the RequestHandlerComponent
$this->layout = 'ajax';
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
The in the view file whatever.ctp:
echo json_encode(array('moviecount' = $moviecount));
//It is a good idea to add an isset() ternary check here like:
// echo isset($moviecount) ? json_encode(array('moviecount' => $moviecount)) : json_encode(false);
Notice that I am creating an array and encoding it to JSON. This is the way to convert variables to and from JSON. To decode use json_decode() of course.
The Client-side code really depends on what you're using to make the AJAX call but let us say that the call succeeded and you got the data back in the data variable:
//Make the AJAX call to example.com/movies/whatever via GET
//Check what data is but it should definitely be an array
if (data['moviecount']) {
//If moviecount is 0 it will go in the else statement - 0 i falsey
window.location = 'example.com/redirect/url';
} else {
alert('No records');
}
I advice against using alert() to inform the user that there are no records. Better put it somewhere in the page - in some div or whatever. Since this is an AJAX request it could be repeated many times. Consecutive use of alert() is not really user-friendly in this case.

Can JavaScript read HTTP Session object?

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?
(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.
As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

Categories

Resources