Can I use PHP value in JavaScript? - php

I’m using below a simple Jquery code to call a PHP page and get the button information back in a div:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
How can I get the PHP information inside JavaScript, as follows:
alert(<?php echo('buttonPHP'); ?>);
Note: The following code shows the alert box message, but I can’t use it since I need the $buttonPHP value:
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data){ alert(data); });
I’ve tried $_SESSION in myPHPfile.php, and also all jQuery AJAX functions: load(), get(), post() and the ajax() method, none of them is giving the PHP value inside JavaScript.
I looked all over but I couldn’t find an answer.

You would be better with an $.ajax request. Don't echo the 'Value of button is' part, just echo the actual value. For example:
$.ajax({
url: "myPHPfile.php",
context: document.body
}).done(function(data) {
var buttonValue = data;
// Whatever you want to do with the data goes here.
});
See the jQuery docs http://api.jquery.com/jQuery.ajax/
Alternatively, if you are generating the page with PHP, just echo the PHP variable into the JavaScript
<script>
...
var buttonValue = "<?php echo $buttonPHP; ?>";
...
</script>

Encode it in JSON instead of trying to echo the data :
<?php
if( $_GET["selectedButtonValue"] )
{
$buttonPHP = $_GET['selectedButtonValue'];
header('Content-Type: application/json');
echo json_encode($buttonPHP);
}
?>
Then use jquery get json to grab the data
$.get('myPHPfile.php?selectedButtonValue='+buttonvalue, function(data){
console.log(data);
});

Try:
alert('<?php echo $buttonPHP; ?>');

As a temporary solution, you could quickly merge both into a dirty code like this:
index.php:
<?php
$buttonPHP = "10"; //Set up your default button variable
if( $_REQUEST["selectedButtonValue"] == 10 )
{
echo "Selected button value: 10"; //You can also print $_REQUEST["selectedButtonValue"] here directly, but what's the point if you can select it from DOM through jQuery?
exit;
} else if ($_REQUEST["selectedButtonValue"] == 20) {
echo "Selected button value: 20";
exit;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $buttonPHP ?>; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
index.php rendered in browser:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = 10; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
EDIT: Stored session
<?php
session_start();
if (isset($_REQUEST['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = $_REQUEST['selectedButtonValue'];
echo $_REQUEST['selectedButtonValue'];
exit;
} else if (!isset($_SESSION['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = 10;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?>;
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv"><?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?></div>
</body>
</html>
Also make sure you filter the $_REQUEST variable, because as of now, it will print anything. See http://en.wikipedia.org/wiki/Cross-site_scripting for details.

Related

How to handle multiple requests with the help of one function in AJAX?

view
<?php
for(condition)
{
?>
<input type="hidden" name="pid" value="<?php echo $data1->id; ?>">
</i>
<?php
}
?>
AJAX
<script type="text/javascript">
$ (document) .ready(function() {
$('[name="like"]') .click (function() {
var pid = $('[name="pid"]').val();
alert(pid);
});
});
</script>
Expected Result:-
If I click on like anchor tag it should show me different id for different posts and I don't want to reload my page.
Actual Result:-
It is showing me the first id when I click on different like tags of different posts.
I am new to AJAX.
Thanks in advance.
view
<?php
for($i=0;$i<count($data1);$i++)
{
?>
<input type="hidden" name="pid#<?=$i?>" value="<?php echo $data1->id; ?>">
</i>
<?php
}
?>
AJAX
<script type="text/javascript">
$ (document) .ready(function() {
$('[name="like"]') .click (function() {
$name = $(this).split("#");
var pid = $('pid'+$name[1]).val();
alert(pid);
});
});
</script>
you place the input and a inside the div and then get the a's sibling which is the input
<?php
for (condition) {
?>
<div>
//Your input and a tag here
</div>
<?php }
?>
<script>
$('[name="like"]').click(function () {
var input = $($(this).siblings("input")[0]); // get the input element
var value = input.val(); //value of the input
alert(value);
});
</script>
You are setting same name for all the input.
If you don't need input field as hidden then you can use attribute to set and get the value of your post.
<?php
for(condition)
{
?>
<input type="hidden" name="pid" value="<?php echo $data1->id; ?>">
</i>
<?php
}
?>
You can use class name to access the attribute of anchor tag.
<script type="text/javascript">
$(document).on('click', '.select_id', function(){
var pid = $(this).attr('data-pid');
alert(pid);
});
</script>

PHP submit form without refreshing

When the user submits the form, the result should be displayed without page refreshing. The PHP script is also in the same HTML page.
What is wrong withe $.post jQuery?
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btn").click(function(event) {
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $("#testform").serialize()
);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform">
<!-- $_SERVER['PHP_SELF'] array -->
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
You need to use event.preventDefault in your javascript
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $( "#testform" ).serialize()
);
});
Yes, you need e.preventDefault. Also, I think these var myname and myage variables are unnecessary since you're serializing the entire form in $.post.
Try this:
$(document).ready(function() {
$("#btn").click(function(e) {
e.preventDefault();
$.post(
"23.php", $("#testform").serialize()
);
});
});
Hope this helps.
Peace! xD
This is my finalized complete code after following your all suggestions. But it is still refreshing when getting results. Let's see if I have made any further error in the code. Thanks for your all helps.
UPDATE! - All these HTML and PHP scripts resides in the same file called 23.php
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform"> <!-- $_SERVER['PHP_SELF'] array -->
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
<input type="submit" name="submit" id="btn"/>
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { //was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>

why i cannot pass json data to another PHP file?

i have two php files home.php and ajax.php. i have two buttons on home.php. when they are clicked the according php functions in ajax.php should get called.
home.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
</html>
ajax.php
<?php
echo 'this was called';
echo $_POST['action']; //THROWS AN ERROR undefined index 'action'
if ( isset( $_POST['action'] ) ) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
the problem is the json data i assign to data property in jquery code will not get passed to the ajax.php. Is there any reason why it doesn't not pass it?
here is my youtube video on the error video
There are two possibilities, depending of what you want to achieve afterwards.
Eighter you stick on doing a backgroud ajax-call to ajax.php and then do with the response whatever you want (that's what I'd suggest):
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).id(); // changed to id here!
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
console.log(response); // log what the response is
alert("action performed successfully and the resonse is: \n"+response);
// do with that data whatever you need
});
});
});
</script>
</head>
<body>
<!-- changed to buttons, removed the form -->
<button class="button" id="insert">insert</button>
<button class="button" id="select">select</button>
</body>
</html>
or you submit the form and output on screen the response from ajax.php:
<html>
<head>
<!--script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script-->
<script type='text/javascript'>
// no need for any javascript then
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
and in ajax.php:
<?php
echo 'this was called';
if ( isset( $_POST['insert'] ) ) {
insert();
}
if ( isset( $_POST['select'] ) ) {
select();
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
try
$.post(ajaxurl, data)
.done(function( r ) {
alert("action performed successfully");
});
I like to use the jQuery on() and to be sure post has worked, I moved in your variables as such. Also you can try to do console.log(clickBtnValue) after the click to be sure you are able to see the value itself. After confirming, the post() should send that value into action post param.
<script type='text/javascript'>
$(document).ready(function(){
$('.button').on('click',function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
$.post(ajaxurl, {action:clickBtnValue}, function (response) {
alert("action performed successfully");
});
});
});
</script>
If you need to do a ajax call, remove the following part from the home.php
<form action='ajax.php' method="POST">
</form>
I think you are messed up with Ajax technology and the form post mechanism.

Not getting jquery Ajax data using dynamic id selector

My PHP code looks like this -
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>"></input>
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</Submit>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
I want to get the data of these <input> elements using jquery dynamic id selectors. My jQuery looks like -
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("[id^=SelectPostComment-]").click(function(){
var $td = $(this).closest('input').next();
var CommentText = $td.find("[id^=GetCommentText-]").val();
var PostID = $td.find("[id^=GetPostID-]").val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
But I'm not getting value of ajax data CommentText and PostID in my test1.php file when i click <button>. Not sure what mistake I'm making. Please help.
try this:
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>" />
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('[id^="SelectPostComment-"]').click(function(){ // changed here
var $td = $(this).parent(); // changed here
var CommentText = $td.find('[id^="GetCommentText-"]:first').val(); // changed here
var PostID = $td.find('[id^="GetPostID-"]:first').val(); // changed here
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
Or You could use more efficient way (no need to make garbages in DOM Tree):
<?php
for ($i=0;$i<=10;$i++) {
?>
<div data-postId="<?php echo $i; ?>">
<input type="text" name="commentText" value="" />
<button type="button" class="submit-comment">Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.submit-comment').click(function(){
var $parent = $(this).parent();
var postId = $parent.data('postId');
var commentText = $parent.find('input[name="commentText"]:first').val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: commentText, PostID: postId},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>

how to submit the form without refreshing the page

this is my html code when i click on submit button it displays alert and then when i open the retrieveform.php it does not show me the value please solve this mystery
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function () {
alert('helllo');
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text"name="t1">
<input type="submit"name="s1"value="submit">
</form>
</body>
</html>
and my retrieveform.php is
<?php
if($_POST['t1'])
{
echo $_POST['t1'];
}
else
{
echo "hekllojjio";
}
?>
Is it possible that the element "t1" is present since it's part of your form, but empty or just empty characters .. perhaps check if this is the case?
<?php
if($_POST['t1'] && !empty($_POST['t1'])) {
echo "You submitted t1 of: ".$_POST['t1'];
} else {
echo "t1 is empty";
}
?>
Also of note is you may want to use something like firebug to view the ajax page loaded and its results. The echo statement on the ajax loaded page will not display on the parent page unless you set the contents of the response into the page:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$('.form').on('submit', function (e) {
tValue = $(this).find(input[type=text]:first).val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function (response) {
alert('helllo');
$('#placeholder').html(response);
$('#placeholder2').html(tValue);
}
});
});
});
</script>
</head>
<body>
<?PHP for ($i = 1; $i <= 10; $i++) { ?>
<form class="form" name="form_<?PHP echo $i; ?>" id="form_<?PHP echo $i;?>">
<input type="text" id="t<?PHP echo $i; ?>" name="t<?PHP echo $i; ?>">
<input type="submit" name="s<?PHP echo $i; ?>" value="submit">
</form>
<?PHP } ?>
<div id="placeholder"></div>
<div id="placeholder2"></div>
</body>
</html>
with this your ajax loaded page's echo will be put on the page in the "placeholder" div.

Categories