To assign javascript value to a php variable in the same page - php

I have a page with php and javascript. In the php section i need to call a function with an argument $arg, Now $arg is the problem, $arg is actually value of a dropdown option in the same page . Here is what i am trying to accomplish.
<?php include("aclass.php")?>
<script language="javascript">
function getoption(val){
}
</script>
<html>
<select name="sel" onchange="getoption();">
<option value="1">One</option>
<option value="2">Two</option>
</html>
<?php
$object=new a;
$object->calculate($arg);
?>
// Here the issue is $arg should be the value i select in dropdown, $arg should be 1 if i select One and should be 2 if i select Two in dropdown.
" Is there a possibility to pass the javascript value 'val' to php variable $arg "

The thing you want to do is not possible without a form submission or without a contact to the server. PHP is a server side language whereas javascript is client side. So obviously you cannot do a server function in the client side.
So, either make this as a form and submit the form on change of the value in select or if you dont want reload of the page, try using ajax

You can use PHP variables in Javascript but the opposite can't be done. PHP runs server-side. Javascript is client-side. The only way to send something from Javascript to PHP is using AJAX. You might want to search in that direction.

Related

Drop down live update in a form

How do you live update the content of drop down 2 based on the selection made in drop down 1 in a PHP based web form?
Would appreciate any code examples to work from.
Many thanks!
You are going to have to use AJAX, I would recommend jQuery's abstraction.
e.g.
<select id="sel1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="sel2">
</select>
<script type="text/javascript">
$('#sel1').change(funciton(){
$.ajax({url: 'fetchSel2.php',
data:{sel1:$('#sel1').val()},
success:function(data){
$('#sel2').html(data);
}
});
});
</script>
This presumes there is a 'fetchSel2.php' that is ready to serve the options for the second select.
e.g.
function getSecondOptions($sel1){
$r=mysql_query(RELEVANT_QUERY);
$opts='';
if($r && mysql_num_rows($r)>0){
while(list($label,$val)=mysql_fetch_row($r)){
$opts.='<option value="'.$val.'">'.$label.'</option>';
}
}
return $opts;
}
if(isset($_GET['sel1'])){
echo getSecondOptions($_GET['sel1']);
}
exit;
For live update, you need to use AJAX and require JS enabled browser. If the user-browser don't support JS or JS is disabled, the only option is to submit the form and reload the whole page with the updated option in the 2nd dropdown. If you want the JS code to perform AJAX, can you kindly tell me the JS library you want to use, so I can provide the code accordingly.
What you are looking for is a cascading dropdown list. This is done using AJAX triggered in sequence by each dropdown. Here is an example via Google (http://codestips.com/php-ajax-cascading-dropdown-using-mysql/), note I'm not endorsing this link, it's just the first reasonable result.
I recently did this with jQuery http://jsfiddle.net/tBrXt/1/
You have these options:
Use AJAX if you don't want the form to refresh and update parts of
the form.
If you don't want to use ajax and can bear with refreshing the whole
form, you can capture the onChange event of the drop down using
javascript.
If the user does not have javascript enabled, the above 2 methods
will fail. Therefore, it is best to include a button users can click,
which will ask the PHP side to rerender the form.
My personal preference is to use the last method as a fall back for those who do not have javascript enabled. Then use the first method (AJAX) to progressively enhance the form for those that have javascript.

Change php variable based on javascript value

how can i change/assign a value to php variable depending on a javascript variable?
here is my code.
<select id="reOutcome" name="reOutcome" onchange="OnChange(this.form.reOutcome);">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<script type="text/javascript">
function OnChange(dropdown)
{
var myindex = dropdown.selectedIndex
var SelValue = dropdown.options[myindex].value
if(SelValue==2){
<?php
$sCOMPFields .= "|"."SreComments";
$sCOMPFields .= "|"."rePrID";
?>
}
return true;
}
</script>
The onchange function is working fine. I just don't know how to change the php variable. I searched online a lot. All im getting is how to assign php variable to javascript. That is not what im looking for.
Thanks for your help.
The execution you want won`t occur, because the flow of the php scope and the javascript scope occurs on different moments. It is something like this:
So, you can`t execute php while the javascript is being executed on the computer of the user through the browser, but you can execute php on your server to generate the javascript you need to be executed on the user computer.
Actually, your question seems to be closer to a "what is the best way to do (something)"
PHP variables are set at run time. You can't do it directly within the javascript. Off the top of my head the best way I can think of to do it would be to set the php variables as session variables. Then use your javascript to call a php file via ajax/jquery that can update the session variables.
that's exactly we use ajax.
make the page loads in default preferences, then update it using ajax

PHP class method called by jQuery

I'm fairly new to jQuery and OOP in PHP,
but what I have is a PHP Object that has an array
$array[0] = "a"
$array[1] = "b"
$array[2] = "c"
$array[3] = "d"
and a select box in my HTML
<select class="box">
<option value="1">First Letter</option>
<option value="2">Second Letter</option>
<option value="3">Third Letter</option>
<option value="4">Fourth Letter</option>
</select>
<div></div>
How do I dynamically change whatever is in the div tags as someone changes the value of the select box using jQuery?
Is there a way to do something like
$('.box').change(){ var value = $object->array[index-1]}?
Assuming I had already have the value for index.
EDIT
I know I'll have to use Ajax, but I'm not sure how to call a method in an instance of an object already made.
You can't access PHP through javascript. There are several possible solutions:
Load all of the possible data combinations at once onto the page stored somewhere in the DOM. As the user cycles through the options, change them appropriately.
Load only the initial elements onto the page without javascript, then use Ajax to load all other possible combinations.
Load each combination with ajax on the fly.
You can either have javascript make an Ajax request to the same page and filter the request, or you can create a proxy that will serve only the requests you need when hit with ajax.
Remember that you are trying to combine PHP with Javascript.
Your code will primarily be written in javascript, but you'll
only inject bits of PHP code into the javascript code.
As in this instance, use the standard jquery onchange event method 'change()'
for the selectbox, set the javascript variable value to $object->array[0]
from PHP.
$('select').change(function() {
var value = <?php echo $object->array[$index] ?>
$('div').html(value)
});
You can use the php function json_encode to turn your php data into a javascript object. e.g
<script type="text/javascript">
var mydata = <?= json_encode($myarray) ?>;
console.log(mydata);
</script>

How to transfer select value to php?

I want to display the photos according to the album selected. But, I don't want to post the page, I want to just change the div.
This is my script:
<script type="text/javascript">
function replaceContent(divName, contentS) {
document.getElementById(divName).innerHTML = <?php echo get_pictures_from_album($fb, $albums, contentS); ?>;
}
</script>
And this is the select tag that invokes it:
<select name="album" size= "1" style="width:210;" onchange="replaceContent('photos', this.options[this.selectedIndex].value);">
<?php get_albums_select_list($albums); ?>
</select>
<div id = "photos">
<?php echo get_profile_pictures($fb, $albums); ?>
</div>
I understand from a reading that I have done that the problem might be connected to javascript Vs php variable types.
Please advise.
Looks like you are looking for an AJax call to an PHP script that retrives the data for the appropriate album selected and THEN update the div with the callback function.
Ajax + PHP basics
You are mixing Clientside and Serverside Code here. The function replaceContent is called after the page (and the php code) was loaded. You would need an Ajax Call for that if you need more information about that:
Ajax Tutorials on Google
What you are doing is not possible because PHP code runs before (on the server because PHP is server-side language) javascript code.
You will have to resort ot AJAX for that.

Problem with keeping selected value in form after reloading page

I'm trying to populate a second dropdown in a dynamic way based on a previs selected dropdown.
However, I've managed to write get the page to reload when I choose anything in the dropdownbox but the chosen value isnt passed after reloading.
I have register_globals turned off (and prefer to) and i'm using the GET function to submit the form. However when I try setting values in the URL I cant get it to work.
Example: dropdown.php?area=1 still gives me a value in the dropdownbox with the default value.
What am I doing wrong? Running on a LAMP server. Apache 2.2, php 5.3.
Note: I found the php code here on the web wwich is suppose to help me pass the GET variable and select the option in the selectbox.
This is my code:
<html>
<head>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.area.options[form.area.options.selectedIndex].value;
self.location='dropdown.php?area=' + val ;
}
</script>
</head>
</body>
<? #$area=$HTTP_GET_VARS['area']; ?>
<form action="" method="get">
<select name="area" id="area" onchange="reload(this.form)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</form>
</body>
</html>
Also, if this could be done with POST (or equivalent function) it would be even better.
Regards.
I think you're not specifying anywhere which one of the options should be selected on page load. Depending on the value of $area, you should add something like
<option selected>1</option>
You could easily do this with a couple of lines of PHP when rendering the option nodes:
<? if $area == 1
print '<option selected>1</option>';
?>
etc.
Alternatively, you could just populate the second combo using client-side javascript eliminating the need for a page reload. If you need to do some sensitive server-side processing to calculate the value of the second combo, do it in a background AJAX call using jQuery (examples here). Postbacks for this kind of thing are kind of undesirable and old-fashioned these days.
Regarding the GET issue, if submitting the form has any side effects (eg. a change in state in the user's account, deleting something, creating a new entity) then it should definitely be a POST. Discussion here for example.

Categories