I am working on a project that I wanted to use jquery for, however it's come to light that it is mandatory to write in dojo, I've never worked with it before and am having some trouble reading up online as to how to use it.
Below is the code I was using:
<script>
window.onload = function() {
getManager($("#team_name").val());
}
function getManager(team) {
$.ajax({
type: "POST",
url: "getManager.php",
data: {team:team}
}).done(function( manager ) {
$("#manager_name").val(manager);
});
}
</script>
Essentially, there is a drop down <selection> field, when selected (and upon window loading) it should prefill the read-only box below it based upon which team is listed. See the below screenshot for a better idea:
I the above code works fine with jquery, I can't seem to find the equivalent for dojo.
This is the html for the selection field:
<select name="team" id="team_name" onchange="getManager(this.value)" type="text" readonly>
and this is the html code for text input field:
<input name="manager_name" id="manager_name" type="text" readonly/>
The code must be written in dojo as the rest of the page does, unless there is a way to override the dojo with jquery?
window.onload = function() {
getManager(document.getElementById('team_name').value);
}
function getManager(team) {
require(["dojo/_base/xhr"], function(xhr){
xhr.post({
url:"getManager.php",
timeout: 4000,
content: { team:team },
load: function( manager ){
document.getElementById("#manager_name").value = manager;
}
});
});
}
If you are using dojo 1.7 and above no need to use window.onload() or even dojo.addOnLoad() - I think this is what you are looking for
require(['dojo/dom', 'dojo/domReady!', function(dom) {
getManager(dom.byId('team_name').value);
});
function getManager(team) {
require(['dojo/request/xhr', 'dojo/dom'], function(xhr, dom) {
xhr.post('getManager.php', {
method: 'POST',
data: {team: team}
}).then(function(manager) {
dom.byId('manager_name').value = manager;
}, function(error) {
console.error('couldn\'t fetch manger!');
});
});
}
domReady! - is an AMD loaded plugin that will wait until the DOM has finished loading before returning
Related
I've got a problem with some JavaScript code. It works fine when I test the website locally but doesn't work on the server unless I reload the page. The code is below. Please let me know if you need more details.
$(document).ready(function(){
$( "#header_inbox_bar" ).click(function() {
const inboxtopcount = $('#inboxtopcount')
const badgedanger = inboxtopcount.parent('.badge-danger')
$.ajax({
type: 'POST',
url: 'controllers/ctrl_client_update_inbox_notifications.php',
success (res) {
if (res) {
badgedanger.hide()
inboxtopcount.hide()
}
},
});
});
});
my guess is your DOM elements are not binding to the jQuery in time. Also, try inspecting your jQuery for syntax errors or any missing syntax.
To address any binding issues on load, try using the jQuery 'on' method so you can then pass it your #header_inbox_bar element and have it bind at a later time. like this:
$(document).ready(function() {
$('body').on('click', '#header_inbox_bar', function() {
const inboxtopcount = $('#inboxtopcount');
const badgedanger = inboxtopcount.parent();
$.ajax({
type: 'POST',
url: 'controllers/ctrl_client_update_inbox_notifications.php',
success(res) {
badgedanger.hide();
},
});
});
});
My code looks something like this
HTML
<div><input type="checkbox" name="showInactiveBox" value="showInactiveBox" id="showInactiveBox">Show inactive project numbers</div>
Javascript
$("#showInactiveBox").live("click", function () {
if ($(this).is(":checked")) { //checkbox is checked
$.ajax({
type: "POST",
url: "#Url.Action("UpdateInactiveBox", "Project")",
data: {
showInactive: true
}
})
.done(function (data) {
Debug.writeln("Check box is checked?: " + $("#showInactiveBox").is(":checked"));
$("#project-numbers-grid").data("kendoGrid").dataSource.read();
});
I have an else that looks similar to above, just sets the checkbox to false basically. My debug line above in the .done of the Ajax function returns the correct value whether it be checked or not. However I then call the .read() on my grid which relates to more javascript below:
read: {
url: "#Html.Raw(Url.Action("GetActiveProjectNumbers", "Project"))",
type: "POST",
cache: false,
dataType: "json",
data: {
q: function () {
var model = {
projectid: "#Model.Id",
};
return JSON.stringify(model);
},
showinactive: $("#showInactiveBox").is(":checked")
}
},
When I put another Debug.writeline in the server, it is receiving the correct value for "q" but "showinactive" is always read in as false. Is there something with javascript that I don't quite understand where going from function to function will read a different value for ($"checkboxid").is(":checked")?
Thanks
Are you sure .is() works with the jQuery version you are running? You could also try .prop('checked'). I would try running this in the Chrome developer tools on the page:
$("#showInactiveBox").is(":checked")
and
$("#showInactiveBox").prop("checked")
If those return the value you are looking for, then there is something else going on. Try running those in console.log at the point at which you are calling those functions to see what the active output is:
console.log('This is my checkbox value', $("#showInactiveBox").is(":checked"));
In addition to Lawrence Johnson's (.prop) answer I'd take a look at some of the other code you are using.
For instance, when dealing with checkboxes it's always better to use the .change() method rather than click.
Also, the .live method is deprecated now and should be using .on().
When dealing with checkboxes you can easily use "vanilla javascript" to test if the box is checked or not. jQuery is not always the "less code/best solution".
See the below code for all the amendments mentioned above:
<input type="checkbox" name="showInactiveBox" value="showInactiveBox" id="showInactiveBox">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#showInactiveBox').on('change',function(){ //using .on and change rather than click
if ( this.checked ) {//test if checked or not
console.log('checked');
}
})
});
</script>
Change
showinactive: $("#showInactiveBox").is(":checked")
to
showinactive: function() {
return $("#showInactiveBox").is(":checked");
}
and call it with
showinactive()
Currently, you are setting showinactive to the value of the property, which I'm assuming starts as false. Values in javascript don't update with the DOM like that--you need to explicitly check each time.
My question is what is better to use onfocus="ajaxUpdateCompanyList2();" in my input OR $("#CompanyNameFilter").focus(function(), I'm new to jquery, so I have quite some issues with code aswell.
JS code option 1:
$(document).ready(function() {
$("#CompanyNameFilter").autocomplete("ajaxFuncs.php",{cacheLength:1,mustMatch:1,extraParams:{getClientList:1}});
});
$("#CompanyNameFilter").focus(function() {
var CN99 = $("#CompanyNameFilter").val();
url: "clientsFiltering.php?companyname=" + CN99,
method: "GET",
success : function( data ) {
var content = $(data).find("#companyList").html();
}
});
JS code option 2:
$(document).ready(function() {
$("#CompanyNameFilter").autocomplete("ajaxFuncs.php",{cacheLength:1,mustMatch:1,extraParams:{getClientList:1}});
});
$.fn.ajaxUpdateCompanyList2=function() {
var CN99 = $("#CompanyNameFilter").val();
url: "clientsFiltering.php?companyname=" + CN99,
method: "GET",
success : function( data ) {
var content = $(data).find("#companyList").html();
}
};
html code option 1:
It doesn't work at all :S
<input id="CompanyNameFilter" style="width: 205px;"/>
html code option 2:
I get error like, ajaxUpdateCompanyList2 is undefined function :S
<input id="CompanyNameFilter" onfocus="ajaxUpdateCompanyList2();" style="width: 205px;"/>
If using jQuery 1.7+ something like this is the way to go:
$("#CompanyNameFilter").on('focus', function() {
//code here
});
Inline JS is almost never the way to go!
Then again, you should probably start by reading the jQuery documentation, and figure out exactly what it is your trying to do, as the first code looks like it's missing an Ajax function, and the second code looks like some sort of attempt to create a plugin, also missing something essential?
I'm using bsmSelect jQuery plugin. Basically, what it does is changing the way a select-multiple is rendered to make easier to pick up the options. It hides the select element and shows a list instead.
So, first of all I'm applying the plugin function to my select-multiple element:
$(document).ready(function() {
...
$('#my_select_multiple').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
...
});
On the other way, I have another select element (this one is simple) which has an ajax request bind to its change event. This ajax request get new #my_select_multiple options depending on the select simple value. Ajax response is the new HTML for #my_select_multiple options. So I have:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/
}).responseText;
return r;
}
...
$(document).ready(function() {
...
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val()));
}
...
});
AJAX is working as expected. New options are got correctly and they are inserted into #my_select_multiple (which is hidden by bsmSelect plugin, but I can check it with Firebug). But bsmSelect didn't realize new changes and doesn't get updated.
So, I think what I want is to reapply $('#my_select_multiple').bsmSelect(); with its new options.
I've been looking around a little bit and here is what I have tried.
1. I've tried to call again the funcion with the success and complete (one at time) of the AJAX request. Didn't work:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function() { $('#my_select_multiple').bsmSelect(); }
}).responseText;
return r;
}
2. I've tried to bind the function with the on jQuery function. Didn't work:
$('#my_select_simple').on('change', function() {
$('#my_select_multiple').bsmSelect();
});
3. I've tried 1 and 2 removing previosly the HTML generated by bsmSelect. Didn't work.
Thank you very much.
UPDATE: The exact code
First I have a global.js file which apply bsmSelect plugin to some select multiples (.quizzes):
$('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
And then, in the php file I define the updateQuizzes function and bind it to the select simple (project_id) change event:
<script type="text/javascript">
function updateQuizzes(project_id) {
var r = $.ajax({
type: 'GET',
url: '<?php echo url_for('event/updateQuizzes')?>'+'<?php echo ($form->getObject()->isNew()?'':'?id='.$form->getObject()->getId()).($form->getObject()->isNew()?'?project_id=':'&project_id=')?>'+project_id,
success: function() { $('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
}); }
}).responseText;
return r;
}
$('#project_id').change(function(){
$('.quizzes').html(updateQuizzes($(this).val()));
});
</script>
As I told, the AJAX request works without problems, but not the calling bsmSelect the second time...
Not sure if this is what the problem is, but you could try
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val())).trigger('change');
}
This triggers a change event on select_multiple, and might fire bsmSelect. I'm not sure what the problem here is exactly, but that's the best I can come up with.
I think you want to set your HTML in the success of the Ajax call, something like:
function loadNewOptions(val) {
$.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).bsmSelect();
}
});
}
And then calling like:
$('#my_select_simple').change() {
loadNewOptions($(this).val());
}
$(document).ready(function() {
$('#my_select_simple').change() {
$('#my_select_multiple').load("your Url", function(){
$('#my_select_multiple').bsmSelect();
});
}
});
something like this should work.
.load will put whatever your url returns into #my_select_multiple
the first parameter is the url to load, and the 2nd is a function to call when it is done. which is where you need to set up your fancy selector.
Ok, I opened a ticket and bsmSelect developer has answered me in minutes. Great!
To let bsmSelect know about its select changes, you have to trigger a change event on the select. There is no need to call bsmSelect again.
So it can be that way:
function loadNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).trigger('change');
}
}).responseText;
return r;
}
$('#my_select_simple').change(function() {
loadNewOptions($(this).val());
});
Sometimes in my application there are many elements loading so I want to show the typical AJAX spinner above the control (or DOM node) with it disabled.
What is the easiest/best way to do that?
Ideally I would like to:
$("#myelement").loading();
$("#myelement").finishloading();
Or even better being able to do AJAX requests directly with the element:
$("#myelement").post(url, params, myfunction);
Being #myelement a regular node or form input.
You could use beforeSend and complete callbacks:
$.ajax({
url: 'script.cgi',
type: 'POST',
beforeSend: function() {
$('.spinner').show();
},
complete: function() {
// will trigger even if request fails
$('.spinner').hide();
},
success: function(result) {
// todo: do something with the result
}
});
Since you're already using jQuery, you may want to look into BlockUI in conjunction with Darin Dimitrov's answer. I haven't used it yet myself as I just came across this today, but it looks decent.
If you're writing a semi-large-ish application and anticipate making many AJAX calls from different places in your code, I would suggest that you either add a layer of abstraction over $.ajax, or create a helper function to avoid having boiler plate for your UI indicator all over the place. This will help you out a lot should you ever need to change your indicator.
Abstraction method
var ajax = function(options) {
$.ajax($.extend(
{
beforeSend: function() {
$.blockUI();
},
complete: function() {
$.unblockUI();
}
},
options
));
};
ajax({
url: 'script.cgi',
type: 'POST',
success: function(result) {
// todo: do something with the result
});
Helper method
var ajaxSettings = function(options) {
return $.extend(
{
beforeSend: function() {
$.blockUI();
},
complete: function() {
$.unblockUI();
}
},
options
);
};
$.ajax(ajaxSettings({
url: 'script.cgi',
type: 'POST',
success: function(result) {
// todo: do something with the result
}
}));
Also, I wouldn't suggest overwriting the $.ajax method itself.
what i've done in the past is, on post pass the element id (a containing div) to a function which replaces it's inner HTML with a loading image, and then in the post back replace it's content again with the updated real content.
If you want to show the spinner every when an ajax call is in progress I think you should use ajaxStart and ajaxStop.
$("#spinner")
.ajaxStart(function(){$(this).show();})
.ajaxStop(function(){$(this).hide();});