Passing Javascript Variable (var ...) to PHP Variable ($...) using Ajax - php

I'm having a problem in passing variable from Javascript to PHP,
passing variables from PHP to Javascript is Easy
but is there a way to pass Variables from Javascript to PHP?
Here's the Situation
Think of this as the variables of the first select input
--2010
--2011
--2012
and
the Values of the second select group varies depending on the selected option
of the first select group
The values are:
2010
--AAA
--AAB
--AAC
2011
--ABA
--ABB
--ABC
2012
--ACA
--ACB
--ACC
say that the values are displayed by a conditional PHP function that
retrieves data from a Database
Here's What I Want to do:
When I Select One from the first select Group,
It will change the options of the second select group
of course, this happens via triggers when the first select group changes
I need to Retrieve the value of the first select group to filter the data
that will be displayed as the options of the second Group which comes from
a database and a PHP function is made to process it, thats why i need the value
of the first select group and use it as a parameter for the second select group.
The Problem:
i need to get the value of the first select group in PHP Varible
to make a PHP Function work.
Please Help!!!

You can simply add it in as a url parameter in the ajax request that you send.
Consider your first field is like so:
<select id="field1">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select>
Your javascript will be like so:
var ajaxUrl="http://myserver.com/getfield2.php?field1=" + document.getElementById("field1").value;
And then you will send the ajax request to ajaxUrl
In the php, you will get this value as
$_GET["field1"]

Like said above, your fields are
<select id="field1">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select>
Use jQuery to perform an AJAX call to your script. Something like that
$("#field1").change(function(){
var value = $(this).val();
$.post('script.php', {
phpvar: value
}, function(){
//this is callback, render your second field here, with the responce of php script
});
});
In your php script, variable passed from jQuery will be available like this
$_POST['phpvar']

Related

Retrieving .data('value') from <select> "sometimes" works

My select box that is generated by PHP:
<select>
<option selected>Select something</option>
<option data-value="test"></option>
</select>
So far I have tried the following ways to retrieve the value within the data-value attribute:
$('select').children(":selected").data('value');
$('select option:selected').data('value')
$('select option:selected').attr('data-value');
$('select').find(':selected').data('value');
Of course there are a couple of more ways to do this. Once the one of these options gets executed I "sometimes" get the value within the data-value attribute. Even using
$('select').on('change', function () { // code });
gives me the same result. Am I missing some underlying thing?
FIXED:
After every select I use the data information for something else. Then I refresh the select box data by retrieving the remaining data information from the database. At that point I forgot to add the attribute data-value to every option..

Add options to <select> based on value of another <select>

I am working on a form that requires a drop-down menu to be populated based on the value of another that is completed by the user first.
The two selects are "subject" and "topic". When the subject is chosen, the "topic" drop-down menu should contain all of the topics within that subject. E.g. for "maths" subject "topic" should show algebra, shape etc.
How can I achieve this? The values for both selects are done in PHP. For the first select, it is a simple task of using a for loop to populaate the select but it seems as though JavaScript must be used for the second. How shall I go about this?
Thanks in advance,
Ilmiont
Assume that, your first select has 2 options:
<option value="math">math</option>
<option value="english">english</option>
So, you can load second select's option something like this:
<option value="math-a">math-a</option>
<option value="math-b">math-b</option>
<option value="english-a">english-a</option>
<option value="english-b">english-a</option>
where a & b is representing different topic. You can initially hide the second select's option using jQUery or CSS.
Then, just use jQuery to show specific option based on first select like this:
$('#sub').change(function(){
$('#topic option').css('display', 'none');
var value = $(this).val();
if(value){
$('#topic option').each(function(){
var topic = $(this).val();
topic = topic.split('-');
topic = topic[0];
if(value == topic){
$(this).css('display', 'block');
}
});
}
});
Working fiddle.
Hope this will works!

Multiple updates at once via ajax

I just want to make sure I'm on the right track at the moment:
Made a little thing so an admin can edit people's schedules. Right now he clicks on a row and all the schedules become editable. If he changes values in a row I'm catching it with
$('.selector').change(function() { // this happens to be a <select> dropdown. I guess technically this is the <option> inside of the select.
var updates = new Array(); // an array of all the updates
var classList = $(this).attr('id').split(/\s+\); // the id of a <select> would be something like "12 monday start" meaning the user_id, day_of_week, start/end time. Just converting it to an array here.
classList.push($(this).val()); // the time it has been changed to
updates.push(classList); // add the singular time update to the overall array
$('.save_schedule').click(function() {
// here I would iterate through all of the arrays in updates and do some sort of ajax call, correct?
});
});
Just want to make sure that I'm on the right track before I go any further and have to potentially rewrite things.
Thanks
My HTML since it has been requested: https://gist.github.com/2435293
if your HTML looks somehow like this
<select id="12 monday start" class="selector">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="12 monday end" class="selector">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="button" class="save_schedule" value="save" />
your javascript could look like this
$('.save_schedule').click(function() {
var arr = new Array();
$('.selector').each(function() {
arr.push($(this).attr('id').split(/\s+/));
arr.push($(":selected", this).val())
});
alert(arr);
// ajax call here
});
see jsfiddle example
I can think of two ways to implement this:
OPTION 1 - draft saving
Each time the user edits a row, you make an AJAX call to temporary save his changes (add a database column draft to distinct drafts from real changes).
You should move the click handler outside the change handler:
$('.selector').change(function() {
...
});
$('.save_schedule').click(function() {
...
});
In the change handler, $(this) points to the current tag select.
To get the selected value, you can use $(this).val().
To avoid splitting the select id attribute to get all the elements you need, you can use custom attributes:
<select data-user-id="12" data-day="monday" data-time="start">...</select>
Then, in your change handler, you can use the attr method to get their values.
var user_id = $(this).attr('data-user-id');
var day = $(this).attr('data-day');
var time = $(this).attr('data-time');
Now, you can make an ajax call to store the changes as draft.
When the user clicks on save_schedule, make a final ajax call to update the status of the drafts and set it to permanent.
OPTION 2 - simple save, form serializing
All changes are saved only when the user clicks on save button.
I would recommend to keep all the data in HTML tags and not in Javascript. (for reasons like: What happens if the user edits twice a schedule? Are the changes pushed again in the array?).
You could hide the inputs/selects when they are not editable and you won't need to treat the change event anymore.
When the user clicks on save_schedule, you can use a function like $(form).serialize() to gather all the data from your inputs (http://api.jquery.com/serialize/) and make an AJAX call to save your changes.

javascript and PHP variable passing

I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
If I understand correctly, then yes, using AJAX is really your only choice.
Indeed, you can, with AJAX, call something like 'getSelectionData.php?data=' + select1.value, which returns a JSON array of data based on the selection in the first select box. You then parse the data and enter it into the second select box.
Add a onchange event listener to the first select box:
document.getElementById("select1").addEventListener("change", function(ev){
var yourstoredvariable = this.value;
someFunctionThatCallsAjax(yourstoredvariable);
}, true);
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
You will have an onchange event on the first <select> that will query the server using Ajax with the value of the selected <option> that will return the <option> elements with which to populate the 2nd <select> element.
Question is, how do I pass in the var I have in the first select box to PHP?
I see no problem here.
Just usual, an ordinary html form using GET method.
What's so big about it?
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js

How do you set the default value of a drop down list that is being called via AJAX from another page?

For my code, my drop down lists are initiated on the original page, via
<select name =country id=country
onchange=showRecords(this.value,'country','province')>"
This function is taking the value, equating it to country, then querying MySQL, and setting the results where id=province, and creating cascading dropdown lists. This is obviously via Ajax.
So, when $_REQUEST['province'] is set, then the Province dropdown list gets populated with all provinces from the country to which it belongs, etc.; i.e.;
<?if(isset($province)){
echo "<script>showRecords('".$country."','country','province');</script>";}?>
However, for the life of me, I cannot figure out how I can set the default value equal to $_REQUEST['province']. I cannot use the traditional way:
if (($selected) == ($value)) {
$options.= " selected";
}
Because it is querying the AJAX page with one piece of information at a time.
Any ideas would be greatly appreciated.
Your code doesn't seem to make a lot of sense. The particular thing that worries me is that you say ajax is loading one item at a time?
Perhaps something like this. A country select tag like...
<select onchange="showRecords(this)">
As well as creating the javascript function showRecords() which will be called when someone chooses an option in the select tag.
<script>
function showRecords(calling_element) {
// do AJAX call here using calling_element.options[calling_element.selectedIndex].value as the selected country. this.value does not work for select tags.
}
</script>
the PHP page that receives this AJAXed request would reply with a JSON object containing all of the province values, or a delimited list.
once the Javascript showRecords function receives the responce from the PHP page, it would add each of these options to the correct select tag. Once finished, it would set the default value to whichever option it wants by something like the following:
target_element.selectedIndex = {desired list index here};
I have a lot of assumptions to your questions,
first is, if bydefault you have the select province like this
<select id="province">
<option value=""></option>
<option value="California">California</option>
<option value="Washington">Washingthon</option>
</select>
then you can use this script to default select
document.getElementById("province").value="Washington";
but if bydefault you have the select province like this
<select id="province"></select>
then you can use this script to default select
document.getElementById("province").innerHTML='<option value="Wahsington">Washington</option>';
so it depend on your code and your need. maybe if you have another case the problem should be solved in another way.
cmmiiw :)

Categories