jQuery Var in a PHP Query

Is there a way to place a jQuery VAR in a PHP Query?
<script>
	var lineName ="line_25"	
        	<?php	
        		$pd_base_liabel = $this->EE->db->select('id, state, pd_base_rate')
				->from('exp_state_rates')
				->where('id', '+ lineName+')
				->limit('1')
				->get();

Open in new window

LVL 8
rgranlundAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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.

Alexandre SimõesManager / Technology SpecialistCommented:
What are you trying to achieve?

That var there, as it stands, will be declared in the global scope which isn't a good idea...
Also PHP code runs server-side and javascript runs client-side... what are you expecting to do with them?
Big MontyWeb Ninja at largeCommented:
Is there a way to place a jQuery VAR in a PHP Query?

yes, but as Alexandre said, PHP runs on the server side, and is processed before the client side code is. You would need to use AJAX (or a simple form submission, if all you're trying to do is pass the value to the server.

if you be more specific on what you're trying to accomplish, it'll be much easier to help
rgranlundAuthor Commented:
I have a form that onChange calculates an updates price.  Part of the price is determined by a value kept in the DB.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Big MontyWeb Ninja at largeCommented:
you're better off saving that value to a hidden variable upon page load, then you can access it like you would any other element on the page
Chris StanyonWebDevCommented:
In the code above, you know what lineName is because you're hardcoding it in, so you could just use that directly in your php.

Depending on the element that you're binding the change() event to, you might be able to build your HTML in such as way that you don't need to make an AJAX request - you just pull the records from your database and build your element's HTML in PHP - then all your values will be available on the client-side.

We'd need to know a bit more about exactly what you're tying to do
Dave BaldwinFixer of ProblemsCommented:
AJAX is the only way to do that after the page is loaded.
Slick812Commented:
greetings rgranlund, , If you have not used or learned about AJAX before, you are like most, and do not know what it does or how it does it. In a browser web page, there is NO LONGER any PHP code that can be used in that page, even in a <script> tag, so No server database can be used in javascript. But what is called AJAX, means that in javascript, you can make a JS ajax function to SEND information to your PHP server page, the PHP page then reads this information from a $_POST entry, like -
   $lName = $_POST["lineName"];

then you select from table in PHP and get your three outputs columns  -   id, state, pd_base_rate
and you can echo them out of PHP-
echo $row["id"]."_".$row["state"]."_".$row["pd_base_rate"];

and then in javascript another ajax function  
   aj.done(function( received ) {
var dbArray = received.split("_");
$( "#price" ).val(dbArray[2]);
});

Reads what was sent from the server, and then uses that to change anything you want (a price) on your web page.
although AJAX can be not easy to understand at first, since it is a three step process on two different computers, you should learn how to do it , , , as it is extremely useful.

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
rgranlundAuthor Commented:
Here is most of the code and I am wondering if there is a better way to write this.  The php works because there is a for that submits.  When the form submits, the values are obtained.  Once the specific values are there the jQuey onChange just uses what ever values have been set.

<?php
	$pd_base_liabel = ee()->db->select('*')
		->from('exp_state_rates')
		->where('id', $bike_state)
		->limit('1')
		->get();	
		$bsl = $pd_base_liabel->result_array();
		$pd_base_liabel->free_result();	
		  foreach($bsl as $row) {
			$medpay_1000 = $row['medpay_1000'];
			$medpay_2500 = $row['medpay_2500'];
			$medpay_5000 = $row['medpay_5000'];
			$medpay_7500 = $row['medpay_7500'];
			$medpay_10000 = $row['medpay_10000'];
			$medpay_15000 = $row['medpay_15000'];
			$medpay_20000 = $row['medpay_20000'];
			$medpay_25000 = $row['medpay_25000'];
		  }
?>	

<script>
function() {
	var liability_option_value = $('select[name*="[product_liability]"]').val();
        	
        		if(liability_option_value == "liability_25") {
        		 		liability_rate = "<?php echo $liability_25; ?>";
        		 }	else if (liability_option_value == "liability_50" )   {
        		 		liability_rate = "<?php echo $liability_50; ?>";
        		 }	else if (liability_option_value == "liability_100" )   {
        		 		liability_rate = "<?php echo $liability_100; ?>";
        		 }	else if (liability_option_value == "liability_300" )   {
        		 		liability_rate = "<?php echo $liability_300; ?>";
        		 }	else {
 					liability_rate = 0;
 				}	
}

</script>

Is there an easier way than writing out each line like that?

Open in new window

Chris StanyonWebDevCommented:
Not really sure how your code ties together. You set a few $medpay* variables in your PHP but do nothing with them.

Your javascript functions refers to PHP variabels called liability*, but there's no indication of what these are or where they come from.

You have an anonymous javascript function - how does this get called. I absolutely certain there's a better way to do what you want, just can't quite figure out what you want.
Slick812Commented:
you say this - " have a form that onChange calculates an updates price.  Part of the price is determined by a value kept in the DB."
I simply do not know what or how you do the "calculates an updates price" part of this thing, I guess that you need a price from the DB maybe it's the   pd_base_rate    column, but your select change with -

if(liability_option_value == "liability_25") {
        		 		liability_rate = "<?php echo $liability_25; ?>";
        		 }	else if (liability_option_value == "liability_50" )   {
        		 		liability_rate = "<?php echo $liability_50; ?>";
        		 }	else if (liability_option_value == "liability_100" )   {
        		 		liability_rate = "<?php echo $liability_100; ?>";
        		 }	else if (liability_option_value == "liability_300" )   {
        		 		liability_rate = "<?php echo $liability_300; ?>";
        		 }	else {
 					liability_rate = 0;
 				}

Open in new window


makes no sense to calculate a price, do you mean get a Price ? ? or do you multiply by a quantity of items?
can not understand?

can you show use the HTML for the <form> that you use?
rgranlundAuthor Commented:
Here is most of the code and I am wondering if there is a better way to write this.  The php works because there is a for that submits.  When the form submits, the values are obtained.  Once the specific values are there the jQuey onChange just uses what ever values have been set.

<?php
	$pd_base_liabel = ee()->db->select('*')
		->from('exp_state_rates')
		->where('id', $bike_state)
		->limit('1')
		->get();
		
		$bsl = $pd_base_liabel->result_array();
		
		$pd_base_liabel->free_result();	

	echo '<pre>';
	var_dump($pd_base_liabel);
	echo '</pre>';
	
		  foreach($bsl as $row) {
			$liability_25 = $row['liability_25'];
			$liability_50 = $row['liability_50'];
			$liability_100 = $row['liability_100'];
			$liability_300 = $row['liability_300'];
		  }
?>	

<script>
function() {
	var liability_option_value = $('select[name*="[product_liability]"]').val();
        	
        		if(liability_option_value == "liability_25") {
        		 		liability_rate = "<?php echo $liability_25; ?>";
        		 }	else if (liability_option_value == "liability_50" )   {
        		 		liability_rate = "<?php echo $liability_50; ?>";
        		 }	else if (liability_option_value == "liability_100" )   {
        		 		liability_rate = "<?php echo $liability_100; ?>";
        		 }	else if (liability_option_value == "liability_300" )   {
        		 		liability_rate = "<?php echo $liability_300; ?>";
        		 }	else {
 					liability_rate = 0;
 				}	
}

</script>

Is there an easier way than writing out each line like that?

Open in new window

Slick812Commented:
since there is no code for a <form>, then I guess there is no better way to write that?
Chris StanyonWebDevCommented:
OK. We're still not getting the full picture, so I'm going to take a guess at what you're trying to do. You want to build a <select> element, and when that changes, you want to get at a particular value from the database, associated with the value from the dropdown. If this assumption is correct, then here's how I would do it.

Build the <select> using the values you want, and add a data attribute using the values from your database. Because you are only returning one row from your database there's no need to loop through them. Just get the value directly from the row

<?php
$pd_base_liabel = ee()->db->select('*')
    ->from('exp_state_rates')
    ->where('id', $bike_state)
    ->limit('1')
    ->get();

$options = "<option value='' data-rate='0'>Please select an option...</option>";
$options .= sprintf("<option value='liability_25' data-rate='%s'>Liabilty 25</option>", $pd_base_liabel->row('liability_25'));
$options .= sprintf("<option value='liability_50' data-rate='%s'>Liabilty 50</option>", $pd_base_liabel->row('liability_50'));
$options .= sprintf("<option value='liability_100' data-rate='%s'>Liabilty 100</option>", $pd_base_liabel->row('liability_100'));
$options .= sprintf("<option value='liability_300' data-rate='%s'>Liabilty 300</option>", $pd_base_liabel->row('liability_300'));
?>

Open in new window


Now in your HTML, do this:

<select name="product_liability">
    <?php echo $options ?>
</select>

Open in new window


And your jQuery would then look like this:

$('select[name=product_liability]').change(function() {
     var rate = $(':selected', this).data('rate');
});

Open in new window


If I'm way off the mark with this, then please take a minute to clearly explain exactly what you're trying to do.
Ray PaseurCommented:
Here's the "Hello World" example that shows the client side (JavaScript, jQuery) communicating with the server side (PHP).  Once you understand this part of things, you will be able to get data to go back and forth between client and server.  The next step will be to use some of that client data in the MySQL queries.  But this is really a two step process.

Step 1: use jQuery for client/server communication
Step 2: user server-side SQL to talk between the server and the data base engine, transporting the data received from the client.

http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html
rgranlundAuthor Commented:
@ Slick812 Thanks for the info.  Is there a good place online where I can learn this specific function?

@Chris.  Thanks for this information.  It will really help me in the future.  After looking at this response I had a light bulb moment.

@ Ray.  As always, thanks for the informative reading.
Slick812Commented:
@rgranlund, , , I am not one to look for beginers in AJAX web stuff, but here is the Jquery Manual page for one of the least difficult Ajax as the Jquery  post()  method -

$.post( "test.php", { name: "John", time: "2pm" })
  .done(function( received ) {
   $( "#showme" ).html(received );
  });

      http://api.jquery.com/jQuery.post/

and at the w3schools site -
    http://www.w3schools.com/jquery/ajax_post.asp

please consider looking and studying these codes abour Non Jquery Ajax in JS using the XMLHttpRequest Object -
    http://www.w3schools.com/ajax/ajax_intro.asp
I have been able to more effectively use Ajax because I took the time and effort to learn the native XMLHttpRequest Object use and the particulars need to do special  transactions between browser and server, there is much more to the wide options for data exchange between JS and PHP then the simple Jquery examples ever show. One thing that really helped me was using the many HEADER sends that are available to use like -


ajaxObj.getResponseHeader("Content-Type");
var eTag=ajaxObj.getResponseHeader("ETag");
   ajaxObj.setRequestHeader ("If-None-Match", mrk);
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
PHP

From novice to tech pro — start learning today.