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

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

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.

php encoded json to template and javascript

I'm using Codeigniter and Smarty (template engine) and therefore using templates.
I have a method that calls the template which has all html, css and js functions:
public function index()
{
//dashboard text
$this->data['title'] = 'Dashboard';
$this->data['subtitle'] = 'feeds, users, and more';
//load the donut graph data
$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);
//parses the dashboard template
$this->smartyci->display('dashboard.tpl', $this->data);
}
the thing is that I need to send some information to one of the js files bounded to my dashboard.tpl in order to render a graphic.
So I know I have to encode the php array into jSon object and send it to the template. But, how do I do this when I have not only to send and echo with the json but also I have to display my template sending for it other information?
The other question is, How do I receive the json and get the data? I'm trying and so far no results:
From my dashboard.tpl:
<script src="{site_url()}application/views/js/test.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
From test.js:
$.getJSON('admin.php', function(data) {
console.log(data.vgro_name);
});
You could set it like
$this->data['fbyg'] = json_encode($fbyg);
And then in your javascript do
var yourVar = <?php echo $fbyg ?>;
A cleaner solution would be to make an ajax call to a function that will return something like
$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);
after the page has loaded.
Edit jQuery ajax get:
$.ajax({
type: "GET",
url: "urlToYourFunction",
success: function(data){
var yourVar = data;
}
});
I've only ever made get and post requests with angularjs and jquery, but here's another stackoverflow post detailing how to do it with regular javascript:
https://stackoverflow.com/a/18078705/3739551
I hope this helps!

Accessing and decoding JSON sent from JavaScript to PHP

So I have a form, I took the contents of its inputs, threw them into an array, had it made into a JSON and then sent it to PHP so it can in turn decode and enter it into a database. I know it'd be easier to just use a <form method="POST" action="phpfile.php"> but I can't have this redirecting to another page, especially since my PHP is not embedded into HTML, instead it handles things offsite. Otherwise it'd be simpler to just use $_POST["name"] to get what I need. Nonetheless, this page in particular is supposed to create the user, receive a server response, that the user has been entered into the database and then is given an alert with a button to be redirected to the main page.
So anyway here are the relevant sections of this whole process.
JavaScript:
window.onload = function findSubmitButton() {
var button = document.querySelector(".send_info").addEventListener("click", serverInteraction);
}
function serverInteraction() {
var xmlhttp;
var inputArray;
var finalArray = [];
var JSONArray;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Your browser is not compatible with XMLHTTP");
return false;
}
inputArray = document.querySelectorAll("input[type=text]");
for(var i = 0; i < inputArray.length; i++){
finalArray[i] = inputArray[i].value;
}
console.log(finalArray);
JSONArray = JSON.stringify({finalArray: finalArray});
console.log(JSONArray);
xmlhttp.open("POST","phpFiles/sendUserInfo.php", true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(JSONArray);
}
PHP:
<?php
$finalArray = json_decode($_POST['finalArray']);
var_dump($finalArray);
?>
That var_dump simply returns a null and using echo gives me nothing, except a warning that my array variable isn't initialized through XDebug. I'm not quite sure what I'm doing wrong here, I've been following this just like the tutorials tell you to do it, and isn't generating the array. I've also tried $_POST['JSONArray']without any luck in case that was how it was supposed to go. Also tried file_get_contents('php://input') which sends an empty string as well.
You can't get your data from $_POST if you put JSON in your post body.
see this question Receive JSON POST with PHP. php can't handle application/json properly.
For your var_dump is empty, try this
var_dump(file_get_contents('php://input'));
var_dump(json_decode(file_get_contents('php://input'), true));
you will see your data.
And if you send your data without change it to JSON, you will get wrong data.
eg: your finalArray is ['a','b','c'] and you send it directly.
var_dump(file_get_contents('php://input'));
you will see php got string a,b,c instead of ['a','b','c']
So if you want to use $_POST to receive data, you need to use application/x-www-form-urlencoded. you can use jquery to do it. see http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
it will serialize your js object into x-www-form-urlencoded and php will handle it properly.
use chrome's dev tools, switch to network and see the request payload and response would be helpful for you.
You are bypassing $_POST by sending the the data as "Content-type","application/json" .
The data will instead be set in the body of request and can be retrieved using file_get_contents("php://input")
For further discussion see file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?
Generally there is no need to send your data as json to php

Yii: best practices to pass data from php to JS

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>

Convert html string (json representation) into actual javascript object

I am printing some php data into a field on my page. The data is json_encoded by the backend.
Now i want to retrieve this information and turn it into a javascript object...
$(document).ready(function(){
$('.trigger-info-change').click(function(){
var rel = $(this).attr('rel');
var td_id = 'info-'+rel;
var data = $('#'+td_id).html();
console.log(data);
});
});
now data is correctly console logging my "object" like this:
{"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}}
Now the question is how do i turn this html into a actual javascript object... I've tried to use jQuery.parseHtml, and some other things google advised but no luck... would i need a script or is there something like that out there?
Thanks in advance!
If you want use Jquery:
var json = $.parseJSON(data)
Or
var obj = JSON.parse(data);
I think this better to print out JSON String in javascipt.
<script>
var data = <?php echo $json ?>;
</script>
Which makes :
<script>
var data = {"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}};
</script>
But if you insist on your way, use JSON.parse(jsonString).

Categories

Resources