Getting a response from Cfajaximport / ajax with coldfusion - ajax

I've searched a number of the previous responses, but none of them have helped me. I'm actually extrapolating on another script I found earlier.... but I'm not sure how to capture the response in AJAX. I was guessing that handleResponse would just capture whatever is outputted on checkdomain.cfm, but I can't seem to make that happen so I can output it. So in the example below, somehow the person who developed this script was able to get back AVAILABLE from checkdomain.cfm, but I can't figure out how to do that.
Thanks in advance!
<head>
...
<cfajaximport />
...
<script>
function handleResponse(s) {
if(s == "AVAILABLE") {
//rewrite span
var domainspan = document.getElementById('DomainStatus');
var newcontent = "Available To Register :)";
domainspan.innerHTML = newcontent;
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' value='GO!' class='search_domain_go' type='submit' />";
loadingspan.innerHTML = newcontent;
} else {
//rewrite span
var domainspan = document.getElementById('DomainStatus');
var newcontent = "Unavailable To Register :(";
domainspan.innerHTML = newcontent;
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' value='GO!' class='search_domain_go' type='submit' />";
loadingspan.innerHTML = newcontent;
}
}
function CheckDomain() {
var loadingspan = document.getElementById('frmGO');
var newcontent = "<input name='' type='image' class='search_domain_go' src='images/ajax-loader.gif' alt='' />";
loadingspan.innerHTML = newcontent;
ColdFusion.Ajax.submitForm('frmDomainCheck','checkdomain.cfm',handleResponse);
}
</script>
...
</head>
<body>
...
<div class="search_domain">
<div class="search_domain_form">
Search Your Domain Here<br />
<form method="post" action="" onSubmit="CheckDomain();return false;" id="frmDomainCheck">
<input class="search_domain" name="frmURL" id="frmURL" value="Please enter your domain name here..." onfocus="if(this.value == 'Please enter your domain name here...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Please enter your domain name here...';}" type="text" />
<span id="frmGO"><input name="" value="GO!" class="search_domain_go" type="submit" /></span>
<form>
</div><!-- /# end search form -->
<div class="domain_features">
<ul>
<li><span id="DomainStatus">Type in the domain and click 'GO' to check its availability.</span></li>
</ul>
</div>
</div>
...
</body>

I used your code and then added the following for checkdomain.cfm
<cfoutput>AVAILABLE</cfoutput>
It worked just fine. In your handleResponse function, put an alert(s); statement at the top to see just what you're getting back from checkdomain.

Related

How to maintain scroll position when submitting on toggle buttons - one form per toggle button

`I've been searching a lot, and I think the answer to my task is a call to an AJAX function. I'm using classic ASP. Please have in mind that I'm a total newbie. I really need someone to take my hand and tell me what to do. The examples I've found so far doesn't keep the same position on the website on submit. The idea is to press the toggle button (on/off) and save immidiately. That part is working perfectly. But when you have a lot of toggle buttons, and the submit gets you to the top of the page, you have a lot of scrolling down to do after every submit
The folowing is working just fine; either it's on or off. No need to do anything, but to press the toggle button. But if you are way down the webpage, you go way up to the top of the page, and you need to scroll way down to continue where you left off. This is where I want the page to be steady as a rock: Don't do anything on submit. Don't move up, don't move down. Stay put. I hope someone can help.
<%
If Request("mode") = "msgfromadmin" Then
Dim dato10, vUser10
dato10 = Day(Date) & "/" & Month(Date) & "/" & Year(Date) & " " & Time()
vUser10 = SQLEncode(Session("username"))
If Request.Form("msgfromadmin") = Lcase("on") Then
msgfromadmin = 1
Else
msgfromadmin = 0
End If
SQL = Conn.Execute("UPDATE usersettings SET msgfromadmin = " & msgfromadmin & " WHERE username = '" & SQLEncode(Session("username")) & "'")
Response.Redirect("/profile/mysettings/")
End If
%>
<head>
<style>
.switch{position:relative;display:inline-block;width:3.43em;height:1.75em;}
.switch input{opacity:0;width:0;height:0;}
.slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#ccc;-webkit-transition:.4s;transition:.4s;}
.slider:before{position:absolute;content:"";height:1.26em;width:1.26em;left:0.25em;bottom:0.25em;background-color:white;-webkit-transition: .4s;transition:.4s;}
input:checked + .slider{background-color:#4d72ff;}input:focus + .slider{box-shadow: 0 0 0.063em #c4cbe7;}
input:checked + .slider:before{-webkit-transform:translateX(1.625em);-ms-transform:translateX(1.625em);transform:translateX(1.625em);}
.slider.round{border-radius:2.125em;}.slider
.round:before{border-radius:50%;}
</style>
</head>
<html>
<body>
<form name="msgfromadmin" action="/profile/mysettings/" method="post">
<input type="hidden" name="mode" value="msgfromadmin">
<div class="col-12 form-group row mt-4">
<div class="col-1 form-group text-center">
<label class="switch">
<input type="checkbox" name="msgfromadmin" onChange="this.form.submit();"<% If RSchosenSetting("msgfromadmin") = 1 Then %> checked<% End If %>>
<span class="slider"></span>
</label>
</div>
<div class="col-11 form-group">
Send a mail when there's a message from admin
</div>
</div>
</form>
</body>
</html>
Is it something like this you want??
You will have to obviously do the database connections etc on the submitpage.asp
I added the loop to the text and slider to generate a page that is longer.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>msgfromadmin</title>
</head>
<style>
.switch{position:relative;display:inline-block;width:3.43em;height:1.75em;}
.switch input{opacity:0;width:0;height:0;}
.slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#ccc;-webkit-transition:.4s;transition:.4s;}
.slider:before{position:absolute;content:"";height:1.26em;width:1.26em;left:0.25em;bottom:0.25em;background-color:white;-webkit-transition: .4s;transition:.4s;}
input:checked + .slider{background-color:#4d72ff;}input:focus + .slider{box-shadow: 0 0 0.063em #c4cbe7;}
input:checked + .slider:before{-webkit-transform:translateX(1.625em);-ms-transform:translateX(1.625em);transform:translateX(1.625em);}
.slider.round{border-radius:2.125em;}.slider
.round:before{border-radius:50%;}
</style>
</head>
<html>
<body>
<form name="msgfromadmin" action="msgfromadmin.asp" method="post">
<input type="hidden" name="mode" value="msgfromadmin">
<div class="col-12 form-group row mt-4">
<%for i = 1 to 100 %>
<div class="col-1 form-group text-center">
<label class="switch">
<input type="checkbox" name="msgfromadmin<%= i %>" id="msgfromadmin<%= i %>" onChange="loadXMLDoc('<%= i%>','message <%= i%> from admin')" <% If request("msgfromadmin" & i) = "on" Then %> checked<% End If %>>
<span class="slider"></span>
</label>
</div>
<div class="col-11 form-group" id=adminmessage<%=i%>>
Send a mail when there's a message from admin
</div>
<% next %>
</div>
</form>
<script>
function loadXMLDoc(incoming, incoming2) {
var demoChecked = document.getElementById("msgfromadmin"+ incoming).checked;
if (demoChecked == true) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("adminmessage"+incoming).innerHTML = this.responseText;
}
};
xhttp.open("post", "SubmitPage.asp?msgfromadmin="+ incoming +"&message="+incoming2, true);
xhttp.send();
document.getElementById("adminmessage"+incoming).innerHTML = "Mail sent to admin";
} else {
document.getElementById("adminmessage"+incoming).innerHTML = "Send a mail when there's a message from admin";
}
}
</script>
</body>
</html>
and the SubmitPage.asp
<%
If Request("msgfromadmin") <> "" then
Dim dato10, vUser10
dato10 = Day(Date) & "/" & Month(Date) & "/" & Year(Date) & " " & Time()
response.write "Mail sent to admin at " & dato10
' vUser10 = SQLEncode(Session("username"))
' SQL = Conn.Execute("UPDATE usersettings SET msgfromadmin = " & msgfromadmin & " WHERE username = '" & SQLEncode(Session("username")) & "'")
End If
%>

Blank page after submitting external HIT in MTurk

If I submit my external HIT with the https://workersandbox.mturk.com/mturk/externalSubmit URL, it gets succesfully submitted to MTurk (in my requester Sandbox, i can see the result), but for the worker an empty / blank page appears, instead of the confirmation, that her/his HIT got submitted succesfully...
I guess, something with the action-parameter in my form could be wrong...
The HTML-Code of this blank page looks like:
<html><head>
<title><bean:message key="external_submit.title" /></title>
<script type="text/javascript">
function reloadOuterPage() {
var boxes = top.document.getElementsByName('autoAcceptEnabled');
if( boxes.length == 0 || !boxes[0].checked ) {
top.location = top.document.getElementById('hitExternalNextLink').href;
} else {
top.location = top.document.getElementById('hitExternalNextAcceptLink').href;
}
};
</script>
</head>
<body onload="reloadOuterPage();"><bean:message key="external_submit.body">
</bean:message></body></html>
The form I'm submitting:
<form target="_parent" name="hitForm" style="visibility:hidden" id="hitForm" method="POST"
action="https://workersandbox.mturk.com/mturk/externalSubmit">
<input type="hidden" id="assignmentId" name="assignmentId">
<input type="hidden" id="hitId" name="hitId"/>
<input type="hidden" id="workerId" name="workerId"/>
<input type="hidden" id="caption" name="caption" value="TEST">
<input type="submit" name="Submit" id="submitButton" value="submit" disabled="true">
</form>
<button ng-show="!hasAccepted()" disabled>You must first accept the HIT in order to Submit it!</button>
<button ng-click="submitHit(inputText)" ng-show="hasAccepted()">Submit</button>
where the submitHit Method looks like this (the ids get assigned properly - i checked that):
$scope.submitHit = function (cap) {
$scope.form = document.getElementById("hitForm");
$scope.assignmentId = "";
$scope.hitId = "";
$scope.workerId = "";
$scope.assignmentId = $scope.turkGetParam("assignmentId");
$scope.hitId = $scope.turkGetParam("hitId");
$scope.workerId = $scope.turkGetParam("workerId");
document.getElementById("assignmentId").value = $scope.assignmentId;
document.getElementById("hitId").value = $scope.hitId;
document.getElementById("workerId").value = $scope.workerId;
$scope.form.submit();
}
thank you very much for your help!
As always, one works nearly 2 days on this "bug" and after overcoming to ask on stackoverflow, one finds the solution: I had to delete the target="_parent" in my form and now everything works fine!

onclick calling object working ONLY in Firefox

as I stated in the title, I can get the onclick calling object only in Firefox: not in Chrome, not in IE, not in Safari.
I am pretty new to ajax and javascript in general, so I built my code around the answers you guys gave here.
I have a html page with a number of 'products': for each one of them, I have a form with hidden fields which contain the information about the product. Every form has two (submit) buttons: one is to 'add' the product to the shopping cart, the other is to take it 'off' of it.
I want to identify the button that gets clicked in order to identify the product it refers to and then add it to or cancel it from the cart list.
Here is the html code for the page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
TEST
</title>
<meta charset="utf-8">
<script src="form_submit.js" type="text/javascript">
</script>
</head>
<body>
<form id="ajax_1" name="ajax_form" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="1" /><br />
<button id="ajax_1" type="submit" name="on">On</button>
<button id="ajax_1" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<form id="ajax_2" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="2" /><br />
<button id="ajax_2" type="submit" name="on">On</button>
<button id="ajax_2" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<form id="ajax_3" method="POST" action="test.php">
<fieldset>
<legend>My form</legend>
<label for="stnz">Stnz</label><br />
<input type="hidden" name="stnz" id="stnz" value="1" /><br />
<label for="opz">Opz</label><br />
<input type="hidden" name="opz" id="opz" value="3" /><br />
<button id="ajax_3" type="submit" name="on">On</button>
<button id="ajax_3" type="submit" name="off">Off</button><br />
</fieldset>
</form>
<div id="responseArea"> </div>
</body>
</html>
This is the script code:
window.onload = checkButton;
var xhr = false;
var on;
var stnz;
var opz;
var url;
function checkButton() {
var el = document.getElementsByTagName('button');
for(var i=0; i<el.length; i++){
el[i].onclick = function (e) {
// Capturing the event
e = e || window.event;
var targ = e.target || e.srcElement;
on = (targ.name == 'on') ? true: false;
var form = document.getElementById(targ.id);
url = form.action;
stnz = form.stnz.value;
opz = form.opz.value;
makeRequest();
return false;
};
}
}
function makeRequest(){
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr){
var data = "stnz=" + stnz + "&opz=" + opz + "&act=";
if(on){
data = data + "1";
} else {
data = data + "0";
}
xhr.onreadystatechange = showContents;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(data);
}
}
function showContents(){
if(xhr.readyState == 4 && xhr.status == 200) {
var return_data = xhr.responseText;
console.log(return_data);
} else {
var return_data = "Sorry, but I couldn't create an XMLHttpRequest";
console.log(return_data);
}
/*document.getElementById("responseArea").innerHTML = return_data;*/
}
The test.php file is just:
<?php
if (isset($_POST['stnz'],$_POST['opz'],$_POST['act'])){
$stnz= $_POST['stnz'];
$opz = $_POST['opz'];
$act = $_POST['act'];
echo "Stnz: " . $stnz . ", Opz: " . $opz . ", Azt: " . $act;
}
?>
Please, help me fixit this thing for Chrome, IE and Safari....
Also, is there a better way to get the same functionality? (maybe not using forms?)
Thanks a lot!
each browser has its own event handling method , use a library like jquery to be able to handle all the browsers .
$(el[i]).click(function(e){});
using jquery isn't the only solution you can optimize your code for every browser by adding the browser specific codes but that is a recipe for disaster.same goes for your ajax request(cross browser problems).
jquery designed with all the browsers in mind , so you write just one code and jquery handles the browser specific stuff .
example for your ajax with jquery :
https://api.jquery.com/jQuery.ajax/
$.ajax({
url : url,
type:'POST',
data:{"stnz" : stnz , "opz" : opz , "act" : (on ? 1 : 0)}
success : function (data){
},
error:function(){}
});

Ajax script not running on submit button click

I'm following a tutorial and when I click the submit button nothing happens. I added an alert to see if the function runs. It runs the alert.
[code]
<!-- THE HTML PAGE AND JAVASCRIPT -->
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// added by me to test
alert("Hello");
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Your First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>
[php]
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
What am I doing wrong here?
It doesn't give any errors at all. Please help me.
http://jsfiddle.net/HjhV4/
try this
html
<h2>Ajax Post to PHP and Get Return Data</h2>
<form id="form">
Your First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data">
<br /><br />
</form>
<div class="status"></div>
javascript
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#form") .submit(function(){
var first_name = $("#first_name") .val();
var last_name = $("#last_name") .val();
var s = {
"first_name":first_name,
"last_name":last_name
}
$.ajax({
url:'action.php',
type:'post',
data:s,
beforeSend: function (){
$(".status") .html("<img src=\"style/img/ajax/load1.gif\" alt=\"Loading ....\" />");
},
success:function(data){
$(".status").html(data);
}
});
});
})
</script>

ajax post no update in django template

I want to post some text in django with ajax,and save the input data,show the data in same page and no refresh,like twitter.
my js:
$('#SumbitButton').click(function(){
var data_1 = $('#data_1').val()
var data_2 = $('#data_2').val()
var data_3 = $('#data_3').val()
var data_4 = $('#data_4').val()
var user = $('#AuthorName').text()
var authorprotrait = $('#UserProprait').html()
if(data_1.length>0){
$.ajax({
type: 'POST',
url: '/post/',
data:{'data_1':data_1,'data_2':data_2,'data_3':data_3,'data_4':data_4},
async: false,
error: function(msg){alert('Fail')},
success: function(msg){
$('#TopicWrap').prepend("<div class='topic-all even'><div class='topic-left'><div class='topic-author'><div class='topic-author-protrait'>"+authorprotrait+"</div><div class='topic-author-nickname'>"+authorname+"</div></div></div><div class='topic-right'><div class='topic-meta'><span class='topic-datetime'></span></div><div class='topic-content-wrap'><div class='topic-content'>"+msg+"</div></div></div><div class='clearfix'></div></div>");
$('#data_1').val('');
$('#data_2').val('');
$('#data_3').val('');
$('#data_4').val('');
}
});
} else {
alert('The data_1's length error !'+data_1.length);
}
});
and the html:
<div id="TopicTextarea">
<div>
data1:<input tabindex="4" id="data_1" type="text" name="data1" value="" maxlength="6" placeholder=""/></br>
data2:<input tabindex="4" id="data_2" type="text" name="data2" value="" maxlength="8" placeholder=""/></br>
data3:<input tabindex="4" id="data_3" type="text" name="data3" value="" maxlength="10" placeholder=""/></br>
data4:<input tabindex="4" id="data_4" type="text" name="data4" value="" maxlength="10" placeholder=""/>
<div id="TopicFormControl">
<button type="button" id="SumbitButton" class="button orange">sumbit</button>
</div>
</div>
   <div class="clearfix"></div>
</div>
<div id="TopicWrap">
{% include 'topics.html'%}
</div>
and the views:
#login_required
def post(request):
assert(request.method=='POST' and request.is_ajax()==True)
data_1 = smart_unicode(request.POST['data_1'])
data_2 = smart_unicode(request.POST['data_2'])
data_3 = smart_unicode(request.POST['data_3'])
data_4 = smart_unicode(request.POST['data_4'])
data_obj = DataPool(user=request.user,data_1=data_1,data_2=data_2,data_3=data_3, data_4=data_4)
data_obj.save()
content = '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
response = HttpResponse(cgi.escape(content))
return response
when I input the data and click the sumbit button,it can save the data ,but it can't show the data.what's wrong in my code?
thanks.
First, use something like Poster to test that your view is returning what you expect. Only then should you start building the AJAX part.
As for what's wrong... it's a bit difficult to say since you just write that it "can't show the data" instead of saying what it's actually doing. I suspect it has to do with this line in your view:
content = '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
It's not really clear to me what you think this would do, but what it actually does is:
>>> '"+data_3+"  "+data_4+" "+data_1+"("+data_2+")'
'"+data_3+" \xe3\x80\x80"+data_4+"\xe3\x80\x80"+data_1+"("+data_2+")'
That is to say that it produces a string containing the substrings "data_3" (etc..) It does not include the submitted data.

Resources