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.
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() + '\' }',
I have a Windows Media Object that is showing a stream from our conference center from Windows media encoder. The browser everyone uses is IE8. I have created the object and adjacent to it a chat application using AJAX/JQuery. The goal of the chat app was to ping the server for new messages in the database. For some reason, The typing becomes troublesome missing some keys as the user types. i.e. "Fox jumps over the brown cow" turns into "fx jum ovr thbrown ow"
I have tried:
Putting the object in an iframe
Removing the Server Ping Function completely
Placing the append in an if statement
Here is the code:
HTML:
<div class="wrapper">
<div id="video">
<div id="player">
<!--[if !IE]> -->
<object id="mediaplayer" type="application/x-ms-wmp" data="data:application/x-ms-wmp," class="wide">
<param name="src" value="mms://r2pwd-s096186:8080" valuetype="ref" type="video.wmv">
<param name="animationatStart" value="1">
<param name="transparentatStart" value="1">
<param name="windowlessVideo" value="true">
<param name="autoStart" value="1">
<param name="ShowControls" value="0">
<param name="ShowDisplay" value="0">
<param name="ShowStatusBar" value="0">
<param name="playcount" value="10">
<param name="autoRewind" value="1">
<param name="displaysize" value="0">
<param name="stretchtofit" value="1">
<param name="enableContextMenu" value="0">
<param name="uiMode" value="none">
<strong>Error:</strong>You need Windows Media Player Plugin.
</object>
<!--> <![endif]-->
<!--[if IE]>
<object id="mediaplayer" type="application/x-ms-wmp" classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" class="wide">
<param name="url" value="mms://r2pwd-s096186:8080" valuetype="ref" type="video/x-ms-wmv">
<param name="animationatStart" value="1">
<param name="transparentatStart" value="1">
<param name="autoStart" value="1">
<param name="ShowControls" value="0">
<param name="windowlessVideo" value="true">
<param name="ShowDisplay" value="0">
<param name="ShowStatusBar" value="0">
<param name="playcount" value="99999">
<param name="clickToPlay" value="1">
<param name="autoRewind" value="1">
<param name="displaysize" value="0">
<param name="stretchtofit" value="1">
<param name="enableContextMenu" value="0">
<param name="uiMode" value="none">
<strong>Error:</strong>You need Windows Media Player Plugin.
</object>
<![endif]-->
</div>
</div>
<div id="chat">
<div id="chatWindow">
<div id="chatBox"></div>
<div id="chatControls">
<div id="input">
<input id="messageInput" name="message" value="" />
</div>
<div id="send">
<input id="sendButton" name="message" type="button" value="Send" />
</div>
</div>
</div>
</div>
</div>
The JS:
function getSessionMessages() {
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var today = new Date(),
h = today.getHours(),
mins = today.getMinutes(),
secs = today.getSeconds(),
m = checkTime(mins),
s = checkTime(secs),
tod = "am",
newMessage = $('#messageInput').val();
if (h>12){
h=h-12;
tod="pm"
}
var timeStamp = h + ":" + m + ":" + s + tod,
data = {time: timeStamp, guid: guid},
json = JSON.stringify(data);
$.ajax({
type: "POST",
url: wsPath+'?method=getSessionMessages',
contentType: "application/JSON; charset=utf-16",
data: json,
cache: false,
beforeSend: function() {
//alert(json);
},
error: function(data,status,error){
alert('Something went wrong: ' + data + ', ' + status + ', ' + error);
},
dataType: 'JSON'
}).done(function(api) {
//console.log( api );
$(api).each(function( index, value ) {
$('#chatBox').append('<div class="messageEntry"><span>' + this.TIMESTAMP + ': </span><span><strong>' + this.NAME + '</strong></span>: <span>' + this.MESSAGE + '</span></div>');
});
$('#chatBox').scrollTop($('#chatBox')[0].scrollHeight);
newMessages();
});
};
// This is the service call that is on an interval
function newMessages () {
setInterval(function () {
var count = $('.messageEntry').length,
data = {numOfItems: count, guid: guid},
json = JSON.stringify(data);
$.ajax({
type: "POST",
url: wsPath+'?method=newMessages',
contentType: "application/JSON; charset=utf-16",
data: json,
cache: false,
beforeSend: function() {
//alert(json);
//console.log(json);
},
error: function(data,status,error){
alert('Something went wrong: ' + data + ', ' + status + ', ' + error);
},
dataType: 'JSON'
}).done(function(api) {
//console.log( api[0] );
if (api == ""){
return false
}else{
$(api).each(function( index, value ) {
$('#chatBox').append('<div class="messageEntry"><span>' + this.TIMESTAMP + ': </span><span><strong>' + this.NAME + '</strong></span>: <span>' + this.MESSAGE + '</span></div>');
});
}
});
}, 1000);
};
// This is the service call when a new message is input
function sendMessage() {
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var today = new Date(),
h = today.getHours(),
mins = today.getMinutes(),
secs = today.getSeconds(),
m = checkTime(mins),
s = checkTime(secs),
tod = "am",
newMessage = $('#messageInput').val()
if (h>12){
h=h-12;
tod="pm"
}
var timeStamp = h + ":" + m + ":" + s + tod,
data = {time: timeStamp, message: newMessage, userID: userID, guid: guid},
json = JSON.stringify(data);
$.ajax({
type: "POST",
url: wsPath+'?method=newMessage',
contentType: "application/JSON; charset=utf-16",
data: json,
dataType: "JSON",
cache: false,
beforeSend: function() {
//alert(json);
},
error: function(data,status,error){
alert('Something went wrong: ' + data + ', ' + status + ', ' + error);
},
dataType: 'JSON'
}).done(function(api) {
//console.log( api );
$('#chatBox').append('<div class="messageEntry"><span>' + api.TIMESTAMP + ': </span><span><strong>' + api.NAME + '</strong></span>: <span>' + api.MESSAGE + '</span></div>');
$('#chatBox').scrollTop($('#chatBox')[0].scrollHeight);
$("#messageInput").val('');
});
}
$(document).ready(function () {
getSessionMessages();
$("#sendButton").on('click', function () {
sendMessage();
});
$("#messageInput").on('keypress', function (e) {
if (e.which === 13) {
sendMessage();
}
});
});
The CFC:
<cfcomponent>
<cffunction name="getSessionMessages" access="remote" returntype="array" returnformat="JSON">
<!--- This is the service call that is called once the DOM is loaded
* Incoming Data: A Time Stamp and the GUID {time: timeStamp, guid: guid}
* It takes the messages that currently exist in the database and loads them into an array
* Outgoing Data: A Time Stamp, User Names and their messages
--->
<cfset params = toString( getHttpRequestData().content ) />
<cfset args = #deserializeJSON(params)# />
<cfset theguid = #args.guid# />
<cfquery name="qrym" datasource="Chat">
select NRCLive.*, name_last, name_first
from NRCLive inner join hr.dbo.tblRegionIIEmployee on
NRCLive.EmployeeID = hr.dbo.tblRegionIIEmployee.EmployeeID
where NRCLive.GUID = <cfqueryparam cfsqltype="cf_sql_varchar" value="#theguid#">
</cfquery>
<cfset ary = arraynew(1) />
<cfoutput query="qrym">
<cfset sval = {timeStamp="#qrym.dtTimeStamp#", name="#qrym.name_first# #qrym.name_last#", message="#comment#"} />
<cfset retval = arrayappend(ary, sval) />
</cfoutput>
<cfreturn ary>
</cffunction>
<cffunction name="newMessages" access="remote" returntype="array" returnformat="JSON">
<!--- This is the service call that is on an interval
* Incoming Data: Current Number of chat entries and the GUID {numOfItems: count, guid: guid}
* It takes the current number of chat entries and uses that number to move through to latest chat entries that havent been added yet
* Then it grabs all new entries after that and sends the data back in an array
* Outgoing Data: A Time Stamp, User Names and their messages
--->
<cfargument name="numOfItems" type="array" />
<cfset params = toString( getHttpRequestData().content ) />
<cfset args = #deserializeJSON(params)# />
<!--- ****************************************************************************************
'
' Inputs:
' numOfItems - Existing comments in the chat box. We want to retrieve everything that comes
' AFTER this in the database.
'
' Outputs:
' JSON formatted array of messages contained in the database.
' *************************************************************************************** --->
<cfset theguid = #args.guid# />
<cfquery name="qrym" datasource="Chat">
select NRCLive.*, name_last, name_first
from NRCLive inner join hr.dbo.tblRegionIIEmployee on
NRCLive.EmployeeID = hr.dbo.tblRegionIIEmployee.EmployeeID
where NRCLive.GUID = <cfqueryparam cfsqltype="cf_sql_varchar" value="#theguid#">
</cfquery>
<cfset ary = arraynew(1) />
<cfset istart = #args.numOfItems#+1 />
<cfif #qrym.RecordCount# GT 0>
<cfloop query="qrym" startrow="#istart#">
<!--- Screen chat messages for language --->
<cfinvoke component="chat" method="screenOutput" returnvariable="comment"
stext="#qrym.Comment# " />
<cfset sval = {timeStamp="#qrym.dtTimeStamp#", name="#qrym.name_first# #qrym.name_last#", message="#comment#"} />
<cfset retval = arrayappend(ary, sval) />
</cfloop>
</cfif>
<cfreturn ary>
</cffunction>
<cffunction name="newMessage" access="remote" returntype="struct" returnformat="JSON">
<!--- This is the service call when a new message is input
* Incoming Data: Current Number of chat entries and the GUID {numOfItems: count, guid: guid}
* It takes the current number of chat entries and uses that number to move through to latest chat entries that havent been added yet
* Then it grabs all new entries after that and sends the data back in an array
* Outgoing Data: A Time Stamp, User Names and their messages
--->
<cfset params = toString( getHttpRequestData().content ) />
<cfset args = #deserializeJSON(params)# />
<cfset lanID = "#args.userID#" />
<cfquery name="qryemp" datasource="HR">
select name_last, name_first, EmployeeID
from tblRegionIIEmployee
where Username = <cfqueryparam cfsqltype="cf_sql_varchar" value="#lanID#">
</cfquery>
<cfset timeStamp="#args.time#" />
<cfset name="#qryemp.name_first# #qryemp.name_last#" />
<cfset message="#args.message#" />
<cfset theguid = "#args.guid#" />
<!--- Screen chat messages for language --->
<cfinvoke component="chat" method="screenOutput" returnvariable="comment"
stext="#message#" />
<cfif #qryemp.RecordCount# EQ 1>
<!--- We should always have a recordcount of 1 --->
<!--- Enter into our NRCLive database --->
<cfquery name="qryins" datasource="Chat">
insert into NRCLive
(
GUID, Uname, EmployeeID, Comment, dtTimeStamp
)
values
(
'#theguid#', '#lanID#', #qryemp.EmployeeID#, '#comment#', '#timeStamp#'
);
</cfquery>
</cfif>
<cfset myResult={timeStamp="#args.time#", name="#name#", message="#comment#"} />
<cfreturn myResult>
</cffunction>
<cffunction name="screenOutput" access="public" returntype="string">
<!--- ************************************************************************************
' Created By: Tom Easum
' Date: 07/09/2014
'
' Inputs:
' stext - The message we need to filter.
'
' Outputs:
' A string that has been cleared for nrc use.
'
' We may need to filter language for our chat app. At the very least we need to change
' "Yes" into "Yes." and "No" into "No." due to an existing bug in CF that, when
' returning JSON values, changes this to TRUE/FALSE. We should also filter for
' swear words.
' ********************************************************************************** --->
<cfargument name="stext" type="string" required="yes" hint="chat application message">
<!--- Filter for the stupid CF bug that was never fixed. Yes is JSON'd into True and No is JSON'd into False --->
<cfset sval = #arguments.stext# />
<cfif #sval# EQ "yes" or #sval# EQ "Yes" or #sval# EQ "YES">
<cfset sval = "#sval#." />
</cfif>
<cfif #sval# EQ "no" or #sval# EQ "No" or #sval# EQ "NO">
<cfset sval = "#sval#." />
</cfif>
<!--- Filter for bad language Took this out so I don't get a bad nod from stack for cusasing LOL--->
<!--- Filter for javascript, or other bad hacking attempts --->
<cfset sval = ReplaceNoCase(sval, "<script", "", "all") />
<cfreturn sval />
</cffunction>
</cfcomponent>
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>
I was looking at Ben's example # http://www.bennadel.com/blog/1515-Ask-Ben-Building-An-AJAX-jQuery-And-ColdFusion-Powered-Application.htm and wokring on an ultra simplistic example of my own. but it seems like even though the CFC returns properly formatted JSON, it always ends up in my error handler with the error :
Invalid JSON: {"ERRORS":"","SUCCESS":true,"DATA":"id DEX015-002-00, whs W1, qty 9"}
Here's the ajax call
$.ajax({
type: 'GET',
url: 'bridge.cfc',
data: {
method: 'UpdateQty',
id: 'DEX015-002-00',
whs: 'W1',
qty: '9'
},
dataType:'json',
success: function(res, status, req){ alert("Message from server:\n" + "res: " + res); },
error: function(req, status, err){ "Error from server:\n" + "err: " + err); }
});
And heres the CFC "bridge.cfc"
<cfcomponent>
<cffunction name="UpdateQty" access="remote" returntype="struct" returnformat="json" output="false">
<cfargument name="id" required="yes" type="string">
<cfargument name="whs" required="yes" type="string">
<cfargument name="qty" required="yes" type="string">
<cfset res = structNew()>
<cfset res.success = true>
<cfset res.data = "id " & arguments.id & ", whs " & arguments.whs & ", qty " & arguments.qty >
<cfset res.errors = "">
<cfreturn res >
</cffunction>
</cfcomponent>
What am I missing ?
Usually when I run into this issue, it's because I have debugging set to output, and it gets tacked on to my remote method's output.
Try adding:
<cfsetting showDebugOutput="no" />
to your UpdateQty method.
Try adding output=false to your cfcomponent.