Yii: best practices to pass data from php to JS - javascript

My question is, what are the best practices of passing the data from my server side to my client side?
For example, I have a cartId on my server side which I need to pass on to the client side.
How do I best do that? Right now it's done via the main layout:
<script type='text/javascript'>
(function() {
if (window.cart) {
cart.id = <?php echo Yii::app()->getUser()->getCartId() ?>;
}
})();
</script>
However, that seems like a bad thing to do. Will appreciate any feedback.

In php file write this YII code
YII Code
Yii::app()->clientScript->registerScript("cartid",Yii::app()->getUser()->getCartId());
SCRIPT
(function() {
if (window.cart) {
cart.id = cartid;
}
})();

Use AJAX to get the data you need from the server.
Echo the data into the page somewhere, and use JavaScript to get the
information from the DOM.
Echo the data directly to JavaScript.
With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:
get-data.php
/* Do some operation here, like talk to the database, the file-session
* The world beyond, limbo, the city of shimmers, and Canada.
*
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX
* request. */
echo json_encode(42); //In the end, you need to echo the result.
//All data should be json_encoded.
index.php (or whatever the actual page is named like)
<script>
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
//This is where you handle what to do with the response.
//The actual data is found on this.responseText
alert(this.responseText); //Will alert: 42
};
oReq.open("get", "get-data.php", true);
// ^ Don't block the rest of the execution.
// Don't wait until the request finishes to
// continue.
oReq.send();
</script>
The above combination of the two files will alert 42 when the file finishes loading.

It's best practice to not write PHP in your JavaScript for one. Instead, take the data from PHP and pass it to json_encode (http://php.net/json_encode) and echo it out. You can read that straight into a variable if you like but it would be better to use ajax so it's asynchronous thus better page load.

The best option is to make AJAX calls to a PHP page which performs some action, and returns data. Once that PHP has all the data it needs to return, I echo the data (as an array) in JSON format.
Eg:
info.php
die (
json_encode(
array(
"id" => "27"
"name" => "rogin",
)
)
);
Then, you can use javascript to fetch the data into a json object.
JS
$.getJSON(
'info.php?',
function(jsonObject) {
alert(jsonObject.name);
});

If you just want to prevent javascript syntax highlighting error, quoting would do just fine.
(function() {
var the_id = +'<?php echo Yii::app()->getUser()->getCartId() ?>';
// ^ + to convert back to integer
if (window.cart) {
cart.id = the_id;
}
})();
Or if you like you could add it to an element:
<div id='foo' style='display:none'><?php echo Yii::app()->getUser()->getCartId() ?></div>
Then parse it later
<script>
(function() {
var the_id = +($('#foo').html()); // or parseInt
// or JSON.parse if its a JSON
if (window.cart) {
cart.id = the_id;
}
})();
</script>

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.

How to pass json array of one page into another in php?

i have a php page p1.php where in a JavaScript function i have got some json array as j now i want to use this j to another php page p2.php
i have tried it by
window.location.href="p2.php?data="+j
then in p2.php
i used $_get['data'] to get the result
but after researching i come to know the format is not good for huge data.
so
i leave the idea of passing it into the url
if your j is object then you can post with jquery
example :
$.post("p2.php", { datavar : j},function(data){
})
in your p2.php
print_r( $_POST["datavar"]);
echo $_POST["datavar"]["var2"];
it's depends of many data you can move, but always is ugly send pure data by url.
But in your example, only miss transform the json (object) to string:
window.location.href="p2.php?data="+JSON.stringify(j);
If you can go in the right way, store the info in a session:
http://php.net/manual/es/reserved.variables.session.php
Then the p1.php looks like these:
<?php
session_start();
$_SESSION['json'] = isset($_POST['json']) ? $_POST['json'] : null;
// other php stuffs
?>
<!-- other html stuffs -->
<script>
var json = { your: 'json' };
(function(){
var xhr = new XMLHttpRequest();
var data = encodeURIComponent(JSON.stringify(json));
xhr.open('post', 'p1.php');
xhr.send('json='+data);
})();
</script>
These code send the info (json) via AJAX to p1.php

How do I send a variable name and its value to the server and receive back a calculated response

I am new to wordpress and plugins but have a reasonable grip on php, javascript and html. I have created a plugin for wordpress which generates a page (form) which gathers information regarding a product specification. [It is actually a number of sequential forms, but for simplicity lets say it is one. I do not want to "submit" the form as there are many fields on each form and I do not want to "submit" until it is completed and they are ready to move to the next form].
I would like to be able to (re)calculate the product price when the user changes a parameter. To do this I would like to be able to pass the name of the changed parameter and its value back to the server (where all of the dependant data for the calculation is stored), and do the calculation and return the new price. At present I have a javascript function which is called with the pertinent data on an "onChange" and then modifies the div which represents the total price. this works if I compute the value locally, but now I am looking to complete the function by sending data to the server and receiving the calculated response e.g. :
function total_price(arg,value) {
***** send arg and value to server *****
***** receive total_price back from server *****
var total_div = document.getElementById("total_price");
total_div.innerHTML = "£"+total_price;
}
What code should I be putting in here and what should I have on the server in order to receive the data, do the calculation and send back the result?
I mostly have jQuery loaded in the front-end, so I'll post an answer using the jQuery framework. You'll most probably find a good vanilla snippet elsewhere if you're not looking to load a javascript library.
Front End
var html_price = 1; // Whatever you need here
// You'll notice that the ajaxurl variable below, is sent to the front-end in the second code snippet of this answer
$.post( ajaxurl, {
action: "get_total_price", // action is a special parameter Wordpress is listening for
price: html_price
}).done( function( price ) {
// Price back from the server you can use in the DOM
// You should probably send this using JSON, this example only uses a string
console.log( price );
});
Back End
// Here is where Wordpress is waiting for that special action parameter
// https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add_action( 'wp_ajax_get_total_price', 'get_total_price' );
add_action( 'wp_ajax_nopriv_get_total_price', 'get_total_price' );
function get_total_price() {
$price = $_POST[ 'price' ];
if( $price ) {
// do with the price what you want
echo $price; // Echo instead of return
exit; // Remember to close up the server response here
} else {
echo '0'; // Unrealistic, but guarantees a response
exit;
}
}
// Send the AJAX URL to the front end. There are more elegant ways to do this, but for the purpose of this answer, this should work.
add_action( 'wp_head', 'add_ajaxurl_to_head' );
function add_ajaxurl_to_head() { ?>
<script>
ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }
At last I got it working (based upon your code and grasping the difference between the server and client contexts, which language to use where and what data is accessible). Thanks for your help. There must be scope for a single language for web development which is readable and context aware? HeHo, there I go wanting the world to change to suit me!!

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

Using ajax in zend framework 2

i am really new to the zend framework 2 and to the programming of web applications. In my application, i want to have a button which triggers a function that changes the content of a database and returns a String which i can use to update the visible content of the website. As i don´t want the website to reload when the button is clicked, i would like to do this using ajax. After reading a couple of ajax tutorials, i imagined that the solution would look somilar to this:
The HTML part:
<head>
<script type="text/javascript">
function myFunction() {
var xmlhttp = new XMLHttpRequest();
// I am working with Chrome
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var text = xmlhttp.responseText;
document.getElementById("text_paragraph").innerHTML =
text;
}
};
xmlhttp.open("GET", "function.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
......
<button id="function_button" onClick="myFunction()">Click</button>
<p id = "text_paragraph">Initial text"</p>
......
</body>
With the .php file function.php (for the beginning, i just want it to return a text value) :
<?php
echo "Text triggered by the button click";
?>
When i try to test the button, nothing happens. Apparently, the xmlhttp.status is 404 and the function.php file can´t be found. I suppose that either the location where i put the function.php file (it is in the same folder as the .phtml - view file of the website) or the url i´m using in the xmlhttp.open - function is wrong. Could you please tell me how to use ajax in zf2 correctly? Thank you for your time, every answer is very much appreciated.
First of all i want to thank for all your answers. They really were a great help. Using jQuery is indeed much more comfortable, and not only for Ajax calls, than using pure Javascript. James, thank you very much for your answer. I tried to use it, but i probably did something wrong because it did not work. I found another solution for my problem and i want to post it here in order to round this question up.
The code that i am going to post is a little example that just does a simple thing: on a user click on a button in a website created by zend framework 2, an input field is read, the content of it is transfered to a server function, which, according to the data it receives, returns a certain result. After receiving the result, the website is updated without being reloaded.
As i am going to use Json objects for the communication, it is necessary to activate the Json strategies in zf2 by adding the following codeline to the module.config.php:
// module/Application/config/module.config.php
'view_manager' => array (
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array (
'layout/layout' => __DIR__ .
'/../view/layout/layout.phtml',
'application/index/index' => __DIR__ .
'/../view/application/index/index.phtml',
'error/404' => __DIR__ .
'/../view/error/404.phtml',
'error/index' => __DIR__ .
'/../view/error/index.phtml'
),
'template_path_stack' => array (
__DIR__ . '/../view'
),
'strategies' => array ( // Add
// this
'ViewJsonStrategy' // line
)
),
The view file of the website (called, for example example.phtml) will look similar to this:
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
//Function, activated by clicking the button
$("#trigger").click(function(){
var text = $("#input_to_read").val();
var myData = {textData:text};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:"/example/answer",
data:myData,
success: function(data){
//The callback function, that is going to be executed
//after the server response. data is the data returned
//from the server.
// Show the returned text
$("#answer").text(data.text);
},
failure(function(){alert("Failure!!");})
});
});
</script>
</head>
<body>
<input id="input_to_read" type="text">
<button id="trigger">Klick</button>
<!-- The answer will be shown here. -->
<p id="answer"></p>
</body>
</html>
The server function, that is going to be called when the button is clicked, is placed in the controller for the website (in this case, the ExampleController) and could look like this:
//Make sure to add this line to use Json objects
use Zend\View\Model\JsonModel;
....
public function answerAction(){
#read the data sent from the site
$text = $_POST['textData'];
#do something with the data
$text = $text . "successfully processed";
#return a Json object containing the data
$result = new JsonModel ( array (
'text' => $text
) );
return $result;
}
Typically the way I would handle this, is to build an RPC controller to just return JSON, and then use some good javascript frameworks like jQuery, and Knockout JS, to dynamically update the relevant UI areas. I believe the base Zend controller class provides a $this->_helper->json method that will return JSON instead of returning what you have defined in a given view. In the case of Public_RpcController below I didn't even define a view at all. It returns JSON which I can use in conjunction with JS frameworks for client side markup manipulation. Using the JS frameworks has a bit of learning curve but well worth learning.
class Public_RpcController extends MySubClassed_Controller_Action
{
public function getUserDataAction()
{
$output = array();
$request = $this->getRequest();
...
$output = array(
'Value1' => "foobar",
'Value2' => "foobar",
);
return $this->_helper->json($output);
}
}
// Use Jquery to fetch JSON data to update.
$.getJSON( "/rpc/get-user-data", function( data ) {
// Do something with the JSON data like bind to Knockout template.
});

Categories

Resources