Multiple updates at once via ajax - php

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.

Related

how to validate the selected option to only one time can be used, not double, can it?

I'm a beginner in cakephp, help me please. I have stuck when I think to validate input type selected in form cakephp, the data is detail, so many rows there, first line.
<select id="AirWayBillDetail0ItemId" name="data[AirWayBillDetail][0][item_id]">
<option value="">-- Select an Item --</option>
<option value="9">Handphone</option>
<option value="10">Accecoris</option>
<option value="11">Alat Tulis Kantor</option>
<option value="12">Voucher Fisik</option>
</select>
I want the option, just one time can be used.
Example:
Add first line, I select handphone,
so, the second line, cannot used that option. Is there any way to clear my trouble?
Can I validate in Model or in View or Controller? With javascript or jquery?
You want to check this in the model or controller layers. Never rely on JavaScript for validation as this can lead to vulnerabilities in your app (JavaScript can easily be disabled). You should always validate on the server-side and can supplement this with client-side validation if you want some additional inline validation.
You want to add a check that there are no duplicate item_id in your submitted data. So you could do something like the following in your controller:-
$itemIds = Hash::extract($this->request->data, 'AirWayBillDetail.{n}.item_id');
if (count($itemIds) !== count(array_unique($itemIds))) {
// Invalid item_ids
}
You'd then need to handle how you'd want the error messages showing and ensure it doesn't proceed to save. If you want to do this in the model you need to look at using the beforeSave() callback to check $this->data before saving and return false if duplicated are identified.
You can implement this with jQuery.
Please refer this fiddle http://jsfiddle.net/sqy1n6n3/1/
$('select').on('change', function() {
$('select').find('option').prop('disabled', false);
$('select').each(function() {
$('select').not(this).find('option[value="' + this.value + '"]').prop('disabled', true);
});
});

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

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

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']

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

jquery select list and $_POST help

I have a select list, currently I have it implemented then when the user selects an item, the I have some javscript that creates a li on the fly on the places on the page, the problem is that I want the user the be able to select multiple items from the list, however the javascript cannot cope with this, but I need this functionality so that when I submit the form the values of the selct list go into the post.
Currently my javascript looks like this,
$('#sector').change(function() {
var selected = $(this).val();
//alert(selected);
$('#selected_sectors').prepend('<li>'+selected+'</li>');
});
Is it is possible to get this each time the user ctrl+selects and item is creates the li but and keeps the values accesible in the post?
Possibly something like this is what you're looking for (note the :selected selector).
<select id="items" multiple size="5">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="banana">Banana</option>
<option value="grape">Grape</option>
</select>
<ul id="sel-items"></ul>
$('#items').change(function(e){
$('#sel-items').empty();
$(this).find(':selected').each(function(i,e){
$('#sel-items').append($('<li>').text($(e).val()));
});
});
Working Example
(Working on one now that checks for deltas between the <select> and the <ul>)

Categories