Javascript function only runs once? Attempting to use same function multiple times - javascript

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!

Related

Javascript - Changing tag-it source with select option

I have a select with two options. When changing the select ... I want to filter/autocomplete a different database. Without http://aehlke.github.io/tag-it/ it's working fine and the autocomplete is changing the source ... but not with it. It stays at source_01.php although I see in the console the change of Test Source 01 to Test Source 02. What might causes this?
HTML:
<select id="search_database" class="form-control">
<option value="1" selected="">Source 01</option>
<option value="2">Source 02</option>
</select>
Javascript:
$('#search_database').on('change', function () {
if ( $('#search_database').val() == 1 ) {
console.log('Test Source 01');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_01.php",
...
});
},
...
})
});
} else if ( $('#search_database').val() == 2 ) {
console.log('Test Source 02');
$("#input-newsearch").tagit({
...
autocomplete: ({
source: function( request, response ) {
...
$.ajax({
url: "/source_02.php",
..
});
},
...
})
});
}
});
Your problem is the value not getting picked up by the script when you change the options if you want to pick the value of the changed option you've to do something similar to the below code.
HTML:
<label for="clientSelect" style="margin-left:14px;">Client:</label>
<select name="clientSelect" id="clientSelect" onChange="clientId(this.id)" style="width:180px;"></select>
<input type="text" id="clintId" size="1" hidden>
JavaScript:
function getClient(cId){
//Get the selected ID using this.is in client side HTML then breaks it up using this to get the ID only
var select = document.getElementById("catSelect"),
optionId = select.options[select.selectedIndex],
catId = optionId.id;
I use the hidden text filed to send the selected ID to my PHP then to the database.

C# Razor - Display comment where looped in value equals selectedIndex value

I have a select list that looks like this:
<select class="form-control">
<option>Select</option>
<option value="2">Order</option>
<option value="5">Delivery</option>
<option value="6">PickUp</option>
<option value="13">Quote</option>
</select>
Once a user selects an option, I would like to display a comment only where db_Type = the value of the selected option:
foreach (var note in Model.GetNotes)
{
<div class="current-note-container">
<h5 class="note-comment"><b>Description:</b><br/> #note.db_Comment.Where(note.db_Type == /* Selected Index */)</h5>
</div>
}
I'm not really sure how I can accomplish this using razor, or how to mix javascript in to get the job done.
This is not exact, but I'm think you're looking for something like this
<select class="form-control" onchange="GetComment(this.value)">
<option>Select</option>
<option value="2">Order</option>
<option value="5">Delivery</option>
<option value="6">PickUp</option>
<option value="13">Quote</option>
</select>
Add this to the script of your razor view
function GetComment(ID)
{
var parameters = {};
parameters["ListID"] = ID;
$.ajax
({
type: "GET",
data: parameters,
url: "/MyController/GetComment",
success: function (message) {
$('#note-comment').val(message);
},
error: function () {
alert("error");
}
});
}
And finally something like this to your controller
[HttpGet]
public JsonResult GetComment(int ListID)
{
return Json(Mylist[ListID].Comment);
}
Razor is a server side code and so you can not combine it with client script like what you are planning to.
Instead use jQuery to listen to the selection changed event and pass (GET/POST) newly selected value back to controller and query database and get the required comment.
jQuery inside View (pseudo code):
$( "#ddlOptions" ).change(function() { //assuming ddlOptions is the Id of select list
var selectedOptionId= $(this).val();
$.get('#Url.Action("ActionName","ControllerName")', { id: selectedOptionId},
//You can use $.get(...) or $.post(...) based on action method type.
function (data) {
//Display/append the comment received to a container(div/span etc)
});
});
Controller code (pseudo code)
public JsonResult Get(int id)
{
//Query database here based on id to get the comment
//e.g: db_comment.where(com=>com.id==id).FirstOrDefault();
return Json(comment,JsonRequestBehavior.AllowGet);
}
Hope this provide you some idea.

TypeError: elem.nodeName is undefined when trying to do an ajax call

Good morning everyone.
I know this may have been asked before, but I'm finding it difficult to get a solution specific to my circumstances so I thought I'd ask here.
I am working on a site which has an account section for customers to add Pets to their inventory. The form itself has a "species" drop down which in turn triggers a change event on the "breeds" drop down in order to populate it with breed specific to the chosen species.
However, in the event of the user submitting the form prematurely without having selected a breed, an error will show but the breeds drop down is now un-populated as the trigger is on the change of the species drop down. So, to fix this I added a clause in the javascript to detect whether the species drop down has a value on load which in turn will trigger the function that populates the breed box. However, I get the error above when the page is reloaded and the box is not populated.
Here is the jQuery:
jQuery('#species').change(function () {
var species_id = $(this).val();
loadBreeds(species_id);
});
if (jQuery('#species').val() != "") {
var species_id = $(this).val();
loadBreeds(species_id);
}
function loadBreeds(species_id) {
console.log('loadBreeds is running');
jQuery.ajax({
url: "http://dev.mediaorb.co.uk/hiltonherbs.com/index.php?route=account/breeds",
type: "post",
data: "species_id=" + species_id + "&action=populateBreeds",
success: function (data) {
console.log('\nSuccess.');
jQuery('#breed option').remove();
jQuery('#breed').append('<option value="">-- Please select --</option>');
if (!data) {
jQuery('#breed').append('<option value="" disabled="disabled">No breeds found for selected species.</option>');
} else {
jQuery('#breed').append(data);
}
}
});
}
And here is part of the form HTML:
<div class="form-group">
<label for="species" class="required">Species</label>
<select class="form-control" id="species" name="species">
<option value="" selected="selected">-- Please select --</option>
<option value="1">Dog</option>
<option value="2" selected="selected">Cat</option>
<option value="3">Bird</option>
<option value="4">Horse</option>
</select>
</div>
<div class="form-group">
<label for="breed" class="required">Breed</label>
<select name="breed" id="breed" class="form-control">
<option selected="selected" value="">-- Please choose a species first --</option>
</div>
I have created a jsfiddle here to illustrate this functionality: http://jsfiddle.net/1961bgay/
Ideally you will need the console open (or firebug on Firefox) to see when the error occurs.
I think it may be relating potentially to the fact I have duplicated the jQuery selectors, but this is required in order to check and to add the trigger...any help appreciated, thank you!
Michael
You just have a small JS context/scoping error:
Change line 9:
From this:
var species_id = $(this).val();
To this:
var species_id = jQuery('#species').val()
Here is your working jsFiddle: http://jsfiddle.net/xgkefvbq/
Hope that helps!

ajax function what to put in url

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
});

populate jquery form from XML

I am attempting to populate a jquery form with data from an XML where the XML has an id that will populate a dropdown in the form and upon selection of an id other form fields will be populated. BTW I will not be using PHP
My XML
<XMLReview>
<plan>
<planNumber>773</planNumber>
<Area>Upper Missouri</Area>
<ID>MISSOURI-NUT</ID>
<Name>Missouri River</Name>
<code>10030101</code>
<County>Broadwater</County>
<Station_ID>M09MISSR05</Station_ID>
</plan>
<plan>
<planNumber>774</planNumber>
<Area>Columbia</Area>
<ID>FLAT-STILL-TPA-2013</ID>
<Name>Sheppard Creek</Name>
<Description>- 3A</Description>
<code>17010210</code>
<County>Flathead</County>
<Station_ID>C09SHEPC04</Station_ID>
</plan>
</XMLReview>
The HTML
<form>
<input type="button" id="btnxml" value="XML" onclick="getXML()" />
ID <input type="text" name="ID" id="ID">
planNumber<input type="text" name="Name" id="planNumber">
area<input type="text" name="Area" id="Area">
Name: <input type="text" name="Name" id="Name">
Description: <input type="text" name="Description" id="Description">
Station ID <input type="text" name="Station_ID" id="Station_ID">
<label class="Code-label" for="code">HUC</label>
<select class="select_code" id="code" name="code" data-iconpos="left" data-icon="grid">
<option></option>
<option> 10010001</option>
<option> 10010002</option>
<option> 10020001</option>
</select>
<label class="county-label" for="County">County</label>
<select class="select_county" id="County" name="County" data-iconpos="left" data-icon="grid">
<option></option>
<option> Beaverhead </option>
<option> Big Horn </option>
<option> Blaine </option>
</select>
</form>
The script
<script>
function getXML()
{
$.get("XMLReview.xml", function(data) {
$.ajax({
type: "GET",
url: "XMLReview.xml",
dataType: "xml",
success: function (xml) {
var select = $('#ID');
$(xml).find('plan').each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected'));
var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
var value = $(this).text();
});
});
}
});
alert(data);});
}
</script>
Unfortunataly this is not working and I don't know why. Can anyone help me please
One or two things:
You are specifying the onclick event inline:
<input type="button" id="btnxml" value="XML" onclick="getXML()" />
Why not keep everything in one place -- since you already are using quite a bit of jQuery. Just add it to the javascript block like this:
<input type="button" id="btnxml" value="XML" />
and
$('#btnxml').click(function() {
getXML();
});
Without checking your javascript/ajax code, this construction is wrong:
function getXML(){
$.get("XMLReview.xml", function(data) { <<======= REMOVE
$.ajax({
type: "GET",
url: "XMLReview.xml",
dataType: "xml",
success: function (xml) {
var select = $('#ID');
$(xml).find('plan').each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected'));
var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
var value = $(this).text();
}); //END $(xml).find.eq.find.each
}); //END #ID.change
}); //END $(xml).find.each
alert(data);
} //END AJAX.success fn
}); //END $.ajax
}); //END $.get <<=================================== REMOVE
}
It should look like this:
function getXML(){
$.ajax({
type: "GET",
url: "XMLReview.xml",
dataType: "xml",
success: function (xml) {
var select = $('#ID');
$(xml).find('plan').each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected'));
var newOpt = $(xml).find("values").eq(selectedIndex).find('value').each(function () {
var value = $(this).text();
}); //END $(xml).find.eq.find.each
}); //END #ID.change
}); //END $(xml).find.each
alert(data);
} //END AJAX.success fn
}); //END $.ajax
}
The extra $.get() wrapper is unnecessary.
Note that $.ajax() and $.get() and $.post() do the same thing. You are using the more structured $.ajax() construction, which is (IMHO) easier to keep things straight.
$.get() simply hard-codes the type="GET" and $.post() hard-codes the type="POST"
Also, I haven't done much with the XML dataType, but I strongly suspect that xml -- in the success function of your AJAX code block, in this context:
success: function (xml) {
//post ajax code here, for eg.
alert(xml);
}
Is a variable that will contain whatever has been ECHOed/printed/etc from the server side script? I don't believe it's an XML object...
Ok there are kind of a lot of things going on here so I figured a fresh implementation would be easier to understand than a series of corrections (I'll try and note places where your understanding of JavaScript might need some work) First a demo. Now the JavaScript:
$('#btnxml').on('click', function() {
var select = $('#ID'),
xml = $($.parseXML($('#XMLData').text())),
plans = xml.find('plan');
plans.each(function () {
var ID = $(this).find('ID').text();
select.append("<option>" + ID + "</option>");
});
$("#ID").change(function () {
var selectedIndex = $('#ID option').index($('#ID option:selected')),
plan = $(plans[selectedIndex]);
$('#planNumber').val(plan.find('planNumber').text());
$('#Area').val(plan.find('Area').text());
$('#Name').val(plan.find('Name').text());
$('#Description').val(plan.find('Description').text());
$('#Station_ID').val(plan.find('Station_ID').text());
$('#code').val(plan.find('code').text());
$('#County').val(plan.find('County').text());
}).trigger('change');
});
And then the HTML
<script type='text/xml' id='XMLData'>
<XMLReview>
<plan>
<planNumber>773</planNumber>
<Area>Upper Missouri</Area>
<ID>MISSOURI-NUT</ID>
<Name>Missouri River</Name>
<code>10030101</code>
<County>Broadwater</County>
<Station_ID>M09MISSR05</Station_ID>
</plan>
<plan>
<planNumber>774</planNumber>
<Area>Columbia</Area>
<ID>FLAT-STILL-TPA-2013</ID>
<Name>Sheppard Creek</Name>
<Description>- 3A</Description>
<code>17010210</code>
<County>Flathead</County>
<Station_ID>C09SHEPC04</Station_ID>
</plan>
</XMLReview>
</script>
<form>
<input type="button" id="btnxml" value="XML" /><br/>
ID <select type="text" name="ID" id="ID"></select><br/>
planNumber<input type="text" name="Name" id="planNumber"><br/>
area<input type="text" name="Area" id="Area"><br/>
Name: <input type="text" name="Name" id="Name"><br/>
Description: <input type="text" name="Description" id="Description"><br/>
Station ID <input type="text" name="Station_ID" id="Station_ID"><br/>
<label class="Code-label" for="code">HUC</label>
<select class="select_code" id="code" name="code" data-iconpos="left" data-icon="grid">
<option></option>
<option>10010001</option>
<option>10010002</option>
<option>10020001</option>
<option>10030101</option>
<option>17010210</option>
</select>
<br/>
<label class="county-label" for="County">County</label>
<select class="select_county" id="County" name="County" data-iconpos="left" data-icon="grid">
<option></option>
<option>Beaverhead</option>
<option>Big Horn</option>
<option>Blaine</option>
</select>
</form>
First, I made these changes to make this easier to demonstrate in JSFiddle, but they don't necessarily match what your final code will be:
I faked the AJAX request (the other answer here gives you a clear explanation of how to properly use jQuery's excellent AJAX helper methods). When rolling this answer into yours you can just assume that all of this is wrapped in a $.get() that fetches your XML remotely.
I also bound the click handled in JavaScript to $('#btnxml') (this is cleaner, but also because JSFiddle doesn't like onclick attributes that point to named functions), this is not strictly wrong it's just cleaner.
Now for the substantive changes:
You are really trying to do two things, populate your $('#ID') selector (which was originally a <input type='text'> which is incorrect, in this code I updated to to a <select>, and then after it's populated you are trying to bind a change event handler. You had these steps inside each other, and I separated them back out. Also programmaticly changing a <select> doesn't trigger a change event automatically, so I appended a .trigger('change') at the end.
It also appears that you are attempting to take the child nodes of the selected plan and update the corresponding input with the same name. You could use the .childNodes property but this will include TextNodes for all of the white-space between XML nodes, and rather than trying to filter them out I thought it would be cleaner to just map them individually. This may not work for you if your HTML and XML are constantly being updated but the next point I'm going to make possibly would prevent a totally automatic approach anyways.
Selecting an option based on a value presents some challenges. jQuery is very smart. If you have a <select> element with a set of options that don't have value attributes and you try and set that <select> element's .val() by a string of one of those <option>s inside that element it will do the right thing. However if there are no elements that match that value then it will silently pass over it. Your XML has code and County values that do not appear in your HTML. I added the missing code values to show you that it is working, but I didn't add them to the County <select>. If you know all of your possible codes and county's and you can update your HTML then this won't be a problem, if instead you want new values to be appended while old values are just selected, then your code will get a little trickier.

Categories

Resources