Ways to pass php post data to javascript - php

So I was wondering, if I have a simple php form that posts information to a certain variable, how can I pass that posted variable to javascript and be able to manipulate the data? The only way I've figured out is by using inline javascript with php but I feel there must be a cleaner and more elegant way to do it where the variables don't show up so blatantly in the source code and are handled externally.. Here's what I'm playing around with right now:
<form action="index2.php" method="post">
<input name="sugar" class="form" type="text" value="" />
<input name="fat" class="form" type="text" value="" />
<input name="protein" class="form" type="text" value="" />
<input type="submit" value="submit" />
</form>
Which is followed by:
<?php
$sugar = $_POST['sugar'];
$fat = $_POST['fat'];
$protein = $_POST['protein'];
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var sugar = "<?php echo $sugar ?>";
var fat = "<?php echo $fat ?>";
var protein = "<?php echo $protein ?>";
</script>
<script src="test.js" type="text/javascript"></script>
</head>
Does anyone have any suggestions for alternatives I could follow? I haven't been using javascript for too long so it would be nice to know my options when dealing with a situation such as this.

The easiest way to do this would be simply to send a Javascript object containing all the data you sent. This can easily be accomplished by JSON-encoding $_POST:
var data = <?php echo json_encode($_POST) ?>;
You can then access, for instance, data.fat if you sent a fat value in your POST request.

Without using _GET as well and storing the variables in the URL you have the best solution for your requirements currently.

These variables will have to be printed and visible somewhere if you want to get them to your JavaScript.
JSON-encoding them and printing them so that they're saved in a local JavaScript variable is what I've always been using:
<?php
function passToJavascript($variableName, $variable){
if($variable = json_encode($variable))
echo '<script>var '. $variableName .' = '. $variable .';</script>';
}
$foo = array(
'bar1' => 1,
'bar2' => 2,
'bar3' => 3
);
passToJavascript('foo', $foo);
?>
Will print in your HTML:
<script>var foo = {"bar1":1,"bar2":2,"bar3":3};</script>
And that way you can pass whatever variable you want, may that be a string, a number, an array or even an "associative array".

I feel like the best way to pass php variables over to javascript variable is to json_encode them first. If you are passing a php array over to javascript you can't simple say
var1 = <?php echo $var1; ?>
you should do it like the follwing.
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
?>
<script type="text/javascript">
var arr = "<?php echo json_encode($arr) ?>";
</script>

You could write your vars in inputs and then reach these inputs with javascript
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//You already linked jquery so I use it, you could do without if necessary.
$(document).ready(function(){
var sugar = $('#sugar').val();
var fat = $('#fat').val();
var protein = $('#protein').val()
});
</script>
var sugar = "<?php echo $sugar ?>";
var fat = "<?php echo $fat ?>";
var protein = "<?php echo $protein ?>";
</script>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
<input type="hidden" id="sugar" value="<?php echo $sugar ?>" />
<input type="hidden" id="fat" value="<?php echo $fat?>" />
<input type="hidden" id="protein" value="<?php echo $protein?>" />
</body>
</html>
That way your javascript can all reside in a static file.

you could try sending your variables with GET instead of POST, and then you can access them directly from javascript like this: http://javascript.about.com/library/blqs1.htm
There is no way to access POST variables from javascript, as far as i know. You would have to use something like you are doing

Related

retrieve PHP post values in submit using jquery

I want to retrieve post values in php in jquery form, so as to submit the form using jquery. I am using jquery.submit() function to submit my form. Example is as below
$('#form').submit(function{
var data = '//post variables from php script here';
$.ajax({
type:'post',
data:data,
url://url to save the data,
success:function(response){
//success message here;
}
});
Can anyone please help me?
I don't know exactly what you want to do, but as far as I can see it seems that you need json_encode php function.
var data = '<?php echo json_encode($_POST)?>';
You cannot directly extract POST variables in JavaScript - which you can with GET since they are part of the URL (?my_get_variable=is_here etc.)
If you really NEED to have access to your POST variables in JavaScript, what you could do is make some PHP iterating over and printing out the post variables. The following code fills a JavaScript array called PostVariables with the post variables passed to your page:
<script type="text/javascript">
var postVariables = new Array();
<?php foreach($_POST as $key => $value): ?>
postVariables['<?=$key?>'] = '<?=$value?>';
<?php endforeach; ?>
</script>
If your POST body is name=John&pet=Cat&friends=Many, you will get the following code:
<script type="text/javascript">
var postVariables = new Array();
postVariables['name'] = 'John';
postVariables['pet'] = 'Cat';
postVariables['friends'] = 'Many';
</script>
Of course, this does require PHP.
If you need the data in that format, just adapt the script:
<script type="text/javascript">
var myData = "";
<?php foreach($_POST as $key => $value): ?>
myData += "<?=$key?>=<?=$value?>&";
<?php endforeach; ?>
</script>
You can post form data with serialize. Example form:
<form id="myForm" method="POST">
<input name="one" value="11" />
<input name="two" value="22" />
<input id="submit" type="submit" value="11" />
</form>
<div id="test"></div>
Javascript
<script type="text/javascript">
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
data: $("#myForm").serialize(),
url:'mypage.php',
success:function(response){
$("#test").html(response);
}
});
});
</script>
mypage.php
<?php var_dump($_POST); ?>
output
array (size=2)
'one' => string '11' (length=2)
'two' => string '22' (length=2)
Solved myself. Had been using the plugin jquery form on my site. Implemented the form submit using same.
http://malsup.com/jquery/form/#ajaxForm

Javascript variables to php variables

I have string value in input box
<input name="to" value="hi.rand(1,10). my.rand(10,100).name is .rand(23,54).rand(1,4)" >
How to use $_GET['to'] if i want have
hi5 my54name is 335
Now i have got string "hi.rand(1,10). my.rand(10,100).name is .rand(23,54).rand(1,4)" but not execute like php function.
So how to format string in input box so PHP take it like variables.
You can create javascript using php. Something like this:
<script type="text/javascript">
<?php
$anyVar = "BONJOUR";
?>
var value = "<?php echo $anyVar; ?>" ;
alert(value);
</script>
In the example I'm passing the value of my var $anyVar in PHP to the value var in javascript. So after the page loads and the script is parsed, you'll end up with something like this:
<script type="text/javascript">
var value = "BONJOUR" ;
alert(value);
</script>
You can as well write js code like this:
<script type="text/javascript">
<?php
$anyVar = "BONJOUR";
?>
var value = "<?php echo $anyVar; ?>" ;
<?php echo 'alert(value);' ?>
</script>
Hope this helps.

How do I send url parameters via GET method to PHP with JavaScript?

Here's my JS code...
function da(){
var a=document.forms["user"]["age"].value;
if(this.age.value < 18 || this.age.value > 85) {
alert('some text...');
this.age.focus();
return false;
}else{
window.location.href='file.php?&'+a;
}
}
It simply passes the parameters to the page where I'm standing...
Here's the form just in case (I'm a beginner keep in mind)...
<form name="buscar" method="GET"> Some text <input onmouseover="Aj2('d');document.getElementById('box').style.display='block';" onmouseout="clean();" type="number" name="age" id="age" > Age <div id="help" ><!-- --> </div><br />
<input type="button" value="Send" onclick="da()">
</form>
The Aj2 function is not the problem here...
Thanks for any help y might get...
Just a thought, if you don't actually have to reload the page and just want to get information to your javascript code from PHP, you could do something like
<script>
<?
$phpvariable = "my variable";
?>
var jsvariable = <?php echo json_encode($phpvariable); ?>;
</script>
Now the javascript variable, jsvariable, will hold the PHP variable's content.
Some thing like this I am not a expert.
$('button name').on('click', function() {
var age_ = document.getElemenetById('age');
$.get('path of your file', {'age' : age_}, function(resp) {
// code to pass parameter
alert(age_);
});
});

Pre-fill a form (no control over form code)

I'm using a form plugin / addon where I don't have control over how the form is generated.
The form generates HTML which looks like this:
<form>
<label>First Name</label><input name="Question25" type="text" value="" />
<input class="formBlockSubmitButton" name="add" type="submit" value="Submit" />
</form>
I would like to prefill some of the form values but I can't write, say
<input name="Question25" type="text" value="<?php echo $my_value; ?>" />
Because the form addon generates that HTML. I can write PHP or Javascript before this block, is there a way to search for an input with a name of "Question25" and then prefill it when the block comes up?
You could use jQuery and the .val() method:
<script type="text/javascript">
$(function() {
$('input[name="Question25"]').val('some value');
});
</script>
and if the value must come from the server:
<script type="text/javascript">
$(function() {
var obj = <?php echo json_encode(array('value' => $my_value)); ?>;
$('input[name="Question25"]').val(obj.value);
});
</script>
You can emit all the values you'd like to search as an array of fieldname/values, and then emit a function that tries to map those values to those fields.
<script type="text/javascript">
var values = [{fieldName:'Question25', value:'MyValue'}]; // iterate through your values in PHP and generate the {fieldName:'value',value:'value'} object
$(function() {
$.each(values, function(index, item) {
$('input[name=' + item.fieldName + ']').val(item.value);
});
});
</script>
var value='<?php echo $my_value; ?>'
$("input:text[name='Question25']").val(value);
use something like this
Use Javascript. With jQuery, you could do something along the lines of:
$("input[name=Question25]").val(my_value);
You can then insert PHP vairables into the Javascript with echo, load them with AJAX, or whatever you need.

Why is $_POST empty when I can see the POST variables in firebug?

I am posting a form in an expressionengine (1.6.8) template. I'm doing it using jquery but have tried an HTML form too - same result. The PHP superglobal $_POST is empty after posting the form, even though I have PHP enabled on my templates (on input for the template containing the form and output on the processing template) and can see the POST variables in firebug.
Can anyone suggest what might cause this?
<html>
<head>
<script type="text/javascript" src="/_scripts/jquery-1.6.1.min.js"></script>
</head>
<body>
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(e){
e.preventDefault();
var path = "/select-locale/processing"
var form = $('<form/>');
form.attr("method", "post");
form.attr("action", path);
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", 'locale');
field.attr("value", 'NZ');
form.append(field);
$('body').append(form);
form.submit();
});
});
</script>
</body>
</html>
server-side code (inherited, not my own) :
<?php
var_dump($_POST);
var_dump($_GET);exit;
if ( ! isset($_POST['locale']))
{
$locale = FALSE;
$returnPage = "/";
}
else
{
$locale = $_POST['locale'];
$returnPage = $_POST['returnPage'];
}
if (isset($_GET['locale'])) {
$locale = $_GET['locale'];
$returnPage = "/";
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"} <?php
}
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"}
{exp:session_variables:get name="testSession"}
{if '{exp:session_variables:get name="testSession"}'=='yes' }
{redirect="<?php echo $returnPage;?>"}
{if:else}
{redirect="/nocookies/"}
{/if}
check the network tab if the parameters you want are really sent out
check the url if it's correct
if you use any sort of routing mechanism or url rewrite, you might wanna review it also
check your validation and XSS rules (if any) as it may reject the whole array once hints of XSS is found.
happened to me a while ago (CI) and i was sending it to the wrong url
You might want to re-check the action attribute, are u sure you're sending the data to the right url? I doubt that anything could be filtered.
it seems like form is getting submitted twice because of either action attribute of form tag or oath value in jquery function
It may be useful
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body name="test">
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(){
var form ='<form action="/select-locale/processing" name="newform" method="POST"><input type="hidden1" name="locale" value="NZ"></form>';
$('body').append(form);
alert('added');
document.newform.submit();
});
});
</script>`

Categories