I have successfully done ajax calls before for situations like this in a form:
User selects a 'category' from a list in a select box. Ajax is fired off when selection is made, which updates a second select box with all items related to the selected category.
I know how to successfully do that thanks to the answer found here.
What I am now doing is dynamically adding new nested form fields with the nested_form_fields gem. Here is a snapshot:
So every time the user selects "Add Service", the nested_form_fields gem generates a new nested form with two select boxes (a service category select box and a service provided select box as pictured above).
It works fine. The issue I am having is firing off an ajax request for this dynamic content when the user chooses a service category.
When a user selects a service category, I want to send an ajax call, which updates that second select box with all the services related to that service category.
The issue is that the ajax request is not firing off at all. The server is not getting any requests when the user selects a service category. I think the issue is that since these nested fields are generated dynamically, the javascript does not have the opportunity to bind the ajax request to the new nested fields' service category select box.
Here is my javascript:
$(document).ready(function(){
$("#service_category_selection").on('change', function(){
$.ajax({
url: "narrow_service_by_service_category_selection",
type: "GET",
data: {service_category_id: $(this).val()},
success: function(data){
/* ... */
}
})
});
});
I think if I was somehow able to make this javascript run every time the html in the page changed (ex: when new nested form fields are added), then the javascript will able to bind that ajax call to the new service category select box.
Well only one element can have the id, so you need to reference it with a class. event delegation will capture the new elements. Since you did not give HTML structure, I had to keep the answer for finding the second select generic.
$(document).on("change", ".service_category_selection", function () {
var select = $(this);
$.ajax({
url: "narrow_service_by_service_category_selection",
type: "GET",
data: {service_category_id: $(this).val()},
success: function (data) {
var secondSelect = select.closest("parentElementSelector").find(".classForNextSelect");
}
});
});
You should be able to use a delegated event handler instead of a direct one. Just change
$("#service_category_selection").on('change', function...
to
$('body').on('change', '#service_category_selection', function...
You can read more about this in the jQuery docs here:
https://api.jquery.com/on/#direct-and-delegated-events
HTH!
Related
I have a page tha displays results. The results are loaded into a content div via an ajax request on (document).ready. The results can be filtered using a form. On $(#filter_form).submit() the ajax request is made and the content div is populated with the filtered results.Up to here all is well.
Clicking a result will load the results details in a new page, non ajax load. On clicking the back button we go back to the results page,the form checkboxes are still checked, but the filters are no longer applied to the results. Obviously on document.ready the first, non filtered, ajax request is made and the non filtered results are loaded.
My initial idea was on page ready to check if any of the form elements are checked, and if they were, to submit the form. Problem is I have no idea how to make this work.
My script to load the filtered results is this:
$('#filter_form').submit(function(e){
e.preventDefault();
$.ajax({
url: '<?=base_url().'catalog/show_listings/?';?>'+queryString,
type:'GET',
data: $('form#filter_form').serialize(),
dataType: 'json',
success: function(listings){
$('#result_container').html(listings);
} // End of success function of ajax form
}); // End of ajax call
});
I managed to figure out how to check if any form elements are active :
var validate= false;
$('#requestfilter_from').each(function(){
if($(this).val() != '' || $(this).attr('checked'))
validate = true;
});
I just have no idea how to combine the two. I tried running the ajax request in the second script (dont have that script to post anymore) but it didnt provide any results.
Any suggestions or pointers would be greatly appreciated.
I think the problems boils down to saving the "state" of the filters (keeping track of which ones are checked even if the user leaves the page).
You can easily do this by appending query parameters to the url. For instance, if someone selects a filter checkbox1, you can append &checkbox1=true to the url. This way, even
when user leaves the page and hits back button, you will have &checkbox1=true in the url.
Now, you need to modify the initial loading of data to take query parameters into account.
So don't load all the data at the start. Instead, parse query parameter, prepare the url based on filters found in the query params and then fire the ajax query which loads initial data.
Here are the steps -
On selection of a filter, append query parameter to url.
On $(document).ready, parse query parameter, and
Make sure you update the input boxes, so they reflect the state of the filters.
For e.g, if &checkbox1=true was found in the url, make sure input[name=checkbox1] is checked.
Fire the initial ajax query with filter parameters
This comes with a bonus. Now, your users can also pass around the url with selected filters.
PS: Look into jQuery.param.querystring
I need to make a site, but I'm stuck... cause I only really know how to work with php and html...
trough research I understood that it's impossible to do this without javascript because php only does pre-processing...
my problem:
I want the user to be able to click on a option in the select box and that the chosen option changes the next select box.
meaning: my first select box gets filled by information from my database... depending on the choice made in the first select box the second select box needs be filled with new variabels which he also gets from the database. and the choice in the second makes the options in the third and so on.
I need this cause my database is a tree...
meaning: I have categories (which I would post in the first select box) and only giving the sub categories of the chosen categorie in the second select box and so on...
the use of this:
the user needs to be able to add a new object in the database trough selecting where he wants it and clicking on the +-button to tell me where he wants to add it... the user isn't bound to get down the whole tree and should be able to add an object in the categories, subcategories or even further on...
I hope my explaination makes sence =s so that someone can help me, cause I really don't get javascript at all =s I already searched for 1week and yet I haven't found anything... It's pretty hard searching for something where you don't know the name for... so please somebody help. thx in advance
I would use jQuery and do an ajax request whenever your select box is changed, something like
$(function(){
$('input#theDropDown').change(function(){
var theValue = $(this).val();
$.ajax({
type: "GET",
url: "getData.php",
data: "TheValue=" + theValue,
success: function(response) {
// I would think 'response' would be a json string or something which contains the values the next dropdown should have
}
});
});
Where the dropdown is an input element with id=theDropDown.
Here's more info:
http://api.jquery.com/jQuery.ajax/
I have a webpage with form which is processed with javascript code. There is a form with button with javascript onClick() method.
Here is the webpage (czech declensions)
On input I have a list of names in mysql database. I need to put a single name form list into a form, click on button to invoke onClick() method and on output I want to have name with declension (field 5. vokativ in form) - insert it into database table. This action in cycle for each name from a list form database.
Please, any suggestions how can be this done?
I would recommend ajax to do this trick..
With jQuery it could be done pretty easy if I understand you right.
It could look like this:
$.ajax({
url: "validate.php?info=something&otherinfo=somethingelse"
}).done(function() {
alert('done');
});
You could get all the informations by doing this:
var something = $('input[name=something]').val();
Then make the PHP page handle the informations.
Hope this helps.
I am writing code for a dropdown list. The dropdown list is being populated from the data from the database. So I am making 2 ajax calls one is on event onmouseover to populate the contents of dropdown list and the other on selection of specific option making ajax call to bring related contents on the screen.
Now I want to make another ajax call to get the contents which can be populated on hovering over the specific option. The contents got from ajax call can be displayed in the small dialog box. For achieving this I have installed the qtip libraries.
Problem
I am not getting how the ajax call be made. Which even will be appropriate for achieving this? I know the qtip is loaded onload of the page. But since I want to make ajax call to get the contents of the message to be shown on hovering over the option. Any suggestions?
I have also read somewhere that you can't make more than 2 ajax calls at a time.
** The contents for the 3 ajax calls are different. And I have separate JSP files for each of them.
You could do this
$('.link').mouseover(function(){
$.ajax(
/* Retrieve de options for the select and fill each
title attribute with the information*/);
url: "retrieveinfo.jsp",
type: "GET",
data: ({id : 'itemsId'}), //pass the data in JSON form
dataType: "html",
success: function(msg){ //msg contains the html output or you could request XML (or JSON)
$('#info').html(msg);
NFinit();
tooltip.init();
}
});
That would make one AJAX call, populate the select and init niceforms and qtip.
When you make your AJAX call to get the dropdown list content, you can also return the descriptions you want to display for each list item and affect them to the corresponding qtip.
The qtip will show onmouseover, and with the description you have set when populating your dropdown list.
I want to populate the data from a database using client side programming either HTML or javascript. I looked online and got lot of sites giving examples on server side i.e. JSP,ASP or PHP for creating the dropdown menu. I know the simple syntax for creating the HTML dropdown menu and in other languages. But I don't know how to populate that HTML dropdown menu values from the database. Any technique which either gets the data from the JSP page which fetches the data from the database and on selecting a single item triggers a query to JSP page which again fetches data from the database can work for me.
Problem: I want to access the database fields from a html page. The dropdown list of html page should be populate from the database and on selecting a specific value it should get data specific to that option.
Any ideas or links to the sources I should look at.
Just so you can get a general idea of the mechanism: How about an Ajax-call triggered by an event listener like this (could also use click event or whatever):
After the html-document is loaded, add an event listener to the watched element (here onchange) and call a function when the event is triggered:
$(document).ready(function() {
$('#watchedElement').change(callAjaxFunction());
});
Function for Ajax-call:
In the data variable you can send information to the server to decide there which options to send back. Easiest way (though quick and dirty) would be to return (like "echo" in php) the option values in plain text/html and replace the old option-elements with this. I prefer the JSON-ways described in the link from your question's comment, since you have a lot more control on the data but for a first impression you could try if the mechanism works for you in general:
function callAjaxFunction() {
$.ajax({
type: "POST",
url: url,
data: { "selectedValue": $('#watchedElement').val() }
success: function(data) {
$("#idOfSelectElement").html(data);
}
dataType: "HTML"
});
}
Just for testing purposes without any evaluation of the value sent to the server you could send back two dummy options like this (example is php file for simplicity and you even could use an html-file that only contains the text itself):
<?php
echo "<option value='test1'>Test1</option>" .
"<option value="test2">Test2</option>";
?>
Still it's probably better to go the JSON way and add element by element, which makes dbugging and stuff way easier later on.