Can I convert a php $_POST variable into a jquery variable?

u0867587
u0867587 used Ask the Experts™
on
Hi,

I want to do some calculation in jquery. but I want to do this in a php variable. but to avoid page loading I want the php variable to be made into a jquery variable and then that jquery variable be stored in html. To be honest I want to know would that avoid page loading?

Below is my php variable:

<?php  $postduration  = $_POST['durationChosen']; ?>

Open in new window


I want the above php code to be in a jquery variable and then I want the jquery variable stored in a html. <span> tag.

Can this be done?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Not sure I fully understand but to get something from PHP into javascript you would simply echo it out.

In the <head> of your page you would put

<script type="text/javascript">

var myVar = '<?php echo $_POST['durationChosen']; ?>';

alert(myVar);

</script>

Open in new window

Commented:
Sorry missed your last part about the html.

So if you had something like this in your HTML.  <span id="my-span"></span>

Then you could do.

<script type="text/javascript">

var myVar = '<?php echo $_POST['durationChosen']; ?>';

$('#my-span').html(myVar);

</script>

Open in new window

Author

Commented:
Right, that is great that is part 1 done out of 2. The second part is how can I display "myVar" in a html form. I want it to be displayed in a <span> tag. Do you know how to do this?
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

Author

Commented:
Oh, sorry didn't realise you posted your second comment before my comment. sorry

Author

Commented:
Hi, it worked when I did the alert, but when I try and do it in a span, it does not display anything, I don't know why this is,

Author

Commented:
I tried changing "myVar" from this "var myVar = '<?php echo $_POST['durationChosen']; ?>';" to this "var myVar = 'texting'; to see if it displays 'testing' in the span but still nothing is displayed. Do this jquery method work in firefox?

Author

Commented:
it doesn't work in any browser, so do you know why it isn't working?

Commented:
Here is some code you can try...it works.  Just copy and paste into a blank PHP page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
    <script type="text/javascript">
        var myVar = '<?php echo "testing"; ?>';
        $(document).ready(function(){
            $('#my-span').html(myVar);
        })
    </script>
    <title>Test</title>
</head>
<body>

<span id="my-span"></span>

</body>
</html>

Open in new window

Author

Commented:
It works on your php but it doesn't work on my php page. Can I post my full code to you and you test it on a blank php page for you to see?

Author

Commented:
Hi, below shows most of code, it shows all of jquery code, the var myVar... is further down the jquery code. the myVar is going to echo "testing" like how you have done it". I have posted just relevent htm where in there it shows the <span> tag for "my-span". Please tell me if it is working in your blank php file after you have copied the code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title>Prepare Questions and Answers</title>
   <link rel="stylesheet" type="text/css" href="QandATableStyle.css">
        <link rel="stylesheet" type="text/css" href="jquery/ui-lightness/jquery-ui-1.8.16.custom.css"/>
		<script type="text/javascript" src="jquery/jquery-1.7.min.js"></script>
		<script type="text/javascript" src="jquery/jquery-ui-1.8.16.custom.min.js"></script>
		
		<link rel="stylesheet" type="text/css" href="jquery/ui-lightness/jquery-ui-1.8.14.custom.css"/>
		<link rel="stylesheet" type="text/css" href="jquery/ui-lightness/jquery-ui-timepicker-addon.css"/>
		<script type="text/javascript" src="jquery/jquery-ui-timepicker-addon.js"></script>

<script type="text/javascript">

$(document).ready(function()

{
	
	
	$(function() {	
	$('#questiondurationpicker').trenttimepicker({
			timeFormat:'hh mm ss',
			hourGrid: 4,
			minuteGrid: 10,
			secondGrid: 10,
			showOn: 'button',
			buttonImage: "Images/clock.gif",
			buttonImageOnly: true
	        });
	        
	        });

        initClick = 0;
        

    $(document).on('click','.showGrid', function(e) {
	    
        $(".gridBtns").removeClass("gridBtnsOn");
        
        var value = $(this)
            .siblings('input[name=gridValues]').val();
        
        $("#btn" + value.replace(/\s/g, '')).addClass("gridBtnsOn");
        
        $('.optionTypeTbl').fadeToggle('slow');
        $(this).parent().append($('.optionTypeTbl'));
        $('.optionTypeTbl').css({
	        
            left: $(this).position().left,
            top: $(this).position().top + 20
            
        });
        
        e.stopPropagation();
        
    });



  $( document ).click( function() {
	  
        $( '.optionTypeTbl' ).fadeOut( 'slow' );
        // fadeOut already hides it for you.
        
    });

    $('.optionTypeTbl input').on('click',function() {
	    
        $( ".gridBtns" ).removeClass( "gridBtnsOn" );
        $( this ).addClass( "gridBtnsOn" );
        
        console.log( $( this ).closest( 'td' ) );
        
        $( this ).closest( '.optionTypeTbl' ).siblings('input[name=gridValues]').val( $( this ).val( ) );
        $( this ).closest( '.optionTypeTbl' ).siblings('span[name=gridValues]').val( $( this ).val( ) );
        $( '.optionTypeTbl' ).hide( );
    });



     	var prevButton;
	
     $('.gridBtns').on('click', function()

    {

        var clickedNumber = this.value;
        
         $(this).closest('.option').siblings('.answer').find('.answers').each(function(index) {
            if (!isNaN(clickedNumber) && index < clickedNumber) {
                $(this).show();
                $('.na').hide();
                $('#allBtns').show();
                $('#allRemoveBtns').show();
                
                if (prevButton === 'True or False' || prevButton === 'Yes or No') {
         // show as blank
         $('.numberAnswerTxt').val('').show();
      } else {
         // show but don't change the value
         $('.numberAnswerTxt').show();
      }      

            } else {

                $(this).hide();
                $(this).removeClass('answerBtnsOn');
                $(this).addClass('answerBtnsOff');

            }

        });
        
        prevButton = clickedNumber;
            
        
        if (clickedNumber === 'True or False') {

            $(this).closest('.option').siblings('.answer').find('input[name=answerTrueName]').show();
            $(this).closest('.option').siblings('.answer').find('input[name=answerFalseName]').show();
            $('.na').show();
            $('.numberAnswerTxt').val(1).hide();
            $('#allBtns').hide();
            $('#allRemoveBtns').hide();

        }

        else if (clickedNumber === 'Yes or No') {

            $(this).closest('.option').siblings('.answer').find('input[name=answerYesName]').show();
            $(this).closest('.option').siblings('.answer').find('input[name=answerNoName]').show();
            $('.na').show();
            $('.numberAnswerTxt').val(1).hide();
            $('#allBtns').hide();
            $('#allRemoveBtns').hide();

        }
        
        else
        
        {
	     
	     var context = $('#optionAndAnswer');
	     
         $('.numberAnswerTxt', context).val(context.find('.answerBtnsOn').length);
	           
        }

        getButtons();
		 
    });

});

var myVar = '<?php echo "testing"; ?>';

$('#my-span').html(myVar);
      
function insertQuestion(form) {  
    
    
    var $tr = $("<tr></tr>");
    var $duration = $("<td class='duration'></td>");

     $('#questiondurationpicker').each( function() {
        
     var $this = $(this);
     var $durationText = $("<input type='text' class='questiondurationpickerRow' readonly='readonly' />").attr('name',$this.attr('name'))
                     .attr('value',$this.val())

    $duration.append($durationText);
    
    });
 

    $tr.append($duration);
    $('#qandatbl').append($tr);

    
        
}

</script>

</head>

<body>

<form id="enter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validateForm(this);" >
<div id="detailsBlock">

<table id="questionDuration">
<tr>
     <th colspan="2">
     Question Duration
     </th>
</tr>
<tr>
<td><input type="text" id="questiondurationpicker" name="questionDuration" readonly="readonly" /></td>
</tr>
<tr>
<td>Total Duration Remaining: <span id="my-span"></span></td>
</tr>
</table>
</div>
<hr/>
</form> 

</body>
</html>

Open in new window

Commented:
I can't just copy and paste to test your code as you are using several plugins...are you able to put it on a site that can be accessed?

Also just so you can see the functionality I made a fiddle here.

http://jsfiddle.net/QWYGW/

Author

Commented:
Yes I can, click here then you will access the page. That page has same code I posted to you above. The word "testing" should appear next to "Total Duration Remaining" but as you will see it doesn't.

Commented:
On lines 39, 76 and 80 you have a call to jQuery "on"  that isn't valid, if should be

$(document).click

Author

Commented:
I did not post my whole code that is why. I can post my whole code but it will be huge. Do you want me to post whole code?

Commented:
No it's ok, it was just somethng I noticed is all..
Below page has some errors.

http://helios.hud.ac.uk/u0867587/testing/Testpage.php

No JS files are being included. Make sure the path is correct.
JS file requests are redirected to http://helios.hud.ac.uk/errorpages/error404.htm

Author

Commented:
Thank you for telling me, I have included the jsfiles, you should be able to see the document working now :) http://helios.hud.ac.uk/u0867587/testing/Testpage.php
Try below Jquery Code.

<script language="javascript">
      var myVar = 'testing';
   
    jQuery(document).ready(function($)
    {
        $("#my-span").html(myVar);
    });
</script>

Put your $('#my-span').html(myVar); code inside jQuery(document).ready(function($) and make sure 'myVar ' is defined before jQuery(document).ready(function($).

Fr demo please follow below URL.

http://jsfiddle.net/attu143/DNuRV/

Let me know if you need more details

Author

Commented:
Hi, yes that has worked, AT LAST. I just have one question though. Except displaying it in a span tag like <span id="my-span"></span>, can I display it in between the span tag like a content like this <span>my-span</span>, because I want to use a span id for calculations later on and what I want is my-span to display the first number and then after calculations it will display different numbers depending on the calculations.

Commented:
jQuery uses DOM elements and selectors to place your code.

You can just use the same id if you are going to display your calculated number in the same place.

For example look at this fiddle.

http://jsfiddle.net/QWYGW/1/

Author

Commented:
Thank you everybosdy who has helped me on this question. I have to give this the best solution as this solution managed to get the jquery working

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial