onclick calling object working ONLY in Firefox - ajax

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(){}
});

Related

AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing?

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});
By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

Javascript validate all radio buttons if checked

Im so dumb in javascript, I would like to ask your help about radio button validation. I have 3 set of questions, each has 3 radio buttons. I want to validate if all the 3 questions have been answered or checked.
Thanks in advance
Here is the code I have tested, it only validates 1 radiobutton
<script type="text/javascript">
function validateForm() {
var radios = document.querySelectorAll("#option1, #option2, #option3, #option4, #option5, #option6");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must check some option!");
return formValid;
}
</script>
I have solved the problem with this code
if ($('div.quizbox:not(:has(:radio:checked))').length) {
alert("You missed answering one or more of the questions.");
}
try this it works for me
<script type="text/javascript">
function validateForm(){
var inputs = document.querySelectorAll("#option1,#option2,#option3,#option4,#option5,#option6")
var formValid = false;
for(var i=0;i<inputs.length;i++){
if(inputs[i].checked){
formValid = true;
}
}
if(!formValid ){
alert("Must check some option!");
}
}
</script>
html code
<body>
<form name="frm">
Question 1<br>
<input type="radio" name="group1" value="Ans1" id="option1">Ans1<br>
<input type="radio" name="group1" value="Ans2" id="option2">Ans2<br>
Question 2<br>
<input type="radio" name="group2" value="Ans1" id="option3">Ans1<br>
<input type="radio" name="group2" value="Ans2" id="option4">Ans2<br>
Question 3<br>
<input type="radio" name="group3" value="Ans1" id="option5">Ans1<br>
<input type="radio" name="group3" value="Ans2" id="option6">Ans2<br>
<input type="submit" value="Test" onclick="validateForm();" />
</form>
</body>

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>

How to embed web-service reponse within the portlet that called it?

Apologies for starting another thread but I kind of solved the issue of my first thread but now I run into a different issue.
Background:
I have a portlet which takes 3 Parameters (Temperature,FromUnit,ToUnit) and passes them on to an external WebService located here:
http://www.webservicex.net/ConvertTemperature.asmx/ConvertTemp
I did not want the portlet to actually redirect to the URL of the webService and the only way to do that appeared to be AJAX using jquery which I have done now.
However I also want the response of the webService to be embedded in the same portlet that I used to call it and that's where I am having issues.
This is what I got so far, here is my portlet page:
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
<script src="http://localhost:8080/my-greeting-portlet/jquery.js"></script>
<script type="text/javascript" src="http://localhost:8080/my-greeting-portlet/js/script.js"></script>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# page import="javax.portlet.PortletPreferences" %>
<portlet:defineObjects />
<%
PortletPreferences prefs = renderRequest.getPreferences();
String Temperature = (String)prefs.getValue("Temperature","Temperature");
PortletPreferences prefs2 = renderRequest.getPreferences();
String FromUnit = (String)prefs2.getValue("FromUnit", "FromUnit");
PortletPreferences prefs3 = renderRequest.getPreferences();
String ToUnit = (String)prefs3.getValue("ToUnit","ToUnit");
%>
<portlet:renderURL var="editGreetingURL">
<portlet:param name="jspPage" value="/edit.jsp" />
</portlet:renderURL>
<div id="contact_form">
<form name="callWebService" id="callWebService" action="">
<fieldset>
<label for="Temperature" id="Temperature_label">Temperature </label>
<input type="text" name="Temperature" id="Temperature" size="30" value="" class="text-input" />
<label class="error" for="Temperature" id="Temperature_error">This field is required.</label>
<br />
<label for="FromUnit" id="FromUnit_label">From unit </label>
<input type="text" name="FromUnit" id="FromUnit" size="30" value="" class="text-input" />
<label class="error" for="FromUnit" id="FromUnit_error">This field is required.</label>
<br />
<label for="ToUnit" id="ToUnit_label">To Unit </label>
<input type="text" name="ToUnit" id="ToUnit" size="30" value="" class="text-input" />
<label class="error" for="ToUnit" id="ToUnit_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="submit" />
</fieldset>
</form>
</div>
</body>
</html>
And here is the jquery code:
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
var dataString = $("#callWebService").serialize();
// alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://www.webservicex.net/ConvertTemperature.asmx/ConvertTemp",
data: $("#callWebService").serialize(),
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
$('.error').hide();
var Temperature = $("#Temperature").val();
if (Temperature == "") {
$("#Temperature_error").show();
$("#Temperature").focus();
return false;
}
var FromUnit = $("input#FromUnit").val();
if (FromUnit == "") {
$("label#FromUnit_error").show();
$("input#FromUnit").focus();
return false;
}
var ToUnit = $("input#ToUnit").val();
if (ToUnit == "") {
$("label#ToUnit_error").show();
$("input#ToUnit").focus();
return false;
}
});
});
Everything seems to be working, or at least I do not get errors but it seems that this part of the code is completely ignored:
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
When I press the "submit" button nothing happens. No redirection to the webservice URL (good) but also the custom message defined above does not show up (bad). The screen remains exactly as it is.
When I uncomment the "alert" in the jquery code and the parameters are definitely picked up correctly and I would assume that they are being passed to the webService URL but nothing else is happening.
Is this because the webservice URL returns a response that overwrites my message or something like that?
How can I get the webService response embedded into the portlet?
Again, many thanks for looking at this, it is much appreciated!
You ran into a Cross Domain Scripting problem.
Read this and this to resolve the problem

Getting a response from Cfajaximport / ajax with coldfusion

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.

Resources