Updating local ColdFusion variable in Ajax - coldfusion-11

I have been trying to perform a simple task (in ASP) for a coldfusion page. I have a local variable "pt.PreCaution" that I need updated. I have tried the following code with no success.
<cfset pt.PreCaution = "">
<label>
Patient Precaution:
</label>
<br>
<cfselect name="lstPreCaution" multiple="yes"
query="GetPreCaution"
value="IsoTypeID"
display="IsoTypeName"
size="8"
required="yes"
width="100"
height="25"
label="Precaution: "
onclick="PreCautionSelected(this)"
>
</cfselect>
function PreCautionSelected(val){
var result ="";
var frm=eval('document.next');
for(i = 0 ; i < val.children.length; i++)
{
if(val.children[i].selected){
if(result.length < 1)
{
result = val.children[i].value;
}
else
{
result = result + "," + val.children[i].value;
}
}
}
$.ajax({
type: "POST",
url: "details.cfm",
data: { "#pt.PreCaution#" : result}
}).done(function(){alert(result)})
}
I modified the ajax call as follows:
function PreCautionSelected(val){
var result ="";
var frm=eval('document.next');
for(i = 0 ; i < val.children.length; i++)
{
if(val.children[i].selected){
if(result.length < 1)
{
result = val.children[i].value;
}
else
{
result = result + "," + val.children[i].value;
}
}
}
$.ajax({
type: "POST",
url: "FileUpdater.cfc?method=setPrecautionType",
data: { lstPrecaution : result}
}).done(function(){})
}
<cfcomponent>
<cffunction name="setPrecautionType" access="remote" returntype="Any" >
<cfargument name="lstPrecaution" type="any" required="true" >
<cfset session.lstPreCaution = #arguments.lstPrecaution#>
<cfreturn />
</cffunction>
</cfcomponent>
I added the following CFC file. This file updates the session variables.
CFC File

Thanks for the input. The Ajax function is getting called and the complete data is being extracted. The only problem is the ColdFusion variable is not getting updated on the server side.
I fixed this problem by written the data to the session data. The problem is the old CF5 frame work that the program is written in.

You have only one mistake.select box not have onclick functionality so you have onchange function means working fine

Related

The parameter to the function is required but was not passed in

I am making a filter in order to drill down into a report. I have two fields that are dependent on the selection of another field (which is a multiselect list). When I make my selection(s) from that multiselect field, it looks like the parameter is being passed in as an array and ultimately not being recognized. It looks as if my parameter is being passed in as an array, which I'm thinking is the issue
Javascript Code:
function getMO()
{
var fa_code = $('#tslcFilterFA').val();
var ao_code = $('#tslcFilterAO').val();
var wq_code = $('#tslcFilterWQ').val();
var newOption = '';
$('#tslcFilterMO').empty();
$('#tslcFilterMO').append(newOption);
$('#TSLC_MO_Loading').css('display','inline');
$.ajax({
url: '../TSLC/getData.cfc',
type:"POST",
cache: false,
dataType: "text",
async:true,
data: {method: "getMO",
fa_code: fa_code,
ao_code: ao_code,
wq_code: wq_code
},
success: function(returnMsg)
{
try
{
var obj = JSON.parse(returnMsg);
$.each(obj.DATA, function(index,row) {
if (obj.DATA.length == 1)
{
var newOption = '<option selected="selected" value="' + row[0] + '">' + row[1] + '</option>';
}
else
{
if (row[2] == "1")
{
var newOption = '<option selected="selected" value="' + row[0] + '">' + row[1] + '</option>';
}
else
{
var newOption = '<option value="' + row[0] + '">' + row[1] + '</option>';
}
}
$('#tslcFilterMO').append(newOption);
});
try
{
$('#tslcFilterMO').multiselect('destroy');
}
catch(e) {}
$('#tslcFilterMO').multiselect({
selectedList: 4
}).multiselectfilter();
$('.ui-multiselect').css('width','225px');
$('#TSLC_MO_Loading').css('display','none');
}
catch(e)
{
alert('getMO Error parsing JSON');
}
},
error: function(httpRequest, textStatus, errorThrown)
{
alert("getMO status=" + textStatus + ",error=" + errorThrown);
}
});
}
I've tried to change this line:
var ao_code = $('#tslcFilterAO').val();
to this:
var ao_code = $('#tslcFilterAO').multiselect('getChecked').map(function () {return this.value;}).get();
I've also tried to wrap my ao_code variable in URLDecode() to see if it would pass the value as a string instead of an array, but neither works.
CF Code (from component):
<cffunction name="getMO" access="remote" returntype="any" returnformat="plain" hint="Get distinct Managing Orgs based on FA=ATT_IT and AO">
<cfargument name="fa_code" type="string" required="true">
<cfargument name="ao_code" required="true">
<cfargument name="wq_code" required="true">
<cfquery name="qMO" datasource="#request.dbdsn_ic4p#" username="#request.dbuser_m66266#" password="#request.dbpw_m66266#">
SELECT DISTINCT managing_org MANAGING_ORG, DECODE(managing_org,'*','*ALL*',managing_org) MANAGING_ORG_DISPLAY, DECODE(managing_org,'*',1,2) sortcol
<cfif #fa_code# NEQ "ATT_IT">
FROM HAS_TICKET_STATE_GUI_LOOKUP
WHERE client_id = '#fa_code#'
<cfelse>
FROM IT_TICKET_STATE_GUI_LOOKUP
WHERE 1=1
</cfif>
<cfif #ao_code# neq "">
AND active_org IN (<cfqueryparam value="#ao_code#" cfsqltype="cf_sql_varchar" list="true" />)
</cfif>
<cfif #wq_code# neq "">
<!--- !COM: is workaround for commas in listbox items! --->
AND work_queue IN (#replace(ListQualify(wq_code,"'",",","CHAR"),":COM!",",","all")#)
</cfif>
ORDER BY 3, 1
</cfquery>
<cfreturn serializeJson(qMO)>
</cffunction>
Change this line in your JS code
var ao_code = $('#tslcFilterAO').val();
to
var ao_code = $('#tslcFilterAO').val().join(",");
That should give you a list of string values from the multiple select field that you're expecting in your function in the CFC.
The join() method joins all elements of an array into a string. More on "join" here.
This article helped me solve my problem... https://christierney.com/2011/06/07/returning-multiple-value-elements-to-coldfusion-remote-method-via-jquery-ajax/
function getWQ()
{
var fa_code = $('#tslcFilterFA').val();
var ao_code = $('#tslcFilterAO').val();
if ($.isArray(ao_code))
var ao_code_array = ao_code.join(",");
else
var ao_code_array = ao_code;
var mo_code = $('#tslcFilterMO').val();
if ($.isArray(mo_code))
var mo_code_array = mo_code.join(",");
else
var mo_code_array = mo_code;
var newOption = '';
$('#tslcFilterWQ').empty();
$('#tslcFilterWQ').append(newOption);
$('#TSLC_WQ_Loading').css('display','inline');
$.ajax({
url: '../TSLC/cfcs/getData.cfc',
type:"POST",
cache: false,
dataType: "text",
async:true,
data: {method: "getWQ",
fa_code: fa_code,
mo_code: mo_code_array,
ao_code: ao_code_array
},
success: function(returnMsg)
{
Have you considered a combination of the jQuery serializeArray() function and the param() function? It creates a string similar to a query string which is easily parsed. You could send the whole form in.
Example: $.param($('#yourform').serializeArray(),false);
Or, perhaps, simply use the serializeArray function to send your function a JSON string?

dropdown populated on basis of another using ajax in coldfusion, not working

I have searched a lot through this website and found some similar posts, but they could not help. I have 2 dropdowns. The first is populated through an inline query. The second needs to be populated through the first's selection. I know cfselect and cfajaxproxy are 2 of the simplest things, but I want to use them on Railo which doesn't support them (checked and returned disappointed).
The ajax code goes like this:
$.ajax({
type: 'POST',
url: 'admin/getModelsForManufs.cfc?method=getModels&returnFormat=JSON',
data: {manuid:selected},
dataType: "text",
success: function(res) {
var newoptions = "";
for(var i=0; i<res.length; i++) {
newoptions += "<option value=\"" + res[i].ID + "\">" + res[i].NAME + "</option>";
}
$("#model").append(newoptions);
},
error: function(x) {
alert(x.responseText);
}
});
Where manuid is the first selection, and model is the html field ID for second dropdown to be populated. The cfc has the following:
<cffunction name="getModels" access="remote" returnType="array">
<cfargument name="manuid" type="numeric" required="true" default="#url.manuid#">
<cfset var data="">
<cfset var result=[]>
<cfset var i=0>
<cfquery name="data" datasource="#THIS.dsn#">
select modelId, modelName
from tablename
where manufacturerid = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.manuid#">
</cfquery>
<cfloop index="i" from="1" to="#data.RecordCount#">
<cfset model = {}>
<cfset model.NAME = data.modelName[i]>
<cfset model.ID = data.modelId[i]>
<cfset arrayAppend(result, model)>
</cfloop>
<cfreturn result>
</cffunction>
In Firebug, the data is in the format:
[{"ID":84.0,"NAME":"name 1"},{"ID":1.0,"NAME":"name 2"}]
which looks correct and there are many more records returned. Have tried most of the tricks but still scratching my head as to why the second dropdown doesn't populate. Any help is highly appreciated. Thanks in advance.
Try this code
$.ajax({
type: 'POST',
url: 'admin/getModelsForManufs.cfc?method=getModels&returnFormat=JSON',
data: {manuid:selected},
dataType: "text",
success: function(res) {
var res2 = JSON.parse(res);
var newoptions = "";
for(var i=0; i<res2.length; i++) {
newoptions += "<option value=\"" + res2[i].ID + "\">" + res2[i].NAME + "</option>";
}
$("#model").append(newoptions);
},
error: function(x) {
alert(x.responseText);
}
});

eval for parsing JSON giving undefined

I am working on Grails framework. I have 2 domain classes Country and City with one-to-many relationship. My idea is when the page is loaded the gsp will have two select boxes, one populating the countries and when any country selected the cities of that country are populated in second select box. here i am using grails ajax (jquery).
import grails.converters.JSON
class CountryController {
def index() { redirect action: 'getCountries' }
def getCountries() {
def countries = Country.list()
render view:'list', model:[countries:countries]
}
def getCities() {
def country = Country.get(params.id)
render country?.city as JSON
}
}
When getCities action is fired i am getting the JSON as below:
[
{
"class":"com.samples.City",
"id":3,
"country":{
"class":"Country",
"id":2
},
"description":"California",
"name":"California"
},
{
"class":"com.samples.City",
"id":4,
"country":{
"class":"Country",
"id":2
},
"description":"Dalls",
"name":"Dalls"
}
]
But from my gsp page when evaluating JSON with eval function, its returning "undefined".
<g:select name="countrySelect" from="${countries}"
optionKey="id" optionValue="name"
noSelection="[null:'Select Country']"
onchange="${
remoteFunction(action: 'getCities',
update: message,
params: '\'id=\' + this.value',
onSuccess:'updateCity(data)')
}"/>
<br/>
City :: <g:select name="city" id="city" from=""></g:select>
Following code in tag
<head>
<g:javascript library="jquery"></g:javascript>
<g:javascript>
function updateCity(data) {
alert('done');
var cities = eval("(" + data.responseText + ")") // evaluate JSON
alert(cities)
var rselect = document.getElementById('city')
// Clear all previous options
var l = rselect.length
while (l > 0) {
l--
rselect.remove(l)
}
//build cities
for(var i=0; i < cities.length; i++) {
var opt = document.createElement('option');
opt.text = cities[i].name
opt.value = cities[i].id
try{
rselect.add(opt,null) //For Non IE
}catch(ex){
rselect.add(opt) //For IE
}
}
}
</g:javascript>
<r:layoutResources />
</head>
Can anyone help me finding out where is the problem?
I got it solved by using JQuery each method on JSON data.
<g:javascript>
function updateCity(data) {
var rselect = document.getElementById('city')
$.each(data, function(index, element) {
//alert(element.name);
var opt = document.createElement('option');
if(element.name !== undefined){
opt.text = element.name
opt.value = element.id
try{
rselect.add(opt,null) //For Non IE
}catch(ex){
rselect.add(opt) //For IE
}
}
});
}
</g:javascript>

Ajax passing image variable

I used to use the following Ajax code to pass variables. However, it doesn't seem to work with images. Any suggestions?
<p>
<input type="file" name="image" /><br />
<input type="button" value="Submit" onclick="addImage()" />
</p>
<div id="content"> </div>
<script>
function addImage() {
var image = $('input[name=image]').val();
$.ajax({
type: "POST",
url: "/chat",
data: {'image': image},
cache: false
});
}
</script>
Correctly speaking, you'll need to pass the data to the page in a special manner. Check out this tutorial by Nettuts+, I used it when I was confronted with a similar problem.
The only difference is that you are only allowing a single upload, while it allows many uploads. You can fix that by turning off the multiple attribute.
Also, it automatically uploads the image after selection, so you might wanna try this:
document.getElementById('yourbuttonsid').onclick = function () {
var i = 0, len = this.files.length, img, reader, file;
document.getElementById("response").innerHTML = "Uploading . . ."
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
}
}
}
instead of this:
if (input.addEventListener) {
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
document.getElementById("response").innerHTML = "Uploading . . ."
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
}
}
}, false);
}
Hope I helped. Twiddle the settings to your personal need if necessary.
JSON objects are made only to transfer strings, basic objects, integers and a few other things. They are not meant for sending images. However, if you still want to try implementing this in your own way, I can think of two ways to do it. Firstly, just send the name of the images (exact link) or upload it and provide the path.
Or secondly, convert it to base64 in the browser, send it, and have code convert it back whenever required.
That would look something like this:
<form method="async" onsubmit="addImage(this.image)">
<input type="file" name="image" /><br />
<input type="submit" value="Submit" />
</form>
<div id="content"></div>
<script>
function addImage(img) {
$.ajax({
type: "POST",
url: "/chat",
data: {'image': toBase64(img)},
cache: false
});
}
function toBase64(img) {
// Create an HTML5 Canvas
var canvas = $( '<canvas></canvas>' )
.attr( 'width', img.width )
.attr( 'height', img.height );
// Initialize with image
var context = canvas.getContext("2d");
context.drawImage( img, 0, 0 );
// Convert and return
return context.toDataURL("image/png");
}
</script>

jquery array push not working properly inside ajax success

I am trying to push a div id into an array.Array push is working good bofore ajax call.But when i use push inside ajax success first push is taken place when i click on the second element.that is
array operation when with below code( array push inside success)
first click on id="1" --- resuting array []
second click on id="2" --- resulting array [1]
second click on id="3" --- resulting array [1,2]
my code
$(document).ready(function() {
var count = 0;
var vPool = '';
arr = [];
seat = [];
var totalseat = '<?php echo $sumofseat; ?>';
var date = ' <?php echo $new_date; ?>';
$('.custom_checkbox').click(function() {
pressed = true;
var prev = $(this).attr('class');
var arrid = $(this).attr('id');
var seats = $(this).attr('title');
count = $('.selected').length;
if (prev == 'custom_checkbox') {
//arr.push(arrid);
//seat.push(seats);
$.ajax({
url: "seat_manipulation.php",
dataType: 'json',
data: '&operation=save&seat=' + arrid + '&guid=<?php echo $guid; ?>&date=' + date,
type: "POST",
context: this,
success: function(data) {
if (data.status == 'SAVED') {
$(this).toggleClass('selected');
$('#count').slideDown();
$('#selecte_seat').show();
$('#count').html(count + ' Seats selected');
alert(arrid);
//if(jQuery.inArray(arrid,arr) == -1) {
arr.push(arrid);
//}
//if(jQuery.inArray(seats,seat) == -1) {
seat.push(seats);
//}
} else {
alert("Seat already been used.Please select another");
}
}
})
}
});
});
am i wrong..or this is how its suposed to work ?? Thanks in advance
You need to configure you're Ajax with "async:false" ,because there is a Race Condition thing ,so block the code while you're manipulating Array's.
Se this question.
The AJAX call you are making is asynchronous (by definition...), meaning that the actual function you are defining in $('.custom_checkbox').click is already finished before the success function is called...
When you click on the next div (e.g. div 2) then the success function of the first click may or may not have already been called...
Could this be the problem?

Resources