How to print JavaScript with PHP - javascript

I need to pass some JS variable to PHP and am having some trouble.
I have tried the following:
$product_id = "<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id')</script>";
echo $product_id;
But this just prints it as a string:
`<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id');</script>`
How would I store that JS variable and then echo it using PHP? I am quite new to PHP, so any help would be appreciated!

By doing it your way, it's just impossible. PHP can't "read" or "interact with" javascript directly in the same page.
You have to understand that PHP is a preprocessor, it generates HTML on the server, then the generated page is sent to the client. In this page, the PHP code has entirely disappeared. You can only see what it generated (that is, HTML or JS). Then, the javascript code runs, and it has no idea it was generated using PHP, and no idea of PHP's presence whatsoever.
In order to pass variables to a PHP script, you have to call the file with GET or POST methods :
(JS)
$.get( 'myScript.php', { // This is calling the PHP file, passing variables (use get or post)
variable1 : "Hello",
variable2 : "world!"
}, function(data){ // PHP will then send back the response as "data"
alert(data); // will alert "Hello world!"
});
(myScript.php)
$variable1 = $_GET['variable1']; // or POST if you're using post
$variable2 = $_GET['variable2'];
echo $variable1 . " " . $variable2; // Concatenates as "Hello world!" and prints it out.
//The result of the PHP file is sent back to Javascript when it's done.
Of course, this is a very basic example. Never read and use directly what is sent to PHP (as I just did), because anyone could inject whatever they'd want. Add securities.

JavaScript runs on the client side while PHP runs on the server. They execute at completely different times in the page lifecycle, so they cannot communicate in the manner you have used.
Instead you could to use AJAX to send a value in JS to a PHP page.

Thanks for the assistance, very much appreciated! I have managed to get it done by using ajax as suggested:
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
var prod_id_one = $('#prod1').val();
var prod_id_two = $('#prod2').val();
var prod_id_three = $('#prod3').val();
var prod_id_four = $('#prod4').val();
$.ajax({
type: "GET",
url: "my_ajax_url_here",
data: data,
success: function(data){
window.location = "price-calculator?width="+ $('#wpti-product-x').val() + "&height=" + $('#wpti-product-y').val() + "&id1=" + prod_id_one + "&id2=" + prod_id_two + "&id3=" + prod_id_three + "&id4=" + prod_id_four;
}
});
return false;
});
});
</script>
It is now working with the above code. Thanks again!

Related

how to recover and pass multiple php variables in my AJAX call

I need to pass my PHP variables defined (earlier in my page) in my Ajax call.
And I have a lot of variables defined so I cannot do it var by var in my code.
My first question is, is there a way in PHP to loop on every defined variable ? like get my $var1, $var2
I think I could do it earlier in my PHP page between <script> tags but this is really not clean.
My AJAX call is like so:
function add_content_in_divs(class_name, target_div) {
var page_name = 'displayer/' + class_name + '_informations.php'
$.ajax({
url:page_name,
type: 'GET',
data: {//need to pass my PHP vars here},
success: function (resp){
target_div.html(resp);
}
})
}
My final goal is to include a part of PHP code in my div, knowing that this include contains $vars defined in my main PHP page. So my includes parts of code doesn't recognize my PHP vars in.
There is an example of code part I have to include.
if (isset($detail)) {
echo '<div class="row"><span class="font-weight-bold">City detail: </span>' . $detail . '</div>';
}

What goes into Responce in jQuery AJAX?

I'm sorry to add this broad question here, but I cannot seem to google it myself, I tried, and I really can't grasp the idea behind this, so here goes.
So I have a web-site that uses AJAX to login a user without full page reload. I kind of understand how AJAX works, and I'm sorry for my ignorance, but in my case:
$.ajax({
url: './',
type: 'POST',
data: {auth: auth, login: login, pass: pass}
success: function(res){
// Code that checks if **res** is a specific string
},
error: function(){
alert("Error!");
}
I understand that this sends POST request to the same page with 3 parameters. What I don't understand is what specifically does it get as a responce? In my case, in res is the $_SESSION element that contains the string message.
My question is: how do I know what gets in the responce? If I would just echo something in my function, would that get in the responce? Is there like a documentation about what can be passed to the arguments of success function?
I'm really confused about this.
The "res"... or commonly "data" in most examples, is simply the reply data from your page that your posting to..
So say in the case of PHP... you yes would simply echo anything back to it.
commonly people use JSON, so with php you would create a array with all the data you want to send back and then simply do
YOUR PAGE THAT SENDS THE POST
<script>
// JUST USING SUCCESS HERE ATM (Tthis does not show the full ajax command)
// Refer to original question for full javascript
success: function(res){
var myData = $.parseJSON(res);
if(myData.hasOwnProperty('name')){
alert(myData.name);
}
if(myData.hasOwnProperty('object1') && myData.object1.hasOwnProperty('items')){
alert(myData.object1.items.one);
}
},
</script>
YOUR PHP PAGE THAT RESPONDS
<?php
$myResponse = array();
$myResponse['name'] = "John Doe";
$myResponse['number'] = 123456789;
$myResponse['other'] = "and so on";
$myResponse['object1'] = array();
$myResponse['object2'] = array();
$myResponse['object1']['name'] = "john";
$myResponse['object1']['items'] = array();
$myResponse['object1']['items']['one'] = "one one 1";
$myResponse['object1']['items']['two'] = "two two 2";
$myResponse['object2']['name'] = "jane";
echo json_encode($myResponse);
?>
By using a "multidimensional" array in php, you can then treat each part of the array as a separate section/object
This might help: http://www.thecave.info/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
Well, I think that what you "echo" is what you will retrieve in the "res",
try to see it in the console with:
console.log(res);
Or with an alert
alert(res);
try console.log(res); and check the browser console
ctrl + shift + k (firefox)
f12 (Chrome & IE)
For you task I would recommend using getJSON, instead of .ajax. It's just a shorthand for the same function, but really handy.
$.getJSON('/ajax-get-session/login/value/pass/value', function(json){
if (!json.error) { //check if there wasn't error on the server side
console.log(json.session);
} else {
console.log(json.error);
}
});
And on the server side.
$response = array();
try {
$response['session'] = $_SESSION;
}
catch (e) {
$response['error'] = e;
}
echo json_encode($response)

How to convert javascript variable into php variable?

Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
<?php
include "accounts/config.php";
$phpvar='"+str+"';
mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')");
//echo $phpvar;
?>;
})
});
As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({
"savesample.php",
{myPostVar: str}
}).done(function() {
alert("sample saved.");
});
Of course you need a serverside script to handle this request:
<?php
$yourVar = $_POST["myPostVar"];
// TODO use mysqli::escape_string or similar!!
mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script>
<![CDATA[
var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
CORS
SQL injection
Authenticated AJAX calls
You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.
Look up Jquery post for more information.
The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.
On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!
So for instance (using JQuery)
$.ajax({
url:"someurl",
type:"POST or GET",
data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
datatype:"JSON", //This is the return type of the information you want if any
success: successfulHandlerfunction()
error: errorHandlerfunction()
});
That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/
I hope this helps!
JS
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
$.ajax({
type: "POST",
url: "save.php",
data: {items: str},
success: function(responce) {
alert(responce);
}
});
});
Create save.php file
<?php
include "accounts/config.php";
$items = $_POST['items']; // Validation HERE!!!
foreach ($items as $item) {
// Insert to DB
}
echo 'Saved';
?>
Separate languages = separate files. (if you can...)
In PHP always check user input.
Use PDO.
This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:
Client(browser):
$.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
alert("Variable was successfully sent.");
}});
Server(Apache)
config.php
<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

Send variable that contains an equation through ajax and return it to jquery fully computed

im trying to write a code where i will be able to send a variable that contains a mathematical equation through ajax and have it computed using php
the problem that i am getting is that once the php it returns the variable to jquery it doesnt compute it and still returns it as an equation
this is how i made it
jquery
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
var compute = firstnum+operator+secnum;
content = {compute:compute}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
php
<?php
$compute =$_POST['compute'];
echo $compute;
?>
for example the content of my variable compute is...
10+10
the php will still return it as is
what i want to happen is once it comes back from php it will return as
20
is there a way to make this happen?
thanks
If you want PHP to compute it, you should write something like this. Because when you send 10+10, PHP sees it as a string.
Javascript:
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
content = {first_number:firstnum,second_number:secnum,operator:operator}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
And at the PHP:
<?php
$content = $_POST['content'];
if( '+' == $content['operator'] ){
echo $content['first_number'] + $content['second_number'];
}
else if( '-' == $content['operator']){
//extraction
}
// so on..
?>
You must have a calculator script on server side in PHP.
The mathematical expression must be parsed. You could use something like this
http://20xxproductions.com/code-samples?s=phpsc
for parsing more complex expressions.
If you have to process simpler ones you can specifiy an operator and give both numbers as extra POST variables.

How to read the post request parameters using JavaScript

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.

Categories