Ajax script not running on submit button click - ajax

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>

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.

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

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

Want to execute function when press enter key on text field

I have thi HTML:
<form id="form1" name="form1" method="post" action="">
<input name="PtName" type="text" id="PtName" />
<input name="Button" type="button" id="button" onclick="search_p()" value="Check" />
</form>
serach_p() is function:
<script type="text/javascript">
function search_p(){
$.ajax({
url: 'srchpt.php',
type: 'POST',
data: { PtName: $('#PtName').val()},
success: function(data){
$(".myresult").html(data);
}
})
}
</script>
I want when I press enter key in PtName text do same search_p() function
How can I do that?
Specify an onsubmit on your form:
<form ... onsubmit="search_p(); return false">
and change the type of your button to submit:
<input name="Button" type="submit" id="button" value="Check" />
you can do this by using following jquery function:
$("#PtName").keyup(function (e) {
if (e.keyCode == 13) {
// call function
}
});
Javascript :
In javascript put the following function
function enterPressed(event) {
var key;
if (window.event) {
key = window.event.keyCode; //IE
} else {
key = event.which; //firefox
}
if (key == 13) {
yourFunction();
// do whatever you want after enter pressed event. I have called a javascript function
}
}
HTML :
<input type="text" onkeypress="javascript:enterPressed(event)">
For required textfield put onkeypress event
Call your function on submit event of your form:-
<html>
<head>
<script type="text/javascript">
function search_p(){
$.ajax({
url: 'srchpt.php',
type: 'POST',
data: { PtName: $('#PtName').val()},
success: function(data){
$(".myresult").html(data);
}
})
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="" onsubmit="search_p()" >
<input name="PtName" type="text" id="PtName" />
<input name="Button" type="button" id="button" onclick="search_p()" value="Check" />
</form>
</body>
</html>
I wanted a textarea that would break-line on shift+enter, and on Enter would submit:
This seems to answer my query

jQuery ajaxSubmit ignored by IE8

I am combing the jQuery validation plug-in with the jQuery Form Plugin to submit the form via AJAX.
This works perfectly in Firefox & Chrome, but (as usual) Internet Explorer is being a pain. For reasons that are alluding me, IE is ignoring the ajaxSubmit, as a result it submits the form in the normal fashion.
I've followed the validation plug-in's documentation when constructing my code:
JS:
<script src="/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="/js/jquery.form.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var validator = $("#form_notify").validate({
messages: {
email: {
required: 'Please insert your email address. Without your email address we will not be able to contact you!',
email:'Please enter a <b>valid</b> email address. Without a valid email address we will not be able to contact you!'
}
},
errorLabelContainer: "#error",
success: "valid",
submitHandler: function(form) {$(form).ajaxSubmit();}
});
$('#email').blur(function() {
if (validator.numberOfInvalids() > 0) {
$("#label").addClass("label_error");
return false;
}
else {$("#label").removeClass("label_error");}
});
$('#form_notify').submit(function() {
if (validator.numberOfInvalids() == 0) {
$(this).fadeOut('fast', function() {$('#thank-you').fadeIn();});
return true;
}
return false;
});
});
</script>
Form HTML:
<form id="form_notify" class="cmxform" name="form_notify" action="optin.pl" method="get">
<fieldset>
<div class="input">
<label id="label" for="email">Email Address:</label>
<input type="text" id="email" name="email" value="" title="email address" class="{required:true, email:true}"/>
<div class="clearfix"></div>
</div>
<input type="hidden" name="key" value="sub-745-9.224;1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0;;subscribe-224.htm">
<input type="hidden" name="followup" value="19">
<input type="submit" name="submit" id="submit-button" value="Notify Me">
<div id="error"></div>
</fieldset>
</form>
I can't understand what is causing IE to act differently, any assistance would be greatly appreciated.
I can provide more information if needed.
Thanks in advance!
Try the following:
$('#form_notify').submit(function(e) {
e.preventDefault();
if (validator.numberOfInvalids() == 0) {
$(this).fadeOut('fast', function() {$('#thank-you').fadeIn();});
return true;
}
return false;
});

Resources