sorry for asking such a basic question, but i am new to ajax and i couldn't find a documentation (i dont even know the name of this ajax syntax).i understand other parts of this code snippet but i don't know what am i supposed to put in the url part of the $.ajax function. please help
<form method="GET" action="">
<select name="docSpec" id="docSpec">
<option value="Pulmonary" selected="selected">Pulmonary</option>
<option value="Physician">Physician</option>
<option value="General">General</option>
<option value="Cardiologist">Cardiologist</option>
<option value="pediatrics">pediatrics</option>
</select>
</form>
js:
function do_something() {
var selected = $('#docSpec').val();
$.ajax({
this part-- > url: '/you/php/script.php',
type: 'POST',
dataType: 'json',
data: {
value: selected
},
success: function (data) {
$('#my_div').html(data);
}
});
}
this is the javascript! by the way, i am trying to get a selected option value from a <select> ("supposedly on change as a trigger") without having to submit the form.
You can get the selected value of the <select> using
$('#docSpec').val();
You don't need to use ajax for that. Changing the selected option of a <select> will not trigger form submission or reload the page by default.
You can get the value when it is changed using the change() method:
$('#docSpec').change(function(){
alert(this.value); // You can access the new value here
});
Related
As that title says, I am attempting to use the same javascript function multiple times on the same page. Basically, I have 2 separate drop downs that call users via ajax so that even new users will be present. (The site is based off not having to always reload.) Anyways, the way I currently have it setup is something like this...
Javascript:
function getAllUsers() {
(function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
$('#getAllUsers').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
}
});
})();
}
getAllUsers();
function getAllUsers2() {
(function getAllUsers2() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
$('#getAllUsers2').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers2, 5000);
}
});
})();
}
getAllUsers2();
I am sure that doing it like this is unpractical, hence why I am asking for some guidance now.
This is the current HTML setup for it on the dropdowns:
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2" name="user" id="getAllUsers2" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
Obviously the Loading Users... option is replaced when the ajax data is loaded.
Again though, I am sure that a better way of doing this exists.
But whenever I try to do something like this with the html... using the same javascript function, the second one just stays at "Loading Users..."
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
I would think that doing it the way I currently do with multiple functions all calling the PHP file constantly can cause load time issues after a while espically if I add more.
Thank you for any assistance!
Both select2's are using the same endpoint, why not just assign the value in the same ajax request?
Something like this will be okay:
function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: data => {
$('#getAllUsers').html(data);
$('#getAllUsers2').html(data);
},
error: err => {
//$('#getAllUsers').html("<option>test</option>");
//$('#getAllUsers2').html("<option>test</option>");
},
complete: () => {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
}
});
}
getAllUsers();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select2" name="user" id="getAllUsers" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2" name="user" id="getAllUsers2" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
First, you need to understand why it doesn't work for you and then find a solution.
The problem is that, you are using the same element ID in two separate elements, this is not strictly forbidden and will not throw you any errors, but it points to a wrong implementation.
When you are trying to select elements with the ID getAllUsers using jQuery, it knows that there should be only one such element, so it selects only the first one. Any other elements with the same ID are ignored. That's why it worked only for the first one.
Now, let's try to find solutions.
One solution, as Miroslav Glamuzina suggested is correct and works, but not flexible enough.
Another solution would be using a selector that selects multiple element which is not an ID. The best option is to use element's class, that will be unique for your two (or more) select elements. So if you want to add another one in the future, you don't have to touch the JS code, but only the HTML part.
You can do something like this:
HTML
<select class="select2 getAllUsers" name="user" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
<select class="select2 getAllUsers" name="user2" required>
<option selected="true" disabled="disabled">Loading Users...</option>
</select>
(Note that I also changed the name attribute of the second select, to prevent issues in the future)
JavaScript
(function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
$('.getAllUsers').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
}
});
}());
WARNING!
If you are planning to use this script publicly, you should pay attention on the security issue in this script.
This script is opened for XSS attacks. Because, you are requesting a remote content and applying its content as HTML without any data validations nor escaping.
I would suggest in your case, to generate a JSON in the PHP script, with the list of users and all the data you need, then on the JavaScript, create option elements using the data from the JSON list.
You should do something like this:
Let's say that this is the JSON received from staff/getAllUsers.php:
[
{"id": 14, "name": "User 1"},
{"id": 16, "name": "User 2"},
{"id": 17, "name": "User 3"}
]
JavaScript:
(function getAllUsers() {
$.ajax({
url: 'staff/getAllUsers.php',
success: function(data) {
try {
const list = JSON.parse(data); // Parse JSON from string to object
const selectEl = $('.getAllUsers').empty(); // Clear the content of both `select` elements
for ( let i=0; i<list.length; i++ ) { // Loop through each item in the JSON array
$('<option />') // Create an `option` element
.attr('value', list[i].id) // Set attribute `value` to `option` element
.text(list[i].name) // Set `option` text (this function also escapes any special characters, which prevents potential XSS attacks)
.appendTo(selectEl); // Add `option` element to both `select` elements
}
} catch (e) {
// Report any errors with the JSON parsing process to the developer console.
console.error(e);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// Track any errors received from the server for debugging purposes
console.error(textStatus, errorThrown);
}
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getAllUsers, 5000);
},
dataType: 'json' // Expect a `json` back from server
});
}());
I hope you can learn something from this.
Good luck!
I'm trying to add a new feature to this pagination/filtering script but so far, without succes. I want that, when you change the page, the filter you picked from the top right corner select (that with "Ordonare dupa...) to remain picked instead of switching back to the first option.
This is my website - http://www.wheelsmarket.ro/cautare/jante/1
To paginate/filter i used this function:
$(document).ready(function()
{
$('.sortare').on('change', function(){
$.ajax({
url: '/filtrare-jante.php',
type: 'POST',
data: {'selected' : $(this).val(), 'pagina_id' : <?php echo $_GET['pagina'];?>},
success: function(data){
console.log(data); // do something with what is returned
$('#myTest').html(data);
$('#queryInitial').html('null');
}
});
});
All the querys are made inside a #myTest div, and the myTest div gets changed without reloading when you change that select. The problem is that the select box is out of #myTest div, so i doubt that i can make use of that function i have.
ex:
<select class="sortare select" >
<option value="1">cele mai noi</option>
<option value="2">cele mai ieftine</option>
<option value="3">cele mai scumpe</option>
</select>
<div id="myTest">
code
</div>
If i understood correctly you need something like :
1) Add id to your options:
<select class="sortare select" >
<option id="sel1" value="1">cele mai noi</option>
<option id="sel2" value="2">cele mai ieftine</option>
<option id="sel3" value="3">cele mai scumpe</option>
</select>
<div id="myTest">
code
</div>
AND change tha attr() to selected in jquery :
$(document).ready(function()
{
$('.sortare').on('change', function(){
selValue = $(this).val(); //---> Store this value in a variable.
$.ajax({
url: '/filtrare-jante.php',
type: 'POST',
data: {'selected' : $(this).val(), 'pagina_id' : <?php echo $_GET['pagina'];?>},
success: function(data){
console.log(data); // do something with what is returned
$('#myTest').html(data);
$('#queryInitial').html('null');
$('#sel'+selValue).attr("selected","selected"); //---> Use the variable we created to determine which option should be set to selected dynamically
}
});
});
We have the following SELECT combobox that is populated dynamically with ajax and httphandler web service (.ashx).
When SELECT combobox is dynamically populated, it looks like this:
<select name="selectid" id="selectid">
<option value="">-Select an option-</option>
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</o4tion>
<option value="4">Test5</option>
<option value="5">Test6</option>
<option value="6">Test7</option>
</select>
Below is the js:
function getText() {
$.ajax({
url: 'rulings.ashx',
dataType: 'json'
})
.done(function(textInfo) {
$(textInfo).each(function(i, texts) {
$('<option>').val(texts.dbtextID).text(texts.textToBeDisplayed).appendTo( $('#selectid') );
})
});
}
When we display the values from the dropdown, it displays the VALUE options instead of the displayed text.
Example from the combobox above, it displays 1 instead of Test1.
How do I modify the script to show displayed text instead of VALUE options?
Try this code , just put it inside
$(document).ready(function(event){
$("#selectid").on('change',function() {
//alert($("#selectid option:selected").text());
$('#summTextvalue').html($("#selectid option:selected").text());
});
})
The ON method in jQuery can bind events to dynamically created elements.
or you can also do something like
function _bindEvent()
{
$("#selectid").on('change',function() {
alert($("#selectid option:selected").text());
});
}
and call _bindEvent() from your AJAX done method
Try this to get text, instead of value.
$('#selectid').change(function(){
var selectedVal=$(this).val();
alert($(this).children("option[value='"+selectedVal+"']").text());
});
At present I have a small web-form that loads AJAXed data really nicely from a drop down menu:
<select name="showcode" id="showcode">
<option value="1"> First Name</option>
<option value="2"> Last Name</option>
</select>
What I would like to do is create the action from a text link such as:
First Name
Last Name
I don't know how to change the .change(function() { JS to correctly perform an action onclick event to make this happen. Below is the JS part. Any thoughts / help would be greatly appreciated.
$(document).ready(function(){
$("#showcode").change(function() {
var usr = $("#showcode").val();
$("#getassociatedprojects").html('Retrieving..');
$.ajax
({
type: "POST",
url: "/client-stories/data.php",
data: "showcode="+ usr,
success: function(msg)
{
$("#getassociatedprojects").ajaxComplete(function(event, request, settings)
{ $(this).html(msg); });
}
Worked it out.
Assigned a rel and class to the <a href>
First Name
Then changed the Javascript call in to:
$('a.topic').click(function() {
var usr = $(this).attr('rel');
Voila. It worked. :)
I want to use the following function for all the ajax calls in my site:
function ajaxcall(my_url, my_div, my_data)
{
$(my_div).append('<div style="text-align:center; position:absolute; top:0; left:0; width:100%;"><img src="/images/loading.gif" /></div>');
$.ajax({ url: my_url,
data: {data: my_data},
type: 'get',
success: function(output)
{
$(my_div).html(output);
}
});
}
It gets whatever URL I want and updates the DIV I want, so far so good. The problem is I also need to send 1 or more values and want to predict the names of those values.
<select class="formtext" name="car_id" id="car_id" onChange="ajaxcall('/ajax/carsetup.php', '#car_setups', $(this).val() )">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="car_setups">select car</div>
So what this does is send my select value to the function, it works, however I don't know how to call that value anything, right now its called data but I want to name it whatever I wish, in this case car_id, dynamically, even worse I might want to send more values in that function's third slot. How would I get around this?
Right now print_r($_GET); gives me:
Array ( [data] => 2622 )
Just do:
data: my_data,
instead of:
data: {data: my_data},
and you can then pass whatever values you look to your AJAX script, e.g.
<select class="formtext" name="car_id" id="car_id"
onChange="ajaxcall('/ajax/carsetup.php', '#car_setups', {car_id: $(this).val()} )">
That said, you should consider attaching that AJAX call from within your JS itself, rather than inline in the HTML:
$('#car_id').change(function() {
ajaxCall('/ajax/carsetup.php', '#car_setups', {car_id: this.value});
});