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() + '\' }',
Related
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'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>
All,
Is this the best way to get the value of a currently-checked/unchecked checkbox?
The number of checkboxes is arbitrary so I need a way to get the value of the checkbox that was checked or unchecked.
By looking at Firebug, I see that by using:
this.defaultValue
I can get the value of the currently-checked/unchecked checkbox but not sure if that's really the best way.
Here is the HTML and below is the Javascript click handler
<div id="ClubSponsorshipPartial">
<table class="table-grid">
<tr>
<td>
<input type="checkbox" value="000000244187" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #1
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #2
<input type="checkbox" value="000000533796" id="slpBackgroundCheck" name="slpBackgroundCheck"> Person #3
</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#ClubSponsorshipPartial input[type=checkbox]").click(function (e) {
var queryStr = '';
var clubKeyNumber = '';
var receivedBackgroundCheckChecked = false;
var memberId = this.defaultValue
clubKeyNumber = 'K06253';
receivedBackgroundCheckChecked = ($("#ClubSponsorshipPartial input[type=checkbox]").is(":checked") ? "true" : "false");
queryStr = "memberId=" + memberId + "&isChecked=" + receivedBackgroundCheckChecked;
$.ajax({
type: "POST",
url: '/Dashboard/BackgroundCheck',
data: queryStr,
datatype: 'json',
success: function (data) {
$.notification({
content: 'SLP Advisor Background Check status saved.',
error: false,
timeout: 5000
});
},
failure: function (data) {
$.notification({
content: 'Error saving SLP Advisor Background Check status.',
error: true,
timeout: 5000
});
},
timeout: 5000
});
});
});
</script>
the id should be unique in your page document, and you should use $(this) to mapping current DOM, you can try below code, may help;
http://jsfiddle.net/kJQr9/
I have a form in my view page.it contains 5 text boxes,one search button.while the user enters values in textbox(Entering all fields are not mandatory)and click on the search button,the values I have to store it in an array and pass it to the controller and depending upon the search results i have to display the results of those searched records.
I am able to store the searched values in an array,now i want how to pass this array to the controller and how to access these values in the controller.
as Jose referred , your request may look like this :
$("#submit").click(function () {
var searchData = new Array();
$(".search-input").each(function () {
searchData.push($(this).attr('value'));
});
$.ajax({
type: "POST",
url: "/Home/Index",
data: {"searchData" : searchData},
success: function (data) {
// do something on success
},
traditional: true,
dataType: "json"
});
return false;
});
and your controller action could be :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index([Bind(Prefix="searchData")] List<string> searchData)
{
return Index();
}
and your form have to have markup like this:
<form id="myform">
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="submit" id="submit" />
</form>
Use ajax. If jQuery is an option you could write something like this
$(form).submit(function()
{
var ;
$.ajax({
type: "POST",
url: "/Controller/Action",
data: JSON.stringify(_yourArrayObject),
success: function(data){
alert(data.Result);
},
dataType: "json"
});
})
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.