Data lookup using Coldfusion, Ajax, and CFC - ajax

I'm using a string instead of an integer as a key to do a data lookup on a table using ColdFusion and Ajax. My test is not returning any values and I'm completely stomped. I tried to convert the ajax value to a string.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#init").blur(function() {
alert("This input field has lost its focus.");
var initVal = JSON.stringify({'$(this).val()'});
if(initVal != "") {
$.get("testrun.cfc?method=getuser&init=initVal", function(res) {
$("#team").val=res;
}, "JSON");
}
});
});
</script>
<input type='text' name='init' id='init' /><br>
<input type='text' name='team' id='team'/>
ColdFusion component
<cfcomponent>
<cffunction name="getuser" access="remote" returntype="string">
<cfargument name="init" type="string" required="yes">
<cfquery name="getUser" datasource="#DSN#">
SELECT team
FROM users
WHERE init = <cfqueryparam value = "#arguments.init#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfreturn getUser.TEAM />
</cffunction>
</cfcomponent>

The problem is that you are passing the string "initval" in your Ajax call.
In other words, jQuery will not magically turn
"testrun.cfc?method=getuser&init=initVal"
into
"testrun.cfc?method=getuser&init=whateverYouEnteredInTheTextfield"
Pass the value of the variable instead, and leave the URL parameter building to jQuery completely:
$("#init").blur(function() {
var initval = $.trim(this.value);
if (!initval) return;
$.get("testrun.cfc" {
method: "getuser",
init: initval
}).done(function (res) {
$("#team").val(res);
});
});
It helps to open the network tab in your browser's developer tools and look at the Ajax requests as they are happening.

Related

AJAX is not submiting data to php

I have a form which collects some data that data is then stored into local variables, which all worked fine. I then decided that i also wanted to send this data to a php page on the server.
However when I added the AJAX code everything stops and nothing happens, this is built for an app using cordova and i can't seem to debug it.
window.onload = function()
{
document.addEventListener("deviceready", init, false);
}
function init()
{
document.getElementById("btnSave").addEventListener("click",saveData, false);
document.getElementById("btnGet").addEventListener("click", getData, false);
}
function saveData()
{
var user = document.getElementById("user").value;
var name = document.getElementById("name").value;
window.localStorage.setItem("user", user);
window.localStorage.setItem("name", name);
var deviceID = device.uuid;
window.localStorage.setItem("uuid", deviceID);
$.ajax({
type: "POST",
url: "http://www.mydomain.co.uk/folder/add.php",
data: {
user : user,
name : name,
},
success: function(response){
alert("Thank you your information has been saved");
}
});
}
And the form
<label>Username:</label>
<input name="user" type="text" placeholder="" id="user" class="stored form-control">
<label>Name:</label>
<input name="name" type="text" placeholder="" id="name" class="stored form-control">
<button id="btnSave">Save Data</button><br />

Trying to Pass Form Field Values To CFC via AJAX

I have two form field:
<cfinput type="text" name="ticket_id" id="ticket_id" value="#get_ticket.ticket_id#" tabindex="1" readonly="readonly" />
<textarea class='expanding' tabindex="0" name="admin_notes" id="admin_notes" cols="100" rows="5">#get_ticket.admin_notes#</textarea>
I am trying to pass the values of those fields to a CFC function when I press this button.
<input type="button" name="addTechNotes" id="addTechNotes" value="Add New Note" />
Here is my AJAX call:
<!---Javascript for adding notes to ticket --->
<script>
$(document).ready(function () {
//Submit form to add record.
$('#addTechNotes').click(function (e)
{
e.preventDefault();
$.ajax({
data: {tech_notes : $("#tech_notes").val(), ticket_id : $("#ticket_id").val() },
type:'POST',
url:'../cfcs/add_ticket_notes.cfc?method=addNotes',
success: function() {
$("#addNotesMessage").append( "Note successfully entered." );
error: console.log("error");
}
});
});
});
</script>
When I click the botton my browser console logs: error (The error attribute of my AJAX call). What am I missing?
Here is my CFC:
<cffunction name="addNotes" access="remote" returnType="string">
<cfargument name="ticket_id" type="any" required="true">
<cfargument name="tech_notes" type="any" required="yes">
<!--- localize function variables --->
<cfset var dataDetail = "">
<cfoutput>
<cfquery name="dataDetail" datasource="#datasource#">
update closed_tickets
set tech_notes = <cfqueryparam value="#ARGUMENTS.tech_notes#" cfsqltype="cf_sql_varchar">
<!--- adjust cfsqltype if needed --->
WHERE ticket_id = <cfqueryparam value="#ARGUMENTS.ticket_id#" cfsqltype="cf_sql_varchar">
</cfquery>
</cfoutput>
<cfreturn dataDetail>
Your Ajax call was a little broken. Try this:
<script>
$(document).ready(function () {
//Submit form to add record.
$('#addTechNotes').click(function (e) {
e.preventDefault();
$.ajax({
data: {
tech_notes : $("#tech_notes").val(),
ticket_id : $("#ticket_id").val()
},
type:"POST",
url:"../cfcs/add_ticket_notes.cfc?method=addNotes",
success: function() {
$("#addNotesMessage").append( "Note successfully entered." );
}, // CLOSE THE SUCCESS PARAM
// START THE ERROR PARAM
error: function() {
console.log("error");
}
});
});
});
</script>
Your textarea field has a name and id of 'admin_notes' but you're referencing an element with id of 'tech_notes' in the ajax call.
I also prefer to add quotes around my data string
data: '{tech_notes:\'' + $("#tech_notes").val() + '\', ticket_id: \'' + $("#ticket_id").val() + '\' }',

Populate SELECTLIST with AJAX [duplicate]

I have one dropdown that has 14 values. Depending on the value chosen, it'll query a SQL Server database and return some clients to display in a second dropdown.
I want that 2nd dropdown to use the jQuery Multiselect Widget where each value has a checkbox to select.
Here is what I last tried to do, and it just doesn't work.
<form>
<label for="lstTiers">Tier:</label>
<select name="lstTiers" id="lstTiers">
<option value="1">Tier 1</option>
<option value="2">Tier 2</option>
<option value="3">Tier 3</option>
<option value="4">Tier 4</option>
<option value="5">Tier 5</option>
<option value="6">Tier 6</option>
<option value="7">Tier 7</option>
<option value="8">Tier 8</option>
<option value="9">Tier 9</option>
<option value="10">Tier 10</option>
<option value="11">Tier 11</option>
<option value="12">Tier 12</option>
<option value="13">Tier 13</option>
<option value="14">Tier 14</option>
</select>
<label for="lstClients">Client:</label>
<select name="lstClients" id="lstClients">
</select>
<input type="button" name="click_me" id="click_me" value="Click Me" />
</form>
Here is one attempt at the jQuery:
$('#click_me').click(function() { alert('here');
$.ajax({
url: 'Ajax-test.cfc?method=returnSomething',
data: {
Tier: $('#lstTiers').val()
},
cache: false,
dataType: 'json',
success: function(data) {
$('#lstClients').html(data);
},
// This fires when an error with ColdFusion occurs
error: function() {
alert('An error has occured!');
}
});
}); // End click()
I had also tried some other jQuery where I looped and built the options.
Finally, here's my cfc file:
<cfcomponent output="false">
<cffunction access="remote" name="returnSomething" returntype="query" returnformat="json">
<cfargument name="Tier" type="string" required="yes">
<cfquery name="qryGetClients" datasource="ProjectGrid_Test">
SELECT Div, ClientName FROM tblClientUpgradeClients WHERE Tier = #arguments.Tier# ORDER BY Div
</cfquery>
<cfreturn qryGetClients>
<cffunction>
</cfcomponent>
If possible, that returned dropdown should allow user to multiselect using a checkbox. I've played with the jQuery Multiselect widget and I've had it work, but not on this dynamic query.
$('#lstClients).multiselect(
{ noneSelectedText:"All Selected",
show: ["fade"],
hide: ["fade"],
selectedList: 1,
multiple: true,
uncheckAllText: ["Clear"]
});
I will do my best to use the vernacular of your coding in this example
note i am using coldfusion 9.0.1 and jquery 1.9+
jquery/javascript
$('#lstTiers').on('change', function (){
$.ajax({
url:'Ajax-test.cfm',
data: {'method': 'returnSomething',
'Tier': $(this).val(); },
success: function(json){
if (json != '' )
var vx='<option value="">All</option>';
$.each (json, function(k, v){
vx+='<option value="'+v.client_id+'">'+v.client_name+'</option>';
});
$('#lstClients').html(vx);
}
}); //end ajax()
});
Coldfusion
<cffunction name="returnSomething" access="remote" output="false" returntype="json">
<cfargument name="Tier" type="string" required="yes">
<cfset var qryGetClients= "">
<cfquery name="qryGetClients" datasource="ProjectGrid_Test">
Select * from Clients WHERE Tier = #arguments.Tier# ORDER BY 1
</cfquery>
<cfreturn qryGetClients>
</cffunction>
heres the thing, you need to see what return type json format is giving you, if it is coldfusion json, you would change the jquery each iteration to $.each (json.DATA, function(k, v){
i do things in the MVC way , and like my json to be standard non CF output, so heres an example of my code
controller
<cffunction name="getRequestorsByEvent" access="remote" output="false" returntype="query">
<cfargument name="nd_event_id" type="string" required="false">
<cfargument name="status" type="string" required="false">
<cfset var qRequestorsByEvent = "">
<cfquery datasource="#application.DSN#" name="qRequestorsByEvent">
select distinct d.init_contact_staff, initcap(e.pref_name_sort) name from ben_activity_dtl d
inner join entity e
on e.id_number = d.init_contact_staff
where d.nd_event_id = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.nd_event_id#">
<cfif isDefined("arguments.status") and arguments.status neq "">
and d.request_status_code = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.status#">
</cfif>
order by 2 asc
</cfquery>
<cfreturn qRequestorsByEvent>
</cffunction>
model
<cffunction name="RequestorsByEvent" output="false" hint="index">
<cfset var rc=event.getcollection()>
<cfset var returnArray = ArrayNew(1) />
<cfset qRequestorsByEvent = getmodel("dynform").getRequestorsByEvent(rc.nd_event_id, Event.getValue("status", ''))>
<cfloop query="qRequestorsByEvent">
<cfset RequestorsStruct = StructNew() />
<cfset RequestorsStruct["init_contact_staff"] = init_contact_staff/>
<cfset RequestorsStruct["name"] = name />
<cfset ArrayAppend(returnArray,RequestorsStruct) />
</cfloop>
<cfset event.renderData( type="json", data=returnArray ) />
</cffunction>
Try that using cfcomponent and cfselect tag.
The below link may be useful.
http://forta.com/blog/index.cfm/2007/5/31/ColdFusion-Ajax-Tutorial-2-Related-Selects

How to display CFC Data via AJAX

I'm having a tough time figuring this out and I'm a real novice at AJAX. I'm making a call to a CFC via an AJAX request. I'm getting JSON data returned as I can see the results in firebug, I'm just unable to display the query results it into my div.
Can someone show me how to do this?
My Javascript
<script>
// populate the dropdown
// on change of dropdown value return the cfc data into the div
$("##company_name").change(function() {
var selectValue = $("##company_name").val();
$.ajax({
type: "GET",
url:"cfcs/alertData.cfc?method=getAlerts",
dataType: "json",
data: {
returnFormat: 'json',
company_name: selectValue
},
success: function (data) {
$("##test").html(data);
},
error: function (data) {
$("##test").html('Failed');
}
});
});
</script>
My Div
<div id="test">test</div>
My CFC
<cffunction name="getAlerts" access="remote" returntype="query">
<cfargument name="company_name" type="any" required="true">
<!--- localize function variables --->
<cfset var alertDetail = "">
<cfquery name="getID" datasource="#datasource#" >
select customer_id
from customer_table
where company_name = <cfqueryparam value="#ARGUMENTS.company_name#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfquery name="alertDetail" datasource="#datasource#">
SELECT ID
FROM customer_alerts
<!--- adjust cfsqltype if needed --->
WHERE customer_id = <cfqueryparam value="#getID.customer_id#" cfsqltype="cf_sql_varchar"> AND alert_status = 'on'
</cfquery>
<cfreturn alertDetail>
</cffunction>

My Jquery tools Ajax modal login is not working in IE 7 and 8

I am working on modal login/registration forms. I'm not good with Javascript, but have hacked my way to some working Jquery for my Ajax call, and all is working nicely in Chrome 14.0.835.159 beta-m and in Firefox 5 and 6.0.2 and Opera 11.51. I used Firebug to see the JSON returning correctly and updating the error messages.
In FF/Opera/Chrome if I leave the username and login blank and I click the login button on the modal window, the returns count up the failed logins and display the return.I used firebuggerhttp://www.firebugger.com/ to look at what was going on in On IE 7 and 8.
If you leave the form fields blank, it seems the form is somehow "cached" and the call doesnt go through. None of the returns act on my login javascript to update the loginMsg div. If you change the input each time, "a", "as", "asd", the return counts up the failed logins as intended but still no update on my div
Very odd :-(
The test page is at camarillon.com/testpage.cfm
<!DOCType html>
<html>
<head>
<title>testpage - test ajax login</title>
<!-- include the Tools -->
<script src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>
<!--- add styles --->
<link rel="stylesheet" type="text/css" href="css/loginbox.css" />
<!--- <noscript>This is what you see without javascript</noscript> --->
<CFSET structDelete(session, 'form')>
<cfset session.form.validate_require="username|'Username' is required.;password|'Password' is required.;confirmpassword|'Confirm password' is a required field.;">
<cfset session.form.validate_minlength="username|'Username' must be at least 3 characters long.;password|'Password' must be at least 7 characters long.">
<cfset session.form.validate_maxlength="username|'Username' must be less than 6 characters long.">
<cfset session.form.validate_alphanumeric="username|'Username' must be alphanumeric.">
<cfset session.form.validate_password="confirmpassword|password|'Password' and 'Confirm Password' must both match.">
</head>
<body>
<cfparam name="session.auth.loggedIn" default="false">
<div id="loginMenu">
<cfif session.auth.loggedIn>
Log out
<cfelse>
<button class="modalInput" rel="#login">Login</button>
<button class="modalInput" rel="#register">Register</button>
</cfif>
</div>
<!-- user input dialog -->
<cfif isDefined("session.auth.failedLogins")>
<cfset loginMsg=#session.auth.failedLogins# & " failed logins">
<cfelse>
<cfset loginMsg="Please log in">
</cfif>
<script>
$(document).ready(function() {
var triggers = $(".modalInput").overlay({
// some mask tweaks suitable for modal dialogs
mask: {
color: '#ccc',
loadSpeed: 200,
opacity: 0.5
},
closeOnClick: false,
onClose: function () {
$('.error').hide();
}
});
$("#toomanylogins").overlay({
mask: {
color: '#ccc',
loadSpeed: 200,
opacity: 0.9
},
closeOnClick: false,
load: false
});
$("#loginForm").submit(function(e) {
var form = $(this);
// submit with AJAX
$.getJSON("cfcs/security.cfc?method=processLogin&ajax=1&returnformat=JSON&queryformat=column&" + form.serialize(), function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(0).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else if (json === "More than five") {
var tempString
tempString = "<h2>Too many failed logins </h2>"
$("#loginMsg").html(tempString);
triggers.eq(0).overlay().close();
$("#toomanylogins").overlay().load();
} else {
var tempString
tempString = "<h2>" + json + " failed logins</h2>"
$("#loginMsg").html(tempString);
}
});
// prevent default form submission logic
e.preventDefault();
});
// initialize validator and add a custom form submission logic
$("#signupForm").validator().submit(function(e) {
var form = $(this);
// client-side validation OK.
if (!e.isDefaultPrevented()) {
// submit with AJAX
$.getJSON("cfcs/security.cfc?method=processSignup&returnformat=JSON&queryformat=column&" + form.serialize(), function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(1).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else {
form.data("validator").invalidate(json);
}
});
// prevent default form submission logic
e.preventDefault();
}
});
$.tools.validator.fn("[minlength]", function(input, value) {
var min = input.attr("minlength");
return value.length >= min ? true : {
en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : ""),
};
});
$.tools.validator.fn("[data-equals]", "Value not equal with the $1 field", function(input) {
var name = input.attr("data-equals"),
field = this.getInputs().filter("[name=" + name + "]");
return input.val() == field.val() ? true : [name];
});
});
</script>
<!-- yes/no dialog -->
<div class="modal" id="toomanylogins">
<h2>Having problems logging in?</h2>
<p>
If you have forgotten your password you can request a reset.
</p>
<!-- yes/no buttons -->
<p>
<button class="close"> Cancel </button>
</p>
</div>
<div class="modal" id="login">
<!-- login form -->
<form name="loginForm" id="loginForm" autocomplete="off" method="get" action="">
<div id="loginMsg"><h2><cfoutput>#loginMsg#</cfoutput></h2></div>
<p><input type="text" name="username" placeholder="username..." title="Must be at least 8 characters." <!--- required="required" --->></p>
<p><input type="password" name="password" placeholder="password..." title="Try to make it hard to guess" <!--- required="required" --->></p>
<p>
<button type="submit"> Login </button>
<button type="button" class="close"> Cancel </button>
</p>
</form>
</div>
<div class="modal" id="register">
<!-- signup form-->
<form id="signupForm" autocomplete="off" method="get" action="" novalidate="novalidate">
<fieldset>
<p>
<label>firstname *</label>
<input id="firstname" type="text" name="firstname" placeholder="firstname..." required="required"/></p>
<p>
<label>lastname *</label>
<input type="text" name="lastname" placeholder="lastname..." required="required"/></p>
<p>
<label>email *</label>
<input type="email" name="email" placeholder="email..." required="required"/></p>
<p>
<label>username *</label>
<input type="text" name="username" placeholder="username..." required="required"/>
</p>
<p>
<label>password *<br>
<input type="password" name="password" required="required" placeholder="password..." /></label>
</p>
<p>
<label>confirm password *<br>
<input type="password" name="confirmpassword" data-equals="password" placeholder="password..." required="required"/></label>
</p>
<p>
<button type="submit">Sign Up</button>
<button type="button" class="close"> Cancel </button>
</p>
</fieldset>
</form>
</div>
</body>
</html>
Back end is in Coldfusion, but I don't think thats relevant, the JSON returns work just fine in FF etc
Any pointers about what I presume is some bug in my Javascript appreciated, my JQuery kung foo is not strong :-(
Logans solution below is correct ... I also had a trailing comma in here which was wrong only bugging out in IE 5-7
$.tools.validator.fn("[minlength]", function(input, value) {
var min = input.attr("minlength");
return value.length >= min ? true : {
en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : ""),
};
});
should have been
$.tools.validator.fn("[minlength]", function(input, value) {
var min = input.attr("minlength");
return value.length >= min ? true : {
en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : "")
};
});
Instead of using $.getJSON, you can use $.ajax and set the cache option to false. I think that sound fix the issue.
$("#loginForm").submit(function(e) {
var form = $(this);
$.ajax({
type: 'GET',
url: "cfcs/security.cfc?method=processLogin&ajax=1&returnformat=JSON&queryformat=column&" + form.serialize(),
dataType: "json",
cache: false,
success: function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(0).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else if (json === "More than five") {
var tempString
tempString = "<h2>Too many failed logins </h2>"
$("#loginMsg").html(tempString);
triggers.eq(0).overlay().close();
$("#toomanylogins").overlay().load();
} else {
var tempString
tempString = "<h2>" + json + " failed logins</h2>"
$("#loginMsg").html(tempString);
}
}
});
// prevent default form submission logic
e.preventDefault();
});
// initialize validator and add a custom form submission logic
$("#signupForm").validator().submit(function(e) {
var form = $(this);
// client-side validation OK.
if (!e.isDefaultPrevented()) {
// submit with AJAX
$.ajax({
type: 'GET',
url: "cfcs/security.cfc?method=processSignup&returnformat=JSON&queryformat=column&" + form.serialize(),
dataType: "json",
cache: false,
success: function(json) {
// everything is ok. (server returned true)
if (json === true) {
// close the overlay
triggers.eq(1).overlay().close();
$("#loginMenu").html("<a href='logout.cfm'>Log out</a>");
// server-side validation failed. use invalidate() to show errors
} else {
form.data("validator").invalidate(json);
}
}
});
// prevent default form submission logic
e.preventDefault();
}
});
Did you try out
$.ajaxSetup({
cache: false
});
at the beginning of document ready?
Really looks like a problem with the jQuery Cache. If this helps, it certainly is.

Resources