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

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?
u0867587Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mrh14852Commented:
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

0
mrh14852Commented:
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

0
u0867587Author 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?
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

u0867587Author Commented:
Oh, sorry didn't realise you posted your second comment before my comment. sorry
0
u0867587Author 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,
0
u0867587Author 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?
0
u0867587Author Commented:
it doesn't work in any browser, so do you know why it isn't working?
0
mrh14852Commented:
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

0
u0867587Author 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?
0
u0867587Author 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

0
mrh14852Commented:
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/
0
u0867587Author 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.
0
maeltarCommented:
On lines 39, 76 and 80 you have a call to jQuery "on"  that isn't valid, if should be

$(document).click
0
u0867587Author 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?
0
maeltarCommented:
No it's ok, it was just somethng I noticed is all..
0
Atique AnsariCommented:
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

0
u0867587Author 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
0
Atique AnsariCommented:
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
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
u0867587Author 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.
0
mrh14852Commented:
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/
0
u0867587Author 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
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.